from app.llm.schemas import HistoriaClinicaStructured
from app.services.clinical_extraction_quality import assess_clinical_extraction
from app.services.historia_summary import (
    calculate_historia_summary_policy,
    choose_historia_resumen,
)


def _long_source() -> str:
    return " ".join(
        [
            "Motivo de consulta por trauma y dolor intenso.",
            "Se documentan diagnósticos y hallazgos clínicos.",
            "Se realizan ayudas diagnósticas de laboratorio e imagenología.",
            "Se efectúa procedimiento y se administra tratamiento farmacológico.",
            "La evolución es estable, con egreso y plan de seguimiento.",
        ]
        * 1200
    )


def test_long_history_uses_proportional_policy_and_complete_sentences() -> None:
    source = _long_source()
    policy = calculate_historia_summary_policy(source)
    detailed = " ".join(
        f"La evolución documenta diagnóstico y tratamiento completos en la fecha {index}."
        for index in range(100)
    )

    result = choose_historia_resumen("Resumen corto", detailed_candidate=detailed, raw_text=source)

    assert policy.is_long is True
    assert policy.target_words == 700
    assert policy.acceptable_min_words == 595
    assert len(result.split()) <= 700
    assert len(result.split()) >= 595
    assert not result.endswith((" y", " con", " de", " para"))


def test_identity_is_removed_but_clinical_context_remains() -> None:
    source = "Nombre del paciente: ANA MARIA TEST. Documento: CC 12345678. Caso: CASE-2026."
    result = choose_historia_resumen(
        "ANA MARIA TEST ingresa por dolor abdominal. Caso CASE-2026, documento 12345678.",
        raw_text=source,
        patient_name="ANA MARIA TEST",
        patient_id="12345678",
        case_number="CASE-2026",
    )

    assert "ANA MARIA TEST" not in result
    assert "12345678" not in result
    assert "CASE-2026" not in result
    assert "dolor abdominal" in result


def test_identification_phrase_is_removed_after_patient_id_sanitization() -> None:
    patient_id = "12345678"
    result = choose_historia_resumen(
        f"Paciente identificado con CC {patient_id} - ingresa por dolor abdominal y náuseas.",
        raw_text=f"Documento: CC {patient_id}.",
        patient_id=patient_id,
    )

    assert "identificado con CC" not in result.lower()
    assert patient_id not in result
    assert "dolor abdominal y náuseas" in result


def test_v2_quality_flags_short_long_history_summary() -> None:
    source = _long_source()
    model = HistoriaClinicaStructured.model_validate(
        {"rs": "Paciente con trauma y manejo clínico."}
    )

    quality = assess_clinical_extraction(
        document_type="historia_clinica", raw_text=source, analysis_model=model
    )

    assert quality.validator_version == "v4"
    assert "summary_too_short_for_source" in quality.reason_codes
