from __future__ import annotations

import copy
from typing import Any, Dict, Optional

DonorRecord = Dict[str, Any]


def _ns(default_id: str) -> str:
    return f"{default_id}_guidance"


DONOR_CATALOG: list[DonorRecord] = [
    {
        "id": "eu",
        "name": "European Commission (EU)",
        "category": "intergovernmental",
        "country_or_org": "European Union",
        "site": "https://ec.europa.eu",
        "profile": "NDICI, Erasmus+, Horizon and broader European Commission funding instruments.",
        "rag_namespace": "eu_intpa",
        "strategy": "eu",
        "aliases": ["european_union", "european-union", "european_commission", "ec", "ndici", "erasmus", "horizon"],
    },
    {
        "id": "un_agencies",
        "name": "UN Agencies (UNDP, UNICEF, UNHCR, WFP, UN Women, UNFPA)",
        "category": "intergovernmental",
        "country_or_org": "United Nations",
        "site": "https://www.undp.org",
        "profile": "UN system funding and partnership calls across humanitarian, development, and gender portfolios.",
        "rag_namespace": _ns("un_agencies"),
        "strategy": "generic",
        "aliases": ["un", "undp", "unicef", "unhcr", "wfp", "un_women", "unwomen", "unfpa"],
    },
    {
        "id": "worldbank",
        "name": "World Bank / IFC",
        "category": "intergovernmental",
        "country_or_org": "International",
        "site": "https://worldbank.org",
        "profile": "World Bank and IFC programs for development finance, infrastructure, and institutional development.",
        "rag_namespace": "worldbank_ads301",
        "strategy": "worldbank",
        "aliases": ["world_bank", "world-bank", "ifc", "international_finance_corporation"],
    },
    {
        "id": "afdb",
        "name": "African Development Bank (AfDB)",
        "category": "intergovernmental",
        "country_or_org": "Pan-African",
        "site": "https://afdb.org",
        "profile": "Regional development finance for infrastructure, governance, and inclusive growth in Africa.",
        "rag_namespace": _ns("afdb"),
        "strategy": "generic",
        "aliases": ["african_development_bank"],
    },
    {
        "id": "adb",
        "name": "Asian Development Bank (ADB)",
        "category": "intergovernmental",
        "country_or_org": "Asia",
        "site": "https://adb.org",
        "profile": (
            "Asian multilateral development bank. Projects use the Design and Monitoring Framework (DMF): "
            "Impact / Outcome / Outputs aligned to ADB Strategy 2030 Operational Priorities. "
            "Mandatory climate finance rationale, gender equity category (EGM/GEN/SGE/NO), "
            "and sovereign vs non-sovereign operation classification."
        ),
        "rag_namespace": _ns("adb"),
        "strategy": "adb",
        "aliases": ["asian_development_bank", "adb_asia"],
    },
    {
        "id": "idb",
        "name": "Inter-American Development Bank (IDB)",
        "category": "intergovernmental",
        "country_or_org": "Latin America",
        "site": "https://iadb.org",
        "profile": "Development finance and technical cooperation across Latin America and the Caribbean.",
        "rag_namespace": _ns("idb"),
        "strategy": "generic",
        "aliases": ["iadb", "inter_american_development_bank"],
    },
    {
        "id": "ebrd",
        "name": "European Bank for Reconstruction and Development (EBRD)",
        "category": "intergovernmental",
        "country_or_org": "Europe / Central Asia",
        "site": "https://ebrd.com",
        "profile": "Transition finance, private sector development, and infrastructure in EBRD regions.",
        "rag_namespace": _ns("ebrd"),
        "strategy": "generic",
        "aliases": ["european_bank_for_reconstruction_and_development"],
    },
    {
        "id": "global_fund",
        "name": "Global Fund",
        "category": "intergovernmental",
        "country_or_org": "International",
        "site": "https://theglobalfund.org",
        "profile": "Financing for HIV/AIDS, tuberculosis, and malaria programs.",
        "rag_namespace": _ns("global_fund"),
        "strategy": "generic",
        "aliases": ["the_global_fund", "globalfund"],
    },
    {
        "id": "gavi",
        "name": "Gavi, the Vaccine Alliance",
        "category": "intergovernmental",
        "country_or_org": "International",
        "site": "https://gavi.org",
        "profile": "Immunization and vaccine systems strengthening financing.",
        "rag_namespace": _ns("gavi"),
        "strategy": "generic",
        "aliases": ["gavi_vaccine_alliance", "vaccine_alliance"],
    },
    {
        "id": "usaid",
        "name": "USAID",
        "category": "government",
        "country_or_org": "United States",
        "site": "https://usaid.gov",
        "profile": "Development, health, democracy, humanitarian assistance.",
        "rag_namespace": "usaid_ads201",
        "strategy": "usaid",
        "aliases": ["usaid.gov"],
    },
    {
        "id": "us_state_department",
        "name": "U.S. Department of State",
        "category": "government",
        "country_or_org": "United States",
        "site": "https://state.gov",
        "profile": "Democracy, human rights, diplomacy-related assistance programs.",
        "rag_namespace": _ns("us_state_department"),
        "strategy": "state_department",
        "aliases": ["state_department", "us_department_of_state", "u.s._department_of_state"],
    },
    {
        "id": "ned",
        "name": "National Endowment for Democracy (NED)",
        "category": "government-linked",
        "country_or_org": "United States",
        "site": "https://ned.org",
        "profile": "Civil society, media freedom, democracy support grants.",
        "rag_namespace": _ns("ned"),
        "strategy": "generic",
        "aliases": ["national_endowment_for_democracy"],
    },
    {
        "id": "us_embassy_grants",
        "name": "U.S. Embassy Grant Programs",
        "category": "government",
        "country_or_org": "United States",
        "site": "https://usembassy.gov",
        "profile": "Local small grants programs through U.S. embassies and consulates.",
        "rag_namespace": _ns("us_embassy_grants"),
        "strategy": "generic",
        "aliases": ["us_embassy", "us_embassy_small_grants"],
    },
    {
        "id": "mcc",
        "name": "Millennium Challenge Corporation (MCC)",
        "category": "government",
        "country_or_org": "United States",
        "site": "https://mcc.gov",
        "profile": "Economic growth and infrastructure through compact and threshold programs.",
        "rag_namespace": _ns("mcc"),
        "strategy": "generic",
        "aliases": ["millennium_challenge_corporation"],
    },
    {
        "id": "fcdo",
        "name": "FCDO (UK)",
        "category": "government",
        "country_or_org": "United Kingdom",
        "site": "https://www.gov.uk/government/organisations/foreign-commonwealth-development-office",
        "profile": (
            "UK bilateral development and foreign policy donor. "
            "Programmes use logframe structure (Impact/Outcome/Output), OECD DAC criteria, "
            "Value for Money (4Es), and FCDO Smart Rules including safeguarding."
        ),
        "rag_namespace": _ns("fcdo"),
        "strategy": "fcdo",
        "aliases": [
            "ukaid",
            "uk_aid",
            "uk_foreign_commonwealth_development_office",
            "foreign_commonwealth_development_office",
            "dfid",
        ],
    },
    {
        "id": "bii",
        "name": "British International Investment (BII)",
        "category": "government-linked",
        "country_or_org": "United Kingdom",
        "site": "https://www.bii.co.uk",
        "profile": "Development finance and private sector investment in emerging markets.",
        "rag_namespace": _ns("bii"),
        "strategy": "generic",
        "aliases": ["british_international_investment"],
    },
    {
        "id": "ukri",
        "name": "UK Research and Innovation (UKRI)",
        "category": "government",
        "country_or_org": "United Kingdom",
        "site": "https://www.ukri.org",
        "profile": "Research and innovation funding across science and technology domains.",
        "rag_namespace": _ns("ukri"),
        "strategy": "generic",
        "aliases": ["uk_research_and_innovation"],
    },
    {
        "id": "giz",
        "name": "GIZ",
        "category": "government-linked",
        "country_or_org": "Germany",
        "site": "https://giz.de",
        "profile": "Technical cooperation and implementation support across development sectors.",
        "rag_namespace": _ns("giz"),
        "strategy": "giz",
        "aliases": ["deutsche_gesellschaft_fur_internationale_zusammenarbeit"],
    },
    {
        "id": "kfw",
        "name": "KfW Development Bank",
        "category": "government-linked",
        "country_or_org": "Germany",
        "site": "https://kfw.de",
        "profile": "Development finance, infrastructure and climate financing.",
        "rag_namespace": _ns("kfw"),
        "strategy": "generic",
        "aliases": ["kfw_development_bank"],
    },
    {
        "id": "bmz",
        "name": "BMZ",
        "category": "government",
        "country_or_org": "Germany",
        "site": "https://bmz.de",
        "profile": "German strategic development cooperation donor ministry.",
        "rag_namespace": _ns("bmz"),
        "strategy": "generic",
        "aliases": ["bundesministerium_fur_wirtschaftliche_zusammenarbeit_und_entwicklung"],
    },
    {
        "id": "sida",
        "name": "Sida",
        "category": "government",
        "country_or_org": "Sweden",
        "site": "https://sida.se",
        "profile": "Human rights, democracy, climate, and development cooperation funding.",
        "rag_namespace": _ns("sida"),
        "strategy": "generic",
        "aliases": ["swedish_international_development_cooperation_agency"],
    },
    {
        "id": "swedfund",
        "name": "Swedfund",
        "category": "government-linked",
        "country_or_org": "Sweden",
        "site": "https://swedfund.se",
        "profile": "Sustainable investment and development finance through private sector channels.",
        "rag_namespace": _ns("swedfund"),
        "strategy": "generic",
        "aliases": [],
    },
    {
        "id": "norad",
        "name": "Norad",
        "category": "government",
        "country_or_org": "Norway",
        "site": "https://norad.no",
        "profile": "Environment, gender, health, and development cooperation financing.",
        "rag_namespace": _ns("norad"),
        "strategy": "generic",
        "aliases": ["norwegian_agency_for_development_cooperation"],
    },
    {
        "id": "norwegian_mfa",
        "name": "Norwegian Ministry of Foreign Affairs",
        "category": "government",
        "country_or_org": "Norway",
        "site": "https://regjeringen.no",
        "profile": "Humanitarian assistance and foreign policy related funding instruments.",
        "rag_namespace": _ns("norwegian_mfa"),
        "strategy": "generic",
        "aliases": ["norway_mfa", "norwegian_ministry_of_foreign_affairs"],
    },
    {
        "id": "sdc",
        "name": "Swiss Agency for Development and Cooperation (SDC)",
        "category": "government",
        "country_or_org": "Switzerland",
        "site": "https://eda.admin.ch/deza",
        "profile": "Water, education, governance and humanitarian-development programs.",
        "rag_namespace": _ns("sdc"),
        "strategy": "generic",
        "aliases": ["swiss_agency_for_development_and_cooperation"],
    },
    {
        "id": "seco",
        "name": "SECO (Switzerland)",
        "category": "government",
        "country_or_org": "Switzerland",
        "site": "https://seco.admin.ch",
        "profile": "Economic development and market systems support financing.",
        "rag_namespace": _ns("seco"),
        "strategy": "generic",
        "aliases": ["swiss_seco"],
    },
    {
        "id": "netherlands_mfa",
        "name": "Netherlands Ministry of Foreign Affairs",
        "category": "government",
        "country_or_org": "Netherlands",
        "site": "https://government.nl",
        "profile": "Climate, gender, and agriculture-focused development funding.",
        "rag_namespace": _ns("netherlands_mfa"),
        "strategy": "generic",
        "aliases": ["nl_mfa", "netherlands_ministry_of_foreign_affairs"],
    },
    {
        "id": "fmo",
        "name": "FMO",
        "category": "government-linked",
        "country_or_org": "Netherlands",
        "site": "https://fmo.nl",
        "profile": "Private sector investment in developing countries.",
        "rag_namespace": _ns("fmo"),
        "strategy": "generic",
        "aliases": ["entrepreneurial_development_bank_fmo"],
    },
    {
        "id": "gac",
        "name": "Global Affairs Canada (GAC)",
        "category": "government",
        "country_or_org": "Canada",
        "site": "https://international.gc.ca",
        "profile": "Gender equality, inclusive growth, and international assistance programming.",
        "rag_namespace": _ns("gac"),
        "strategy": "generic",
        "aliases": ["global_affairs_canada", "canada_gac"],
    },
    {
        "id": "findev_canada",
        "name": "FinDev Canada",
        "category": "government-linked",
        "country_or_org": "Canada",
        "site": "https://findevcanada.ca",
        "profile": "Development finance for private sector growth and impact investments.",
        "rag_namespace": _ns("findev_canada"),
        "strategy": "generic",
        "aliases": ["findev", "fin_dev_canada"],
    },
    {
        "id": "afd",
        "name": "AFD (Agence Française de Développement)",
        "category": "government-linked",
        "country_or_org": "France",
        "site": "https://afd.fr",
        "profile": (
            "French bilateral development agency. Projects use cadre logique structure "
            "(Overall Objective / Specific Objective / Outputs), mandatory climate co-benefit "
            "screening, gender markers, and French expertise partnership rationale."
        ),
        "rag_namespace": _ns("afd"),
        "strategy": "afd",
        "aliases": ["agence_francaise_de_developpement", "french_development_agency"],
    },
    {
        "id": "expertise_france",
        "name": "Expertise France",
        "category": "government-linked",
        "country_or_org": "France",
        "site": "https://expertisefrance.fr",
        "profile": "Technical cooperation and implementation support.",
        "rag_namespace": _ns("expertise_france"),
        "strategy": "generic",
        "aliases": ["expertisefrance"],
    },
    {
        "id": "jica",
        "name": "JICA",
        "category": "government",
        "country_or_org": "Japan",
        "site": "https://jica.go.jp",
        "profile": (
            "Japan's primary development cooperation agency. Projects use PCM methodology "
            "and PDM (Project Design Matrix) format with explicit Important Assumptions at every level. "
            "Emphasises Japanese technology transfer, counterpart capacity, and Japan's ODA policy rationale."
        ),
        "rag_namespace": _ns("jica"),
        "strategy": "jica",
        "aliases": ["japan_international_cooperation_agency", "jica_japan"],
    },
    {
        "id": "dfat_au",
        "name": "DFAT / Australian Aid",
        "category": "government",
        "country_or_org": "Australia",
        "site": "https://dfat.gov.au",
        "profile": "Asia-Pacific development and humanitarian assistance programs.",
        "rag_namespace": _ns("dfat_au"),
        "strategy": "generic",
        "aliases": ["dfat", "australian_aid", "australia_dfat"],
    },
    {
        "id": "oecd_dac_europe_agencies",
        "name": "OECD DAC European Development Agencies (DK/FI/AT/BE/IE)",
        "category": "government",
        "country_or_org": "Denmark / Finland / Austria / Belgium / Ireland",
        "site": "https://oecd.org/dac",
        "profile": "Country development agencies funding grants aligned with OECD DAC priorities.",
        "rag_namespace": _ns("oecd_dac_europe_agencies"),
        "strategy": "generic",
        "aliases": [
            "oecd_dac",
            "european_dac_agencies",
            "danida",
            "finland_mfa_dev",
            "ada_austria",
            "enabel",
            "irish_aid",
        ],
    },
    {
        "id": "gates_foundation",
        "name": "Bill & Melinda Gates Foundation",
        "category": "private_foundation",
        "country_or_org": "Private / International",
        "site": "https://gatesfoundation.org",
        "profile": "Global health, education, and agricultural development philanthropy.",
        "rag_namespace": _ns("gates_foundation"),
        "strategy": "generic",
        "aliases": ["gates", "bill_and_melinda_gates_foundation"],
    },
    {
        "id": "open_society_foundations",
        "name": "Open Society Foundations",
        "category": "private_foundation",
        "country_or_org": "Private / International",
        "site": "https://opensocietyfoundations.org",
        "profile": "Civil society, governance, rights, and justice funding.",
        "rag_namespace": _ns("open_society_foundations"),
        "strategy": "generic",
        "aliases": ["osf", "open_society"],
    },
    {
        "id": "rockefeller_foundation",
        "name": "Rockefeller Foundation",
        "category": "private_foundation",
        "country_or_org": "Private / International",
        "site": "https://rockefellerfoundation.org",
        "profile": "Climate, food systems, resilience and public health initiatives.",
        "rag_namespace": _ns("rockefeller_foundation"),
        "strategy": "generic",
        "aliases": ["rockefeller"],
    },
    {
        "id": "ford_foundation",
        "name": "Ford Foundation",
        "category": "private_foundation",
        "country_or_org": "Private / International",
        "site": "https://fordfoundation.org",
        "profile": "Social justice, inequality reduction, and civil society support.",
        "rag_namespace": _ns("ford_foundation"),
        "strategy": "generic",
        "aliases": ["ford"],
    },
    {
        "id": "macarthur_foundation",
        "name": "MacArthur Foundation",
        "category": "private_foundation",
        "country_or_org": "Private / International",
        "site": "https://macfound.org",
        "profile": "Human rights, climate solutions, and institutional strengthening grants.",
        "rag_namespace": _ns("macarthur_foundation"),
        "strategy": "generic",
        "aliases": ["macarthur"],
    },
    {
        "id": "bloomberg_philanthropies",
        "name": "Bloomberg Philanthropies",
        "category": "private_foundation",
        "country_or_org": "Private / International",
        "site": "https://bloomberg.org",
        "profile": "Public health, city governance, and data-driven public policy programs.",
        "rag_namespace": _ns("bloomberg_philanthropies"),
        "strategy": "generic",
        "aliases": ["bloomberg"],
    },
    {
        "id": "wellcome_trust",
        "name": "Wellcome Trust",
        "category": "private_foundation",
        "country_or_org": "Private / International",
        "site": "https://wellcome.org",
        "profile": "Health and science funding, research and innovation grants.",
        "rag_namespace": _ns("wellcome_trust"),
        "strategy": "generic",
        "aliases": ["wellcome"],
    },
    {
        "id": "oak_foundation",
        "name": "Oak Foundation",
        "category": "private_foundation",
        "country_or_org": "Private / International",
        "site": "https://oakfnd.org",
        "profile": "Child rights, climate, and social justice funding.",
        "rag_namespace": _ns("oak_foundation"),
        "strategy": "generic",
        "aliases": ["oak"],
    },
    {
        "id": "akdn",
        "name": "Aga Khan Development Network (AKDN)",
        "category": "private_network",
        "country_or_org": "International",
        "site": "https://akdn.org",
        "profile": "Integrated development programs across Africa and Central/South Asia.",
        "rag_namespace": _ns("akdn"),
        "strategy": "generic",
        "aliases": ["aga_khan_development_network"],
    },
    {
        "id": "comic_relief",
        "name": "Comic Relief (UK)",
        "category": "private_foundation",
        "country_or_org": "United Kingdom",
        "site": "https://comicrelief.com",
        "profile": "Humanitarian and social impact grants.",
        "rag_namespace": _ns("comic_relief"),
        "strategy": "generic",
        "aliases": ["comic_relief_uk"],
    },
]


def normalize_donor_key(value: str) -> str:
    return (value or "").strip().lower().replace(" ", "_")


_DONOR_BY_ID: dict[str, DonorRecord] = {normalize_donor_key(d["id"]): d for d in DONOR_CATALOG}
_ALIAS_TO_ID: dict[str, str] = {}
for donor in DONOR_CATALOG:
    canonical = normalize_donor_key(donor["id"])
    for alias in donor.get("aliases", []):
        _ALIAS_TO_ID[normalize_donor_key(alias)] = canonical


def resolve_donor_record(donor_id: str) -> Optional[DonorRecord]:
    key = normalize_donor_key(donor_id)
    key = _ALIAS_TO_ID.get(key, key)
    donor = _DONOR_BY_ID.get(key)
    if donor is None:
        return None
    return copy.deepcopy(donor)


def list_supported_donors() -> list[DonorRecord]:
    records: list[DonorRecord] = []
    for donor in DONOR_CATALOG:
        item = copy.deepcopy(donor)
        item.setdefault("aliases", [])
        records.append(item)
    return records
