"""Modelos serializables para la capa de aplicación de carga individual."""

from __future__ import annotations

from typing import Any

from pydantic import BaseModel, ConfigDict, Field

from app.individual_ingestion.domain.models import (
    INGESTION_SOURCE_INDIVIDUAL,
    UPLOAD_STATUS_PRECHECK_EN_COLA,
)


def _string(value: Any, *, strip: bool = True) -> str:
    if value is None:
        return ""
    text = str(value)
    return text.strip() if strip else text


def _list_value(value: Any) -> list[Any]:
    return list(value or [])


def _bool_value(value: Any) -> bool:
    return bool(value)


class ApplicationModel(BaseModel):
    model_config = ConfigDict(extra="ignore")

    def to_document(self, *, exclude_none: bool = True) -> dict[str, Any]:
        return self.model_dump(mode="python", exclude_none=exclude_none)


class IndividualUploadCreatePayload(ApplicationModel):
    usuario: str
    original_name: str
    selected_document_type: str
    provided_case_key: str = ""
    status: str = UPLOAD_STATUS_PRECHECK_EN_COLA
    ingestion_source: str = INGESTION_SOURCE_INDIVIDUAL
    source_file_hash: str
    stored_path: str
    file_size: int = 0
    created_at: str
    updated_at: str
    detected_document_type: str = ""
    effective_document_type: str = ""
    extracted_text: str = ""
    pending_actions: list[str] = Field(default_factory=list)
    warnings: list[str] = Field(default_factory=list)
    contradictions: list[str] = Field(default_factory=list)
    impact_summary: list[str] = Field(default_factory=list)
    provisional_case_number: str = ""
    provisional_patient_id: str = ""
    provisional_patient_name: str = ""
    confirmed_case_number: str = ""
    confirmed_patient_id: str = ""
    confirmed_patient_name: str = ""
    case_key: str = ""
    selected_type_override_confirmed: bool = False
    case_override_confirmed: bool = False
    precheck_completed_at: str = ""
    materialization_started_at: str = ""
    completed_at: str = ""
    cancelled_at: str = ""
    failed_at: str = ""
    clinical_document_id: str = ""
    duplicate_of_upload_id: str = ""
    override_audit: dict[str, Any] = Field(default_factory=dict)
    error: str = ""
    audit_only: bool = False


class IndividualUploadUpdatePayload(ApplicationModel):
    status: str | None = None
    updated_at: str | None = None
    detected_document_type: str | None = None
    effective_document_type: str | None = None
    extracted_text: str | None = None
    pending_actions: list[str] | None = None
    warnings: list[str] | None = None
    contradictions: list[str] | None = None
    impact_summary: list[str] | None = None
    provisional_case_number: str | None = None
    provisional_patient_id: str | None = None
    provisional_patient_name: str | None = None
    confirmed_case_number: str | None = None
    confirmed_patient_id: str | None = None
    confirmed_patient_name: str | None = None
    case_key: str | None = None
    selected_type_override_confirmed: bool | None = None
    case_override_confirmed: bool | None = None
    precheck_completed_at: str | None = None
    materialization_started_at: str | None = None
    completed_at: str | None = None
    cancelled_at: str | None = None
    failed_at: str | None = None
    clinical_document_id: str | None = None
    duplicate_of_upload_id: str | None = None
    stored_path: str | None = None
    override_audit: dict[str, Any] | None = None
    error: str | None = None
    audit_only: bool | None = None


class IndividualUploadAcceptedView(ApplicationModel):
    upload_id: str
    status: str
    created_at: str
    poll_url: str
    duplicate: bool = False
    message: str = ""


class IndividualUploadStatusView(ApplicationModel):
    upload_id: str
    status: str
    selected_document_type: str
    detected_document_type: str = ""
    effective_document_type: str = ""
    provided_case_key: str = ""
    case_key: str = ""
    created_at: str = ""
    updated_at: str = ""
    pending_actions: list[str] = Field(default_factory=list)
    warnings: list[str] = Field(default_factory=list)
    contradictions: list[str] = Field(default_factory=list)
    impact_summary: list[str] = Field(default_factory=list)
    provisional_case_number: str = ""
    provisional_patient_id: str = ""
    provisional_patient_name: str = ""
    confirmed_case_number: str = ""
    confirmed_patient_id: str = ""
    confirmed_patient_name: str = ""
    selected_type_override_confirmed: bool = False
    case_override_confirmed: bool = False
    clinical_document_id: str = ""
    duplicate_of_upload_id: str = ""
    error: str = ""
    audit_only: bool = False

    @classmethod
    def from_record(cls, upload_id: str, item: dict[str, Any]) -> IndividualUploadStatusView:
        return cls(
            upload_id=upload_id,
            status=_string(item.get("status")) or UPLOAD_STATUS_PRECHECK_EN_COLA,
            selected_document_type=_string(item.get("selected_document_type")),
            detected_document_type=_string(item.get("detected_document_type")),
            effective_document_type=_string(
                item.get("effective_document_type")
                or item.get("detected_document_type")
                or item.get("selected_document_type")
            ),
            provided_case_key=_string(item.get("provided_case_key")),
            case_key=_string(item.get("case_key")),
            created_at=_string(item.get("created_at")),
            updated_at=_string(item.get("updated_at")),
            pending_actions=_list_value(item.get("pending_actions")),
            warnings=_list_value(item.get("warnings")),
            contradictions=_list_value(item.get("contradictions")),
            impact_summary=_list_value(item.get("impact_summary")),
            provisional_case_number=_string(item.get("provisional_case_number")),
            provisional_patient_id=_string(item.get("provisional_patient_id")),
            provisional_patient_name=_string(item.get("provisional_patient_name")),
            confirmed_case_number=_string(item.get("confirmed_case_number")),
            confirmed_patient_id=_string(item.get("confirmed_patient_id")),
            confirmed_patient_name=_string(item.get("confirmed_patient_name")),
            selected_type_override_confirmed=_bool_value(item.get("selected_type_override_confirmed")),
            case_override_confirmed=_bool_value(item.get("case_override_confirmed")),
            clinical_document_id=_string(item.get("clinical_document_id")),
            duplicate_of_upload_id=_string(item.get("duplicate_of_upload_id")),
            error=_string(item.get("error")),
            audit_only=_bool_value(item.get("audit_only")),
        )
