from __future__ import annotations

from app.modules.shared.gigachat.client import GigaChatClient
from app.modules.shared.gigachat.settings import GigaChatSettings
from app.modules.shared.gigachat.token_provider import GigaChatTokenProvider
from tests.pipeline_setup.suite_02_pipeline.pipeline_intent_rag.helpers.answer_quality import AnswerQualityController
from tests.pipeline_setup.suite_02_pipeline.pipeline_intent_rag.helpers.prompt_payload_builder import PromptPayloadBuilder


class GigaChatAnswerer:
    _SYSTEM_PROMPT = "Ты технический ассистент по коду и документации."
    _PROMPT_TEMPLATE_ID = "pipeline_intent_rag_v1"
    _SYSTEM_PROMPT_VERSION = "v1"
    _TASK_PROMPT = "Дай краткий, практичный ответ по контексту. Если данных мало, явно скажи об этом."

    def __init__(self) -> None:
        settings = GigaChatSettings.from_env()
        if not settings.credentials:
            raise ValueError("GIGACHAT_TOKEN is required for full_chain mode")
        self._client = GigaChatClient(settings, GigaChatTokenProvider(settings))
        self._payload_builder = PromptPayloadBuilder()
        self._quality = AnswerQualityController()

    def answer(
        self,
        query: str,
        rag_rows: list[dict],
        *,
        prompt_template: dict | None = None,
        sub_intent: str | None = None,
    ) -> str:
        prompt_payload = self.build_prompt_payload(
            query,
            rag_rows,
            prompt_template=prompt_template,
            sub_intent=sub_intent,
        )
        return self.answer_from_payload(prompt_payload)

    def build_prompt_payload(
        self,
        query: str,
        rag_rows: list[dict],
        *,
        prompt_template: dict | None = None,
        sub_intent: str | None = None,
    ) -> dict:
        return self._payload_builder.build(
            query,
            rag_rows,
            prompt_template=prompt_template,
            sub_intent=sub_intent,
            default_system_prompt=self._SYSTEM_PROMPT,
            default_task_prompt=self._TASK_PROMPT,
            default_template_id=self._PROMPT_TEMPLATE_ID,
            system_prompt_version=self._SYSTEM_PROMPT_VERSION,
        )

    def answer_from_payload(self, payload: dict) -> str:
        answer = self._client.complete(
            system_prompt=str(payload.get("system_prompt") or self._SYSTEM_PROMPT),
            user_prompt=str(payload.get("user_prompt") or ""),
        )
        return self._quality.refine(answer, sub_intent=str(payload.get("sub_intent") or "").strip() or None)
