from __future__ import annotations

from inspect import signature

from sqlalchemy.orm import Session

from app.models.chat import ChatMessage
from app.models.user import User
from app.services.feishu_async_service import AsyncFeishuKnowledgeService
from app.services.knowledge_service import KnowledgeAccessService
from app.services.rag_service import PromptService, RagResult


class AsyncRagService:
    @staticmethod
    async def build_result(
        db: Session,
        user: User,
        question: str,
        history: list[ChatMessage] | None = None,
        session_summary: str | None = None,
    ) -> RagResult:
        scopes = KnowledgeAccessService.get_allowed_knowledge(db, user)
        chunks = await AsyncFeishuKnowledgeService.retrieve(question, scopes, db)
        prompt = _build_prompt(db, question, chunks, history, session_summary)
        return RagResult(question=question, knowledge_scopes=scopes, chunks=chunks, prompt=prompt)


def _build_prompt(
    db: Session,
    question: str,
    chunks,
    history: list[ChatMessage] | None,
    session_summary: str | None,
) -> str:
    parameters = signature(PromptService.build_prompt).parameters
    if "history" in parameters:
        return PromptService.build_prompt(db, question, chunks, history, session_summary)
    return PromptService.build_prompt(db, question, chunks)
