from __future__ import annotations

from dataclasses import dataclass
from datetime import UTC, datetime

from app.case_epicrisis.domain.models import (
    EpicrisisEvidenceSnapshot,
    EpicrisisRuleEvaluation,
    EpicrisisRuleEvaluationMode,
    EpicrisisRuleFinding,
    EpicrisisRuleSeverity,
    EpicrisisRuleStatus,
)


def _utcnow() -> datetime:
    return datetime.now(UTC)


@dataclass
class HistoriaClinicaRequiredRule:
    rule_code: str = "EPICRISIS-HC-001"

    def evaluate(self, snapshot: EpicrisisEvidenceSnapshot) -> EpicrisisRuleEvaluation:
        checked_documents = list(snapshot.document_types_available)
        has_historia_clinica = "historia_clinica" in checked_documents
        observed_value = {
            "document_types_available": checked_documents,
            "has_historia_clinica": has_historia_clinica,
        }
        if has_historia_clinica:
            return EpicrisisRuleEvaluation(
                status=EpicrisisRuleStatus.PASSED,
                generation_allowed=True,
                ready_for_epicrisis=True,
                findings=[
                    EpicrisisRuleFinding(
                        rule_code=self.rule_code,
                        severity=EpicrisisRuleSeverity.INFO,
                        message="El caso cuenta con historia clínica disponible.",
                        document_types_checked=checked_documents,
                        observed_value=observed_value,
                        blocking=False,
                    )
                ],
                required_documents=[],
                missing_documents=[],
                evaluated_at=_utcnow(),
                evaluation_mode=EpicrisisRuleEvaluationMode.DETERMINISTIC_ONLY,
            )

        return EpicrisisRuleEvaluation(
            status=EpicrisisRuleStatus.BLOCKED,
            generation_allowed=False,
            ready_for_epicrisis=False,
            findings=[
                EpicrisisRuleFinding(
                    rule_code=self.rule_code,
                    severity=EpicrisisRuleSeverity.ERROR,
                    message="No se puede generar la epicrisis sin historia clínica.",
                    document_types_checked=checked_documents,
                    observed_value=observed_value,
                    blocking=True,
                )
            ],
            required_documents=["historia_clinica"],
            missing_documents=["historia_clinica"],
            evaluated_at=_utcnow(),
            evaluation_mode=EpicrisisRuleEvaluationMode.DETERMINISTIC_ONLY,
        )
