# grantflow/core/strategies/fcdo.py

from __future__ import annotations

from typing import Type

from pydantic import BaseModel, Field

from grantflow.core.donor_strategy import DonorStrategy


class FCDO_LogframeOutput(BaseModel):
    output_id: str = Field(description="Output identifier (e.g. Output 1)")
    title: str = Field(description="Output title")
    description: str = Field(description="What will be produced or delivered")
    activities: list[str] = Field(default_factory=list, description="Key activities under this output")


class FCDO_LogframeOutcome(BaseModel):
    outcome_id: str = Field(description="Outcome identifier (e.g. Outcome 1)")
    title: str = Field(description="Outcome title")
    description: str = Field(description="Medium-term change expected from outputs")
    outputs_linked: list[str] = Field(default_factory=list, description="Output IDs that feed this outcome")


class FCDO_TOC(BaseModel):
    impact_statement: str = Field(description="High-level impact: long-term change the programme contributes to")
    outcome_statement: str = Field(description="Primary outcome: medium-term change the programme is accountable for")
    outputs: list[FCDO_LogframeOutput] = Field(default_factory=list)
    outcomes: list[FCDO_LogframeOutcome] = Field(default_factory=list)
    assumptions: list[str] = Field(
        default_factory=list,
        description="Logframe assumptions at each level (output→outcome→impact)",
    )
    risks: list[str] = Field(default_factory=list, description="Key programme risks")
    value_for_money_rationale: str = Field(
        description=(
            "VfM rationale covering Economy, Efficiency, Effectiveness, and Equity (4Es). "
            "Required for all FCDO Business Cases."
        )
    )
    safeguarding_considerations: str = Field(description="Summary of safeguarding risks and mitigation measures")


class FCDO_MELIndicator(BaseModel):
    indicator_id: str = Field(description="Indicator identifier (aligned with logframe row)")
    name: str = Field(description="Indicator title")
    logframe_level: str = Field(
        description="Logframe level: Impact / Outcome / Output",
    )
    oecd_dac_criterion: str | None = Field(
        default=None,
        description="Relevant OECD DAC criterion: Relevance, Effectiveness, Efficiency, Impact, Sustainability, Coherence",
    )
    means_of_verification: str = Field(description="Data source and collection method")
    justification: str = Field(description="Why this indicator captures the intended change")
    citation: str = Field(description="Source reference from FCDO guidance corpus")
    baseline: str = Field(description="Baseline value")
    target: str = Field(description="Target value at programme end")
    disaggregation: str | None = Field(default=None, description="Disaggregation dimensions (e.g. sex, age, geography)")
    evidence_excerpt: str | None = Field(default=None, description="Optional grounded excerpt")


class FCDO_MELDraft(BaseModel):
    indicators: list[FCDO_MELIndicator] = Field(default_factory=list)


class FCDOStrategy(DonorStrategy):
    donor_id: str = "FCDO"

    def get_toc_schema(self) -> Type[FCDO_TOC]:
        return FCDO_TOC

    def get_rag_collection(self) -> str:
        return "fcdo_guidance"

    def get_mel_schema(self) -> Type[FCDO_MELDraft]:
        return FCDO_MELDraft

    def get_system_prompts(self) -> dict:
        return {
            "Architect": (
                "You are an FCDO proposal architect. Structure the Theory of Change using FCDO logframe "
                "conventions: Impact → Outcome → Outputs → Activities. "
                "Every level must have explicit assumptions. "
                "Include a Value for Money rationale covering Economy, Efficiency, Effectiveness, and Equity (4Es). "
                "Address safeguarding risks as required by FCDO Smart Rules. "
                "Use OECD DAC criteria (Relevance, Effectiveness, Efficiency, Impact, Sustainability, Coherence) "
                "to frame the programme logic."
            ),
            "MEL_Specialist": (
                "You are an FCDO monitoring and evaluation specialist. Use only the 'fcdo_guidance' RAG namespace. "
                "Draft SMART indicators aligned to the logframe (Impact / Outcome / Output level). "
                "For each indicator specify: means of verification, baseline, target, disaggregation dimensions, "
                "and the relevant OECD DAC criterion. "
                "Cite FCDO Smart Guide, logframe guidance, or DFID/FCDO evaluation standards for each indicator."
            ),
            "Red_Team_Critic": (
                "You are a strict FCDO reviewer. Apply the following checks: "
                "(1) Logframe coherence — do outputs plausibly lead to outcomes and impact? "
                "(2) Assumptions — are they explicit and realistic at each level? "
                "(3) VfM — does the 4Es rationale hold under scrutiny? "
                "(4) Safeguarding — are risks identified and mitigation measures concrete? "
                "(5) OECD DAC alignment — is each criterion addressed in the MEL framework? "
                "Penalise vague impact statements, missing assumptions, weak VfM rationale, "
                "and indicators without clear means of verification."
            ),
        }
