from __future__ import annotations

from sqlalchemy import text

from fastapi_common.fastapi_common_sqlalchemy.database import GetAsyncSession

from fastapi_modules.fastapi_leaudit.domian.vo.ragDatasetVo import RagDatasetItemVO, RagDatasetPageVO
from fastapi_modules.fastapi_leaudit.services.ragDatasetService import IRagDatasetService


class RagDatasetServiceImpl(IRagDatasetService):
    async def GetMyDatasets(self, CurrentUserId: int, UserArea: str | None, UserRole: str | None) -> RagDatasetPageVO:
        async with GetAsyncSession() as session:
            rows = (
                await session.execute(
                    text(
                        """
                        SELECT id, name, description, area, is_public, is_default, document_count, total_chunks, status
                        FROM rag_dataset
                        WHERE deleted_at IS NULL
                          AND status = 1
                          AND (
                            :is_provincial = TRUE
                            OR area IN (:user_area, '省级', '')
                            OR is_public = TRUE
                          )
                        ORDER BY sort_order ASC, created_at DESC
                        """
                    ),
                    {
                        "is_provincial": UserRole == "provincial_admin",
                        "user_area": UserArea or "",
                    },
                )
            ).mappings().all()
        return RagDatasetPageVO(
            data=[
                RagDatasetItemVO(
                    id=row["id"],
                    name=row["name"],
                    description=row.get("description") or "",
                    area=row.get("area") or "",
                    isPublic=bool(row.get("is_public")),
                    isDefault=bool(row.get("is_default")),
                    documentCount=row.get("document_count") or 0,
                    totalChunks=row.get("total_chunks") or 0,
                    status=row.get("status") or 1,
                )
                for row in rows
            ],
            total=len(rows),
        )
