# grantflow/core/strategies/jica.py

from __future__ import annotations

from typing import Type

from pydantic import BaseModel, Field

from grantflow.core.donor_strategy import DonorStrategy


class JICA_Output(BaseModel):
    output_id: str = Field(description="Output identifier (e.g. Output 1)")
    title: str = Field(description="Output title")
    description: str = Field(description="Tangible deliverable produced by the project")
    activities: list[str] = Field(default_factory=list, description="Key activities under this output")
    japanese_expertise: str | None = Field(
        default=None,
        description="Japanese technology, methodology, or expertise applied in this output",
    )


class JICA_PDM(BaseModel):
    overall_goal: str = Field(
        description=(
            "Overall Goal (上位目標): the broader development objective the project "
            "contributes to beyond direct accountability"
        )
    )
    project_purpose: str = Field(
        description=(
            "Project Purpose (プロジェクト目標): the primary change the project is "
            "directly responsible for achieving"
        )
    )
    outputs: list[JICA_Output] = Field(default_factory=list)
    important_assumptions: list[str] = Field(
        default_factory=list,
        description=(
            "Important Assumptions (重要な前提条件) at each PDM level. "
            "JICA PCM methodology requires explicit assumptions for each causal link."
        ),
    )
    risks: list[str] = Field(default_factory=list, description="Key risks and mitigation measures")
    japanese_oda_rationale: str = Field(
        description=(
            "Why Japanese ODA is appropriate for this project. "
            "Should reference Japan's Country Assistance Policy or sector expertise."
        )
    )
    technology_transfer_plan: str = Field(
        description=(
            "Plan for transferring Japanese technology, knowledge, or methodology "
            "to local counterparts. JICA emphasises sustainable capacity development."
        )
    )
    counterpart_capacity: str = Field(description="Assessment of counterpart institution capacity and commitment")


class JICA_MELIndicator(BaseModel):
    indicator_id: str = Field(description="Indicator identifier (aligned with PDM row)")
    name: str = Field(description="Indicator title")
    pdm_level: str = Field(description="PDM level: Overall Goal / Project Purpose / Output")
    means_of_verification: str = Field(description="Data source and verification method")
    responsible_party: str | None = Field(
        default=None, description="Institution responsible for data collection (JICA or counterpart)"
    )
    justification: str = Field(description="Why this indicator measures the intended change")
    citation: str = Field(description="Source reference from JICA guidance corpus")
    baseline: str = Field(description="Baseline value")
    target: str = Field(description="Target value at project completion")
    evidence_excerpt: str | None = Field(default=None, description="Optional grounded excerpt")


class JICA_MELDraft(BaseModel):
    indicators: list[JICA_MELIndicator] = Field(default_factory=list)


class JICAStrategy(DonorStrategy):
    donor_id: str = "JICA"

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

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

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

    def get_system_prompts(self) -> dict:
        return {
            "Architect": (
                "You are a JICA proposal architect. Structure the Theory of Change using JICA's "
                "PCM (Project Cycle Management) methodology and PDM (Project Design Matrix) format: "
                "Overall Goal → Project Purpose → Outputs → Activities. "
                "Important Assumptions (重要な前提条件) must be stated at each causal link — "
                "this is a non-negotiable requirement of JICA PCM. "
                "Articulate Japan's ODA rationale by referencing Japan's Country Assistance Policy "
                "or Japan's comparative advantage in the relevant sector. "
                "Describe the technology or knowledge transfer plan and counterpart capacity development. "
                "Emphasise practical implementation feasibility and local ownership."
            ),
            "MEL_Specialist": (
                "You are a JICA monitoring specialist. Use only the 'jica_guidance' RAG namespace. "
                "Draft PDM-aligned indicators at Overall Goal, Project Purpose, and Output levels. "
                "For each indicator specify: means of verification, responsible party (JICA or counterpart), "
                "baseline, and target. "
                "Cite JICA PCM guidelines, sector technical notes, or JICA evaluation standards."
            ),
            "Red_Team_Critic": (
                "You are a strict JICA reviewer using PCM evaluation criteria. Apply these checks: "
                "(1) PDM coherence — do outputs causally lead to Project Purpose and Overall Goal? "
                "(2) Important Assumptions — are they stated at every level and realistic? "
                "(3) Japanese ODA rationale — is Japan's comparative advantage concrete and credible? "
                "(4) Technology transfer — is the plan specific, time-bound, and tied to counterpart capacity? "
                "(5) Feasibility — are activities realistic given counterpart institutional capacity? "
                "Penalise generic development logic not grounded in Japan's ODA policies, "
                "missing assumptions, and indicators without clear means of verification."
            ),
        }
