from __future__ import annotations

from datetime import datetime
from typing import Any

from app.llm.renderers import render_clinical_document_html
from app.llm.schemas import ClinicalStructuredModel, dump_clinical_model, get_clinical_document_model


def validate_structured_document(
    document_type: str,
    payload: dict[str, Any] | ClinicalStructuredModel | None,
) -> ClinicalStructuredModel | None:
    if payload is None:
        return None
    if isinstance(payload, ClinicalStructuredModel):
        return payload
    model_cls = get_clinical_document_model(document_type)
    return model_cls.model_validate(payload)


def dump_structured_document(
    document_type: str,
    payload: dict[str, Any] | ClinicalStructuredModel | None,
) -> dict[str, Any] | None:
    model = validate_structured_document(document_type, payload)
    if model is None:
        return None
    return dump_clinical_model(model)


def render_document_analysis_html(document: dict[str, Any] | None) -> str:
    if not isinstance(document, dict):
        return ""
    analysis_structured = document.get("analysis_structured")
    if isinstance(analysis_structured, dict):
        model = validate_structured_document(
            str(
                document.get("tipo_documento")
                or document.get("document_type")
                or analysis_structured.get("dt")
                or ""
            ),
            analysis_structured,
        )
        if model is not None:
            return render_clinical_document_html(
                model,
                redacted_identity_fields=document.get("redacted_identity_fields") or (),
            )
    return str(document.get("analisis_html") or document.get("analisis") or "")


def get_structured_document_model(document: dict[str, Any] | None) -> ClinicalStructuredModel | None:
    if not isinstance(document, dict):
        return None
    payload = document.get("analysis_structured")
    if not isinstance(payload, dict):
        return None
    return validate_structured_document(
        str(document.get("tipo_documento") or document.get("document_type") or payload.get("dt") or ""),
        payload,
    )


def serialize_analysis_document(doc: dict[str, Any] | None) -> dict[str, Any] | None:
    if not doc:
        return None
    serialized = dict(doc)
    if serialized.get("_id") is not None:
        serialized["_id"] = str(serialized["_id"])
    if "fecha_analisis" in serialized and isinstance(serialized["fecha_analisis"], datetime):
        serialized["fecha_analisis"] = serialized["fecha_analisis"].isoformat()
    structured = serialized.get("analysis_structured")
    if isinstance(structured, dict):
        serialized["analysis_structured"] = dump_structured_document(
            str(serialized.get("tipo_documento") or structured.get("dt") or ""),
            structured,
        )
        serialized["analisis_html"] = render_document_analysis_html(serialized)
    return serialized
