from __future__ import annotations

from grantflow.swarm.nodes import mel_specialist as mel_module


def test_mel_formula_prefers_institution_logic_over_people_logic():
    assert (
        mel_module._default_indicator_formula(
            "Strengthen institutional capacity for youth employment and SME skills delivery",
            result_level="outcome",
            donor_id="eu",
        )
        == "Count of institutions adopting verified service quality or administrative procedures"
    )


def test_mel_formula_is_donor_shaped_for_worldbank_and_state_department():
    wb_formula = mel_module._default_indicator_formula(
        "Improve public sector service performance across pilot agencies",
        result_level="impact",
        donor_id="worldbank",
    )
    state_formula = mel_module._default_indicator_formula(
        "Improve independent media resilience outcomes in Georgia",
        result_level="impact",
        donor_id="state_department",
    )

    assert wb_formula == "Count of institutions achieving verified service-performance improvements"
    assert state_formula == "Count of organizations implementing verified resilience or protection practices"


def test_mel_deterministic_justification_is_donor_shaped():
    usaid_text = mel_module._deterministic_indicator_justification(
        donor_id="usaid",
        statement_path="toc.development_objectives[0].description",
        result_level="outcome",
        statement="Civil servants apply AI-assisted service workflows in daily operations.",
    )
    eu_text = mel_module._deterministic_indicator_justification(
        donor_id="eu",
        statement_path="toc.specific_objectives[0].title",
        result_level="outcome",
        statement="Improve youth employment service delivery across target municipalities.",
    )
    wb_text = mel_module._deterministic_indicator_justification(
        donor_id="worldbank",
        statement_path="toc.objectives[0].title",
        result_level="impact",
        statement="Improve public sector service performance across pilot agencies.",
    )

    assert "usaid-style performance indicator" in usaid_text.lower()
    assert "pmp-oriented" in usaid_text.lower()
    assert "outcome-level change" in usaid_text.lower()
    assert "eu intervention-logic indicator" in eu_text.lower()
    assert "implementation-evidence intent" in eu_text.lower()
    assert "world bank-style results framework indicator" in wb_text.lower()
    assert "impact-level change" in wb_text.lower()


def test_indicator_name_from_toc_statement_prefers_compact_result_label():
    name = mel_module._indicator_name_from_toc_statement(
        "Improve digital service quality in municipal agencies.",
        idx=0,
        result_level="impact",
    )

    assert name == "Impact: Improved digital service quality in municipal agencies"


def test_indicator_name_from_toc_statement_strips_boilerplate_narrative():
    name = mel_module._indicator_name_from_toc_statement(
        "Responsible AI Skills for Civil Service Modernization intervention delivers measurable change in Kazakhstan through structured implementation and review cycles. Evidence hint: present.",
        idx=0,
        result_level="outcome",
    )

    assert "evidence hint" not in name.lower()
    assert "structured implementation and review cycles" not in name.lower()
    assert "results delivered" not in name.lower()
    assert "measurable change" not in name.lower()
    assert "eviden" not in name.lower()


def test_suggest_baseline_target_prefers_formula_unit_over_generic_name():
    baseline, target = mel_module._suggest_baseline_target(
        indicator_name="Outcome: Improved operational execution and accountability in public sector performance",
        input_context={"project": "Public Sector Performance", "country": "Uzbekistan"},
        idx=1,
        donor_id="worldbank",
        result_level="outcome",
        formula="Count of institutions achieving verified service-performance improvements",
    )

    assert baseline == "0 institutions"
    assert target == "8 institutions"


def test_indicator_from_hit_aligns_baseline_target_with_formula_unit():
    indicator = mel_module._indicator_from_hit(
        {
            "name": "Outcome: Improved operational execution and accountability in public sector performance",
            "formula": "Count of institutions achieving verified service-performance improvements",
            "result_level": "outcome",
            "excerpt": "ISR and aide-memoire evidence",
            "source": "worldbank_ads301",
        },
        idx=1,
        namespace="worldbank_ads301",
        donor_id="worldbank",
        input_context={"project": "Public Sector Performance", "country": "Uzbekistan"},
    )

    assert indicator["baseline"] == "0 institutions"
    assert indicator["target"] == "8 institutions"


def test_deterministic_definition_from_statement_is_donor_shaped():
    usaid_definition = mel_module._deterministic_definition_from_statement(
        donor_id="usaid",
        result_level="outcome",
        statement="Improve digital service quality in municipal agencies.",
        indicator_name="Outcome: Improved digital service quality in municipal agencies",
    )
    wb_definition = mel_module._deterministic_definition_from_statement(
        donor_id="worldbank",
        result_level="impact",
        statement="Improve public sector service performance across pilot agencies.",
        indicator_name="Impact: Improved public sector service performance across pilot agencies",
    )

    assert "tracks digital service quality" in usaid_definition.lower()
    assert "usaid performance result" in usaid_definition.lower()
    assert "project development objective-style result" in wb_definition.lower()
    assert "public sector service performance" in wb_definition.lower()


def test_mel_worldbank_defaults_are_results_framework_shaped():
    indicator = mel_module._apply_indicator_defaults(
        {
            "indicator_id": "IND_001",
            "name": "Improve public sector service performance across pilot agencies",
            "justification": "stub",
            "citation": "stub",
        },
        donor_id="worldbank",
        toc_statement_path="toc.project_development_objective",
    )

    assert "world bank-style results framework" in str(indicator["definition"]).lower()
    assert "isr" in str(indicator["means_of_verification"]).lower()
    assert "results lead" in str(indicator["owner"]).lower()
    assert "results framework updates" in str(indicator["data_source"]).lower()


def test_mel_usaid_and_eu_defaults_are_review_ready_shaped():
    usaid_item = mel_module._apply_indicator_defaults(
        {
            "indicator_id": "IND_001",
            "name": "Improve service coverage adoption across target districts",
            "justification": "stub",
            "citation": "stub",
        },
        donor_id="usaid",
        toc_statement_path="toc.development_objectives[0].description",
    )
    eu_item = mel_module._apply_indicator_defaults(
        {
            "indicator_id": "IND_002",
            "name": "Strengthen institutional service adoption performance",
            "justification": "stub",
            "citation": "stub",
        },
        donor_id="eu",
        toc_statement_path="toc.specific_objectives[0].title",
    )

    assert "spot-check verification" in str(usaid_item["definition"]).lower()
    assert "verification spot-checks" in str(usaid_item["data_source"]).lower()
    assert "cor-aligned activity team" in str(usaid_item["owner"]).lower()
    assert "pmp records" in str(usaid_item["means_of_verification"]).lower()
    assert "service-standard checks" in str(eu_item["definition"]).lower()
    assert "intervention logic tracking tables" in str(eu_item["data_source"]).lower()
    assert "intervention logic lead" in str(eu_item["owner"]).lower()
    assert "means of verification annexes" in str(eu_item["means_of_verification"]).lower()


def test_mel_state_department_defaults_are_media_resilience_shaped():
    indicator = mel_module._apply_indicator_defaults(
        {
            "indicator_id": "IND_001",
            "name": "Strengthen independent media resilience among local newsrooms",
            "justification": "stub",
            "citation": "stub",
        },
        donor_id="state_department",
        toc_statement_path="toc.project_goal",
    )

    assert "independent-media resilience evidence" in str(indicator["definition"]).lower()
    assert "editorial risk logs" in str(indicator["means_of_verification"]).lower()
    assert "safeguarding notes" in str(indicator["means_of_verification"]).lower()
    assert "media partner leads" in str(indicator["owner"]).lower()
    assert "partner risk reviews" in str(indicator["data_source"]).lower()


def test_mel_state_department_civic_defaults_are_rights_and_governance_shaped():
    indicator = mel_module._apply_indicator_defaults(
        {
            "indicator_id": "IND_002",
            "name": "Strengthen civic accountability and information integrity practices",
            "justification": "stub",
            "citation": "stub",
        },
        donor_id="state_department",
        toc_statement_path="toc.objectives[0].expected_change",
    )

    assert "civic-actor monitoring evidence" in str(indicator["definition"]).lower()
    assert "stakeholder verification" in str(indicator["means_of_verification"]).lower()
    assert "information-integrity review notes" in str(indicator["means_of_verification"]).lower()
    assert "civic engagement leads" in str(indicator["owner"]).lower()
    assert "civic risk reviews" in str(indicator["data_source"]).lower()
    assert (
        indicator["formula"] == "Count of organizations implementing verified civic or information-integrity practices"
    )


def test_mel_un_agencies_defaults_are_programme_shaped():
    indicator = mel_module._apply_indicator_defaults(
        {
            "indicator_id": "IND_001",
            "name": "Improve education access for vulnerable children across target schools",
            "justification": "stub",
            "citation": "stub",
        },
        donor_id="un_agencies",
        toc_statement_path="toc.expected_outcomes[0].title",
    )

    assert "un programme result" in str(indicator["definition"]).lower()
    assert "education monitoring datasets" in str(indicator["data_source"]).lower()
    assert "sector coordination lead" in str(indicator["owner"]).lower()
    assert "sector review documentation" in str(indicator["means_of_verification"]).lower()
    assert indicator["formula"] == "Count of institutions/facilities meeting verified programme delivery criteria"
    assert indicator["disaggregation"] == ["sex", "age", "location"]


def test_mel_un_agencies_retrieval_text_is_programme_shaped():
    justification = mel_module._retrieval_indicator_justification(
        donor_id="un_agencies",
        namespace="un_agencies_guidance",
        toc_statement_path="toc.expected_outcomes[0].title",
        result_level="outcome",
        indicator_name="Schools implementing verified learning continuity standards",
    )
    definition = mel_module._retrieval_definition_from_hit(
        donor_id="un_agencies",
        namespace="un_agencies_guidance",
        toc_statement_path="toc.expected_outcomes[0].title",
        result_level="outcome",
        indicator_name="Schools implementing verified learning continuity standards",
        excerpt="Cluster and field monitoring evidence",
        source="un_agencies_guidance",
    )

    assert "un programme monitoring" in justification.lower()
    assert "partner reporting" in justification.lower()
    assert "sector-review use" in justification.lower()
    assert "un programme result" in definition.lower()
    assert "inter-agency review evidence" in definition.lower()


def test_statement_focus_phrase_prefers_domain_specific_phrases():
    assert (
        mel_module._statement_focus_phrase("Improve digital governance performance and accountability in Moldova.")
        == "digital governance performance"
    )
    assert (
        mel_module._statement_focus_phrase("Improve public sector performance and service delivery in Uzbekistan.")
        == "public sector performance & service delivery"
    )
    assert (
        mel_module._statement_focus_phrase("Improve inclusive education recovery outcomes in Nepal.")
        == "inclusive education recovery"
    )


def test_mel_giz_defaults_include_implementation_validation():
    indicator = mel_module._apply_indicator_defaults(
        {
            "indicator_id": "IND_001",
            "name": "Strengthen SME resilience and continuity planning",
            "justification": "stub",
            "citation": "stub",
        },
        donor_id="giz",
        toc_statement_path="toc.expected_outcomes[0].title",
    )

    assert "implementation validation" in str(indicator["definition"]).lower()
    assert "implementation leads" in str(indicator["owner"]).lower()
    assert "sustainability focal points" in str(indicator["owner"]).lower()
    assert "adaptive implementation review notes" in str(indicator["means_of_verification"]).lower()
