from __future__ import annotations

from typing import Any

from app.case_epicrisis.application.utils import refresh_diagnostico_context
from app.core.logging import get_audit_logger
from app.services.soat_processing import (
    _construir_soat_y_glosa,
    generar_codigos_desde_soat_con_gemini,
)


class ServicesEpicrisisCodingGateway:
    def __init__(
        self,
        *,
        client_groq: Any,
        client_gemini: Any,
        soat_retriever: Any,
        cie10_retriever: Any,
        llm_router: Any = None,
        llm_task_cache_repository: Any = None,
    ):
        self.audit_logger = get_audit_logger()
        self.client_groq = client_groq
        self.client_gemini = client_gemini
        self.soat_retriever = soat_retriever
        self.cie10_retriever = cie10_retriever
        self.llm_router = llm_router
        self.llm_task_cache_repository = llm_task_cache_repository

    def build_soat_and_glosa(
        self,
        *,
        historia_html: str | None,
        qx_html: str | None,
    ) -> tuple[list[dict[str, Any]], str]:
        return _construir_soat_y_glosa(
            historia_html=historia_html or "",
            qx_html=qx_html or "",
            soat_retriever=self.soat_retriever,
            client_groq=self.client_groq,
            llm_router=self.llm_router,
        )

    def generate_codes_from_descriptions(
        self,
        descriptions: list[dict[str, str]],
    ) -> list[dict[str, Any]]:
        if not descriptions:
            return []
        return generar_codigos_desde_soat_con_gemini(
            descriptions,
            client_gemini=self.client_gemini,
            llm_router=self.llm_router,
            cache_repository=self.llm_task_cache_repository,
        )

    def generate_qx_results(
        self,
        *,
        hallazgos: str,
        descripcion_procedimiento: str,
    ) -> list[dict[str, Any]]:
        hallazgos = str(hallazgos or "").strip()
        descripcion_procedimiento = str(descripcion_procedimiento or "").strip()
        if not hallazgos and not descripcion_procedimiento:
            return []
        partes = []
        if hallazgos:
            partes.append(f"Hallazgos quirurgicos: {hallazgos}")
        if descripcion_procedimiento:
            partes.append(f"Descripcion del procedimiento: {descripcion_procedimiento}")
        descripcion_agente = " | ".join(partes).strip()[:1800]
        results = generar_codigos_desde_soat_con_gemini(
            [{"codigo_soat": "QX-HALLAZGOS", "descripcion": descripcion_agente}],
            client_gemini=self.client_gemini,
            llm_router=self.llm_router,
            cache_repository=self.llm_task_cache_repository,
        )
        return [
            {**item, "fuente": "agente_hallazgos_qx"}
            for item in results
            if isinstance(item, dict) and not item.get("error")
        ]

    def refresh_diagnostico_context(self, context: dict[str, Any]) -> dict[str, Any]:
        refreshed = refresh_diagnostico_context(context, retriever=self.cie10_retriever)
        self.audit_logger.business_event(
            event_type="epicrisis.diagnostico_context_refreshed",
            action="refresh_diagnostico_context",
            outcome="success",
            service="services_epicrisis_gateway",
        )
        return refreshed
