from __future__ import annotations

from dataclasses import dataclass
from datetime import UTC, datetime

from sqlalchemy import select
from sqlalchemy.orm import Session

from app.core.config import get_settings
from app.models.knowledge import Knowledge, UserKnowledgePermission
from app.models.user import User


@dataclass(frozen=True)
class KnowledgeScope:
    id: int
    name: str
    feishu_space_id: str
    feishu_node_id: str
    is_mock: bool = False


class KnowledgeAccessService:
    @staticmethod
    def get_allowed_knowledge(db: Session, user: User) -> list[KnowledgeScope]:
        now = datetime.now(UTC).replace(tzinfo=None)
        rows = db.execute(
            select(Knowledge)
            .join(UserKnowledgePermission, UserKnowledgePermission.knowledge_id == Knowledge.id)
            .where(
                UserKnowledgePermission.user_id == user.id,
                Knowledge.status == 1,
                (UserKnowledgePermission.effective_at.is_(None))
                | (UserKnowledgePermission.effective_at <= now),
                (UserKnowledgePermission.expired_at.is_(None))
                | (UserKnowledgePermission.expired_at >= now),
            )
            .order_by(Knowledge.id.asc())
        ).scalars()
        scopes = [
            KnowledgeScope(
                id=knowledge.id,
                name=knowledge.name,
                feishu_space_id=knowledge.feishu_space_id,
                feishu_node_id=knowledge.feishu_node_id,
            )
            for knowledge in rows
        ]
        if scopes or not get_settings().mock_rag_enabled:
            return scopes

        return [
            KnowledgeScope(
                id=0,
                name="开发阶段默认知识库",
                feishu_space_id="mock-space",
                feishu_node_id="mock-node",
                is_mock=True,
            )
        ]
