#!/usr/bin/env python3
"""
Loader for Canada Revenue Agency T3010 charity returns.

Usage: pass the open.canada.ca dataset page URL via --input. The loader extracts
the dataset ID, hits the CKAN API at
    https://open.canada.ca/data/en/api/3/action/package_show?id={ID}
to discover every resource (one CSV per T3010 section/schedule), downloads only
the ones we use, and merges them by (registration_number, fiscal_period_end).

Examples:
    python load_cra.py --input https://open.canada.ca/data/en/dataset/80c00cdb-1358-415c-bb8b-0de7f12675b8
    python load_cra.py --input 80c00cdb-1358-415c-bb8b-0de7f12675b8         # bare ID also accepted
    python load_cra.py --input /path/to/already-downloaded/ident_2024.csv   # local dir/file still works

Resource mapping (English-language CSVs only):
    ident_*.csv                              -> identification (name, city, province, BN, FPED)
    financial_section_a_b_and_c_*.csv        -> revenues + expenses (T3010 sections A/B/C)
    financial_d_and_schedule_6_*.csv         -> detailed financials (assets, gifts)
    schedule_2_countries_*.csv               -> foreign_countries (one row per country)
    schedule_2_resources_*.csv               -> foreign_expenditures total
    schedule_3_compensation_*.csv            -> ceo_comp (highest compensation bucket)
    new_ongoing_programs_*.csv               -> mission + program descriptions
    directors_*.csv                          -> ceo_name fallback
"""
from __future__ import annotations

import json
import re
import shutil
import ssl
import sys
import tempfile
import urllib.parse
import urllib.request
from pathlib import Path

from loader_common import (
    base_argparser, bulk_insert, connect, empty_row, iter_csv_rows,
    iter_input_files, json_or_none, to_bool, to_int, to_str, to_year,
)


CKAN_API = "https://open.canada.ca/data/en/api/3/action/package_show?id={id}"
UUID_RE = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}", re.I)

# open.canada.ca sits behind a WAF that rejects the literal "Mozilla/5.0" UA
# with a "Request Rejected" HTML page. A full browser UA passes.
BROWSER_UA = (
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
    "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36"
)


# --- CKAN discovery ----------------------------------------------------------

def parse_dataset_id(value: str) -> str | None:
    """Accept a CKAN dataset URL or a bare UUID; return the package id."""
    value = (value or "").strip()
    if not value:
        return None
    if UUID_RE.fullmatch(value):
        return value.lower()
    # Match .../dataset/{id} (id may be a UUID or a name-slug)
    m = re.search(r"/dataset/([^/?#]+)", value)
    if m:
        cand = m.group(1)
        return cand.lower() if UUID_RE.fullmatch(cand) else cand
    return None


def fetch_package(dataset_id: str) -> dict:
    api_url = CKAN_API.format(id=urllib.parse.quote(dataset_id, safe=""))
    # Full certificate verification — the CKAN response decides which URLs get
    # downloaded next, so it must be authenticated (SECURITY_REVIEW.md H1).
    ctx = ssl.create_default_context()
    req = urllib.request.Request(
        api_url,
        headers={"User-Agent": BROWSER_UA, "Accept": "application/json,*/*"},
    )
    with urllib.request.urlopen(req, timeout=120, context=ctx) as resp:
        payload = json.load(resp)
    if not payload.get("success"):
        raise RuntimeError(f"CKAN API returned success=false for {dataset_id}: {payload}")
    return payload["result"]


def is_english_csv(res: dict) -> bool:
    """Heuristic: CKAN resources are often bilingual rows. We want the English
    canonical filename — skip anything that looks French-only."""
    fmt = (res.get("format") or "").upper()
    if fmt != "CSV":
        return False
    url = (res.get("url") or "").lower()
    if not url.endswith(".csv"):
        return False
    fname = url.rsplit("/", 1)[-1]
    if "_fr." in fname or fname.endswith("_fra.csv") or "_fre.csv" in fname:
        return False
    lang = res.get("language") or []
    if isinstance(lang, list) and lang and "en" not in [l.lower() for l in lang]:
        return False
    return True


# Filename → semantic key. Matched against the URL basename (lowercased).
RESOURCE_PATTERNS = {
    "ident":              re.compile(r"^ident_"),
    "section_abc":        re.compile(r"financial_section_a_b_and_c"),
    "schedule_6":         re.compile(r"financial_d_and_schedule_6"),
    "sch2_countries":     re.compile(r"schedule_2_countries"),
    "sch2_details":       re.compile(r"schedule_2_details"),
    "sch2_resources":     re.compile(r"schedule_2_resources"),
    "sch2_goods":         re.compile(r"schedule_2_goods"),
    "sch3_compensation":  re.compile(r"schedule_3_compensation"),
    "programs":           re.compile(r"ongoing_programs|programs_"),
    "directors":          re.compile(r"^directors_"),
}


def map_resources(pkg: dict) -> dict[str, dict]:
    """Pick the English CSV for each semantic key."""
    chosen: dict[str, dict] = {}
    for res in pkg.get("resources", []):
        if not is_english_csv(res):
            continue
        fname = res["url"].rsplit("/", 1)[-1].lower()
        for key, pat in RESOURCE_PATTERNS.items():
            if key in chosen:
                continue
            if pat.search(fname):
                chosen[key] = res
                break
    return chosen


# --- Download ----------------------------------------------------------------

MAX_DOWNLOAD_BYTES = 20 * 1024 ** 3


def download(url: str, dest: Path) -> None:
    ctx = ssl.create_default_context()
    req = urllib.request.Request(url, headers={"User-Agent": BROWSER_UA})
    with urllib.request.urlopen(req, timeout=600, context=ctx) as resp, open(dest, "wb") as f:
        written = 0
        while True:
            chunk = resp.read(1 << 20)
            if not chunk:
                break
            written += len(chunk)
            if written > MAX_DOWNLOAD_BYTES:
                raise RuntimeError(
                    f"{dest.name}: download exceeded the "
                    f"{MAX_DOWNLOAD_BYTES // (1024 ** 3)} GB limit; aborting."
                )
            f.write(chunk)


# --- CSV parsing helpers -----------------------------------------------------

def lower_keys(row: dict) -> dict:
    return {(k or "").strip().lower(): v for k, v in row.items()}


def pick(row: dict, *candidates: str):
    for c in candidates:
        v = row.get(c.lower())
        if v not in (None, ""):
            return v
    return None


def reg_year_key(row: dict) -> tuple[str, str] | None:
    reg = to_str(pick(row,
        "bn_registration_number", "bn", "registration_number",
        "bn_reg_num", "business_registration_number"
    ), 50)
    if not reg:
        return None
    fped = pick(row, "fiscal_period_ending", "fped", "fpe",
                "fiscal_period_end", "return_year", "fye")
    year = to_year(fped) or "0"
    return (reg, year)


def year_from_filename(path: Path) -> str:
    m = re.search(r"(20\d{2}|19\d{2})", path.name)
    return m.group(0) if m else "0"


# --- Parsers per resource ----------------------------------------------------

def parse_ident(path: Path, default_year: str) -> dict[tuple, dict]:
    out: dict[tuple, dict] = {}
    for raw in iter_csv_rows(path):
        row = lower_keys(raw)
        key = reg_year_key(row)
        if not key:
            continue
        reg, year = key
        if year == "0":
            year = default_year
            key = (reg, year)

        r = empty_row()
        r.update({
            "country_code": "CA",
            "sub_jurisdiction": None,
            "data_source": "CRA",
            "registration_number": reg,
            "ein": None,
            "name": to_str(pick(row,
                "charity_name", "english_charity_name",
                "legal_name", "legal name",
                "account_name", "account name",
            ), 500) or "",
            "form_type": "T3010",
            "tax_year": year,
            "city": to_str(pick(row, "city", "addr_city", "address_city"), 200),
            "state": to_str(pick(row,
                "province", "prov", "province_state", "addr_province",
            ), 50),
        })
        category = to_str(pick(row, "category"), 200)
        sub_category = to_str(pick(row, "sub category", "sub_category", "subcategory"), 200)
        cats = [c for c in (category, sub_category) if c]
        if cats:
            r["categories"] = json_or_none(cats)
        out[key] = r
    return out


# Sentinel non-tuple key used to stash auxiliary state inside the rows dict.
# Real row keys are (registration_number, tax_year) tuples, so a plain string
# never collides.
_PER_COUNTRY_KEY = "__per_country__"


def _fill_if_none(target: dict, field: str, value) -> None:
    if value is not None and target.get(field) is None:
        target[field] = value


def _apply_financials(target: dict, row: dict) -> None:
    """Pull T3010 financial line items. Modern dataset splits these across
    section A/B/C (program codes, address, some totals) and schedule 6 (the
    bulk of revenue/expense/asset lines), so we try every known column name in
    both files and only write when the field is still empty."""
    _fill_if_none(target, "total_revenue",
        to_int(pick(row, "total_revenue", "line_4700", "4700")))
    _fill_if_none(target, "total_expenses",
        to_int(pick(row, "total_expenditures", "line_5100", "5100")))
    _fill_if_none(target, "program_expenses",
        to_int(pick(row, "charitable_program_expenditures", "line_5000", "5000")))
    _fill_if_none(target, "mgmt_expenses",
        to_int(pick(row, "management_and_administration", "line_5010", "5010")))
    _fill_if_none(target, "fundraising_expenses",
        to_int(pick(row, "fundraising_expenditures", "line_5020", "5020")))
    _fill_if_none(target, "grants_paid",
        to_int(pick(row, "total_gifts_to_qualified_donees", "line_5050", "5050")))
    _fill_if_none(target, "salaries",
        to_int(pick(row, "total_compensation", "line_4200", "4200")))
    _fill_if_none(target, "employees",
        to_int(pick(row, "number_of_employees", "line_400", "400")))
    _fill_if_none(target, "volunteers",
        to_int(pick(row, "number_of_volunteers", "line_5640", "5640")))
    _fill_if_none(target, "total_assets",
        to_int(pick(row, "total_assets", "line_4200", "assets_total", "4200")))
    _fill_if_none(target, "net_assets",
        to_int(pick(row, "net_assets", "fund_balances")))
    _fill_if_none(target, "gross_receipts",
        to_int(pick(row, "total_tax_receipted_gifts", "line_4500", "4500")))
    fa = to_bool(pick(row, "activities_outside_canada", "outside_canada",
                      "line_200", "200"))
    if fa is not None and target.get("foreign_activities") is None:
        target["foreign_activities"] = fa
    aud = to_bool(pick(row, "audited_financial_statements",
                       "financial_statements_audited"))
    if aud is not None and target.get("audited") is None:
        target["audited"] = aud


def merge_section_abc(rows: dict[tuple, dict], path: Path, default_year: str) -> None:
    """Sections A (identification) + B (general info) + C (financial)."""
    for raw in iter_csv_rows(path):
        row = lower_keys(raw)
        key = reg_year_key(row)
        if not key:
            continue
        if key[1] == "0":
            key = (key[0], default_year)
        target = rows.get(key)
        if target is None:
            target = empty_row()
            target.update({
                "country_code": "CA", "data_source": "CRA",
                "registration_number": key[0], "tax_year": key[1],
                "form_type": "T3010", "name": "",
            })
            rows[key] = target

        _apply_financials(target, row)


def merge_schedule_6(rows: dict[tuple, dict], path: Path, default_year: str) -> None:
    """Detailed financial schedule (assets, gifts received, etc.)."""
    for raw in iter_csv_rows(path):
        row = lower_keys(raw)
        key = reg_year_key(row)
        if not key:
            continue
        if key[1] == "0":
            key = (key[0], default_year)
        target = rows.get(key)
        if target is None:
            continue
        _apply_financials(target, row)


def merge_sch2_countries(rows: dict[tuple, dict], path: Path, default_year: str) -> None:
    buckets: dict[tuple, set] = {}
    for raw in iter_csv_rows(path):
        row = lower_keys(raw)
        key = reg_year_key(row)
        if not key:
            continue
        if key[1] == "0":
            key = (key[0], default_year)
        country = to_str(pick(row, "country", "country_name", "country_code", "country_of_activity"), 100)
        if not country:
            continue
        buckets.setdefault(key, set()).add(country)

    for key, target in rows.items():
        countries = buckets.get(key)
        if countries:
            target["foreign_countries"] = json_or_none(sorted(countries))
            target["schedule_f_filed"] = 1
            target["foreign_activities"] = 1


def _accumulate_country_amounts(
    by_country: dict[tuple, dict[str, int]],
    path: Path,
    default_year: str,
    amount_fields: tuple[str, ...],
) -> None:
    """Accumulate {country: amount} per (reg, year) into by_country in place."""
    for raw in iter_csv_rows(path):
        row = lower_keys(raw)
        key = reg_year_key(row)
        if not key:
            continue
        if key[1] == "0":
            key = (key[0], default_year)
        amt = to_int(pick(row, *amount_fields))
        if amt is None or amt <= 0:
            continue
        country = to_str(pick(row, "country", "country_name", "destination"), 100)
        if not country:
            continue
        bucket = by_country.setdefault(key, {})
        bucket[country] = bucket.get(country, 0) + amt


def merge_sch2_resources(rows: dict[tuple, dict], path: Path, default_year: str) -> None:
    """Sum cash/resources sent outside Canada per (reg, year, country).

    Populates the scalar `foreign_expenditures` total and an in-memory
    per-country map that `finalize_foreign_grants` later merges with
    Schedule 2 goods into the `foreign_grant_regions` JSON column."""
    by_country: dict[tuple, dict[str, int]] = rows.setdefault(_PER_COUNTRY_KEY, {})  # type: ignore[arg-type]
    _accumulate_country_amounts(
        by_country, path, default_year,
        ("total_resources_outside_canada", "amount_outside_canada",
         "total_amount", "resources_amount",
         "total_expenditures_outside_canada", "amount"),
    )


def merge_sch2_goods(rows: dict[tuple, dict], path: Path, default_year: str) -> None:
    """Per-country in-kind goods sent outside Canada (Schedule 2 goods)."""
    by_country: dict[tuple, dict[str, int]] = rows.setdefault(_PER_COUNTRY_KEY, {})  # type: ignore[arg-type]
    _accumulate_country_amounts(
        by_country, path, default_year,
        ("item_value", "item value", "value", "amount"),
    )


# T3010 Schedule 3 compensation bands: column → lower bound of the band.
# CRA reports the count of permanent positions in each $40k band; individual
# salaries aren't disclosed, so the highest non-empty band's lower bound is
# the best CEO-comp proxy available.
SCH3_BANDS = [
    ("300",      1),
    ("305",  40000),
    ("310",  80000),
    ("315", 120000),
    ("320", 160000),
    ("325", 200000),
    ("330", 250000),
    ("335", 300000),
    ("340", 350000),
    ("345", 400000),
]


def merge_sch3_compensation(rows: dict[tuple, dict], path: Path, default_year: str) -> None:
    """Schedule 3 holds permanent-position counts bucketed into $40k comp bands
    plus aggregate compensation expenditure. We derive:

      employees  = sum of positions across all bands
      salaries   = line 390 (total compensation) or line 380 (FT total)
      ceo_comp   = lower bound of the highest non-empty band (CRA does not
                   publish individual salaries — only counts per band)
    """
    for raw in iter_csv_rows(path):
        row = lower_keys(raw)
        key = reg_year_key(row)
        if not key:
            continue
        if key[1] == "0":
            key = (key[0], default_year)
        target = rows.get(key)
        if target is None:
            continue

        band_counts = [(col, to_int(row.get(col)), lower) for col, lower in SCH3_BANDS]
        total_positions = sum(c for _, c, _ in band_counts if c)
        if total_positions:
            _fill_if_none(target, "employees", total_positions)

        salary = to_int(row.get("390")) or to_int(row.get("380"))
        if salary is not None:
            _fill_if_none(target, "salaries", salary)

        top_band_lower = None
        nonzero_bands: dict[str, int] = {}
        for col, count, lower in band_counts:
            if count and count > 0:
                top_band_lower = lower
                nonzero_bands[str(lower)] = int(count)
        if top_band_lower is not None:
            _fill_if_none(target, "ceo_comp", top_band_lower)
        if nonzero_bands and target.get("sch3_band_counts") is None:
            target["sch3_band_counts"] = json_or_none(nonzero_bands)


def merge_programs(rows: dict[tuple, dict], path: Path, default_year: str) -> None:
    """Take up to 3 program descriptions and the first as mission fallback."""
    grouped: dict[tuple, list[str]] = {}
    for raw in iter_csv_rows(path):
        row = lower_keys(raw)
        key = reg_year_key(row)
        if not key:
            continue
        if key[1] == "0":
            key = (key[0], default_year)
        desc = to_str(pick(row,
            "program_description", "ongoing_program",
            "description_of_program", "activity_description",
            "description",
        ), 65000)
        if not desc:
            continue
        grouped.setdefault(key, []).append(desc)

    for key, descs in grouped.items():
        target = rows.get(key)
        if not target:
            continue
        if not target.get("mission"):
            target["mission"] = descs[0]
        target["program_desc1"] = descs[0] if len(descs) > 0 else None
        target["program_desc2"] = descs[1] if len(descs) > 1 else None
        target["program_desc3"] = descs[2] if len(descs) > 2 else None
        target["program_count"] = len(descs)


# Director position titles that signal "principal officer" in priority order.
# CRA T3010 doesn't have a CEO field — most charities list a board chair,
# executive director, or president. Match the first occurrence of the highest
# tier we see, so an Executive Director wins over a Director when both exist.
_CEO_TITLE_TIERS: list[tuple[int, re.Pattern]] = [
    (0, re.compile(r"\bceo\b|chief executive", re.I)),
    (1, re.compile(r"executive director|executive\s+dir", re.I)),
    (2, re.compile(r"\bpresident\b", re.I)),
    (3, re.compile(r"chair(person)?|\bchair\b", re.I)),
]


def merge_directors(rows: dict[tuple, dict], path: Path, default_year: str) -> None:
    """Pick the highest-ranking officer per charity as a CEO proxy."""
    best_tier: dict[tuple, int] = {}
    for raw in iter_csv_rows(path):
        row = lower_keys(raw)
        key = reg_year_key(row)
        if not key:
            continue
        if key[1] == "0":
            key = (key[0], default_year)
        target = rows.get(key)
        if not target:
            continue
        position = to_str(pick(row, "position", "title", "officer_position"), 300)
        if not position:
            continue
        for tier, pat in _CEO_TITLE_TIERS:
            if pat.search(position):
                break
        else:
            continue
        if tier >= best_tier.get(key, 999):
            continue  # already have a better match
        first = to_str(pick(row, "first_name", "first name", "given_name"), 150)
        last = to_str(pick(row, "last_name", "last name", "surname", "family_name"), 150)
        name = " ".join(p for p in (first, last) if p)
        if not name:
            continue
        target["ceo_name"] = name[:300]
        target["ceo_title"] = position
        best_tier[key] = tier


# --- Orchestration -----------------------------------------------------------

def load_from_dataset(dataset_url: str, workdir: Path) -> list[Path]:
    """Download every needed CSV from the CKAN package into workdir.
    Returns the list of local file paths."""
    dataset_id = parse_dataset_id(dataset_url)
    if not dataset_id:
        raise ValueError(f"Could not extract CKAN dataset id from: {dataset_url}")
    print(f"  Resolving CKAN package {dataset_id} ...", flush=True)
    pkg = fetch_package(dataset_id)
    chosen = map_resources(pkg)
    if "ident" not in chosen:
        raise RuntimeError(f"Dataset {dataset_id} has no identification CSV — wrong dataset?")

    paths: dict[str, Path] = {}
    for key, res in chosen.items():
        url = res["url"]
        fname = url.rsplit("/", 1)[-1]
        # The name comes from the CKAN API response; never let it become a path.
        if fname in ("", ".", "..") or not re.fullmatch(r"[A-Za-z0-9._-]+", fname):
            print(f"    WARNING: unsafe resource filename {fname!r}; skipping", flush=True)
            continue
        dest = workdir / fname
        print(f"  Downloading [{key}] {fname}", flush=True)
        try:
            download(url, dest)
            paths[key] = dest
        except Exception as exc:
            print(f"    WARNING: failed to download {fname}: {exc}", flush=True)

    return paths  # type: ignore[return-value]


def load_from_local_path(input_path: Path) -> dict[str, Path]:
    """Match files in a local directory against RESOURCE_PATTERNS."""
    files = iter_input_files(input_path, "*.csv") or ([input_path] if input_path.is_file() else [])
    chosen: dict[str, Path] = {}
    for f in files:
        fname = f.name.lower()
        for key, pat in RESOURCE_PATTERNS.items():
            if key in chosen:
                continue
            if pat.search(fname):
                chosen[key] = f
                break
    return chosen


def build_rows(paths: dict[str, Path]) -> list[dict]:
    ident_path = paths.get("ident")
    if not ident_path:
        raise RuntimeError("No identification CSV (ident_*.csv) found — cannot proceed")

    default_year = year_from_filename(ident_path)
    print(f"  Default fiscal year: {default_year}", flush=True)

    rows = parse_ident(ident_path, default_year)
    print(f"  Parsed {len(rows)} identification rows", flush=True)

    for key, merge_fn in (
        ("section_abc",       merge_section_abc),
        ("schedule_6",        merge_schedule_6),
        ("sch2_countries",    merge_sch2_countries),
        ("sch2_resources",    merge_sch2_resources),
        ("sch2_goods",        merge_sch2_goods),
        ("sch3_compensation", merge_sch3_compensation),
        ("programs",          merge_programs),
        ("directors",         merge_directors),
    ):
        path = paths.get(key)
        if path is None:
            continue
        print(f"  Merging [{key}] {path.name}", flush=True)
        merge_fn(rows, path, default_year)

    _finalize_foreign_grants(rows)

    return [r for k, r in rows.items() if isinstance(k, tuple) and r["name"]]


def _finalize_foreign_grants(rows: dict) -> None:
    """Move the per-country aggregation built during sch2_resources/sch2_goods
    merges onto each charity row as foreign_grant_regions (JSON {country: $})
    and foreign_expenditures (sum)."""
    by_country: dict[tuple, dict[str, int]] = rows.pop(_PER_COUNTRY_KEY, {}) or {}
    for key, amounts in by_country.items():
        target = rows.get(key)
        if target is None:
            continue
        if amounts:
            target["foreign_grant_regions"] = json_or_none(amounts)
            target["foreign_expenditures"] = sum(amounts.values())
            target["foreign_activities"] = 1
            target["schedule_f_filed"] = 1


def main() -> int:
    parser = base_argparser("Load CRA T3010 charity returns into MySQL via CKAN API")
    args = parser.parse_args()

    raw = args.input.strip()
    workdir: Path | None = None

    try:
        if raw.startswith("http://") or raw.startswith("https://") or UUID_RE.fullmatch(raw):
            workdir = Path(tempfile.mkdtemp(prefix="cra_"))
            paths = load_from_dataset(raw, workdir)
        else:
            local = Path(raw)
            if not local.exists():
                print(f"  ERROR: input is neither a URL nor an existing path: {raw}", flush=True)
                return 2
            paths = load_from_local_path(local)

        rows = build_rows(paths)
        if not rows:
            print("  No CRA rows parsed.", flush=True)
            return 1

        conn = connect(args)
        try:
            n = bulk_insert(conn, rows)
            print(f"  Inserted/updated {n} CRA rows.", flush=True)
        finally:
            conn.close()
        return 0
    finally:
        if workdir and workdir.exists():
            shutil.rmtree(workdir, ignore_errors=True)


if __name__ == "__main__":
    sys.exit(main())
