#!/usr/bin/env python3
"""
Loader for the UK Charity Commission for England & Wales (CCEW) bulk register.

Source: https://register-of-charities.charitycommission.gov.uk/en/register/full-register-download
CCEW ships a SQL Server BCP dump as a ZIP of tab-delimited .txt files. Tables
consumed by this loader (one zip each on the CCEW download page):

    publicextract.charity                          -> identification, address, latest totals
    publicextract.charity_annual_return_history    -> per-cycle gross income / expenditure
    publicextract.charity_annual_return_parta      -> volunteers, grant-making flag
    publicextract.charity_annual_return_partb      -> expense breakdown, assets, employees
    publicextract.charity_area_of_operation        -> country-of-operation list
    publicextract.charity_classification           -> "what" descriptions, hospital/school flags
    publicextract.charity_governing_document       -> charitable_objects (mission)
    publicextract.charity_policy                   -> conflict / whistleblower / doc-retention
    publicextract.charity_trustee                  -> trustee count, chair name

If --input is omitted, the script downloads and extracts the bulk register
automatically from the CCEW website before processing.

Sub-jurisdiction:
    CCEW covers England & Wales -> sub_jurisdiction = 'EW'.
"""
from __future__ import annotations

import argparse
import csv
import os
import re
import ssl
import sys
import tempfile
import zipfile
from html.parser import HTMLParser
from pathlib import Path
from urllib.error import URLError
from urllib.parse import urljoin
from urllib.request import Request, urlopen

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

# CCEW dumps embed long activity/description blobs that exceed the default
# 128 KB csv field cap. 10 MB comfortably covers the largest legitimate blob
# while still bounding memory on a hostile file.
csv.field_size_limit(10 * 1024 * 1024)

# Full certificate + hostname verification (see SECURITY_REVIEW.md H1).
_SSL_CTX = ssl.create_default_context()

# Resource-exhaustion guards for the auto-download path.
MAX_DOWNLOAD_BYTES = 20 * 1024 ** 3
MAX_EXTRACT_BYTES = 100 * 1024 ** 3
EXTRACT_MAX_RATIO = 200

DOWNLOAD_PAGE = (
    "https://register-of-charities.charitycommission.gov.uk"
    "/en/register/full-register-download"
)
_UA = "Mozilla/5.0 (compatible; charity-analytics/1.0)"

_NEEDED_ZIPS = {
    "publicextract.charity.zip",
    "publicextract.charity_annual_return_history.zip",
    "publicextract.charity_annual_return_parta.zip",
    "publicextract.charity_annual_return_partb.zip",
    "publicextract.charity_area_of_operation.zip",
    "publicextract.charity_classification.zip",
    "publicextract.charity_governing_document.zip",
    "publicextract.charity_policy.zip",
    "publicextract.charity_trustee.zip",
}


# ---------------------------------------------------------------------------
# Download helpers
# ---------------------------------------------------------------------------

class _LinkParser(HTMLParser):
    def __init__(self):
        super().__init__()
        self.links: list[str] = []

    def handle_starttag(self, tag, attrs):
        if tag == "a":
            for k, v in attrs:
                if k == "href" and v:
                    self.links.append(v)


def _zip_urls_from_page(page_url: str) -> list[str]:
    req = Request(page_url, headers={"User-Agent": _UA})
    with urlopen(req, timeout=30, context=_SSL_CTX) as resp:
        html = resp.read().decode("utf-8", errors="replace")

    parser = _LinkParser()
    parser.feed(html)

    # CCEW serves each zip under both /json/ and /txt/ blob paths with the
    # same filename. We need the tab-delimited TXT variant; ignore /json/.
    seen_names: set[str] = set()
    out: list[str] = []
    for href in parser.links:
        href_l = href.lower()
        if ".zip" not in href_l or "/json/" in href_l:
            continue
        fname = href.rsplit("/", 1)[-1].split("?")[0].lower()
        if fname not in _NEEDED_ZIPS or fname in seen_names:
            continue
        seen_names.add(fname)
        out.append(urljoin(page_url, href))
    return out


def _download(url: str, dest: Path) -> None:
    req = Request(url, headers={"User-Agent": _UA})
    with urlopen(req, timeout=300, context=_SSL_CTX) as resp:
        total = int(resp.headers.get("Content-Length", 0))
        if total > MAX_DOWNLOAD_BYTES:
            raise RuntimeError(
                f"{dest.name}: remote file is {total} bytes, over the "
                f"{MAX_DOWNLOAD_BYTES // (1024 ** 3)} GB download limit."
            )
        done = 0
        with open(dest, "wb") as f:
            while True:
                chunk = resp.read(1 << 20)
                if not chunk:
                    break
                done += len(chunk)
                if done > MAX_DOWNLOAD_BYTES:
                    raise RuntimeError(
                        f"{dest.name}: download exceeded the "
                        f"{MAX_DOWNLOAD_BYTES // (1024 ** 3)} GB limit; aborting."
                    )
                f.write(chunk)
                if total:
                    pct = done * 100 // total
                    print(
                        f"\r    {dest.name}: {done/1e6:.0f}/{total/1e6:.0f} MB ({pct}%)",
                        end="", flush=True,
                    )
                else:
                    print(f"\r    {dest.name}: {done/1e6:.0f} MB", end="", flush=True)
    print(flush=True)


def auto_download(tmp_dir: Path, page_url: str = DOWNLOAD_PAGE) -> None:
    print("  Fetching download page …", flush=True)
    try:
        urls = _zip_urls_from_page(page_url)
    except URLError as exc:
        raise RuntimeError(f"Cannot reach CCEW download page: {exc}") from exc

    if not urls:
        raise RuntimeError(
            "No ZIP links found on the CCEW download page.\n"
            "The page structure may have changed — pass --input to a manually "
            "downloaded directory instead."
        )

    print(f"  Found {len(urls)} ZIP file(s).", flush=True)
    for url in urls:
        fname = url.split("/")[-1].split("?")[0] or "ccew.zip"
        # The name comes from a scraped href; never let it become a path.
        if fname in (".", "..") or not re.fullmatch(r"[A-Za-z0-9._-]+", fname):
            raise RuntimeError(f"Unsafe download filename from CCEW page: {fname!r}")
        dest = tmp_dir / fname
        print(f"  Downloading {fname} …", flush=True)
        _download(url, dest)
        print(f"  Extracting {fname} …", flush=True)
        with zipfile.ZipFile(dest) as zf:
            _validate_zip_members(zf, dest)
            zf.extractall(tmp_dir)
        dest.unlink()


def _validate_zip_members(zf: zipfile.ZipFile, zip_path: Path) -> None:
    """Reject archives with traversal-shaped member paths, an uncompressed
    size past the absolute cap, or a zip-bomb compression ratio."""
    total_uncompressed = 0
    for info in zf.infolist():
        member = Path(info.filename)
        if member.is_absolute() or ".." in member.parts:
            raise RuntimeError(f"{zip_path.name}: unsafe zip member path {info.filename!r}")
        total_uncompressed += info.file_size

    if total_uncompressed > MAX_EXTRACT_BYTES:
        raise RuntimeError(
            f"{zip_path.name}: expands to {total_uncompressed} bytes, over the "
            f"{MAX_EXTRACT_BYTES // (1024 ** 3)} GB extraction limit."
        )

    compressed = zip_path.stat().st_size
    if compressed and total_uncompressed / compressed > EXTRACT_MAX_RATIO:
        raise RuntimeError(
            f"{zip_path.name}: compression ratio exceeds {EXTRACT_MAX_RATIO}:1 — "
            f"refusing (possible zip bomb)."
        )


# ---------------------------------------------------------------------------
# Parsing helpers
# ---------------------------------------------------------------------------

def read_pipe(path: Path):
    """CCEW files are tab-delimited and may have BOM."""
    with open(path, "r", encoding="utf-8-sig", errors="replace") as f:
        reader = csv.DictReader(f, delimiter="\t")
        for row in reader:
            yield {(k or "").strip().lower(): (v.strip() if isinstance(v, str) else v)
                   for k, v in row.items()}


def _is_parent(row: dict) -> bool:
    """Linked subsidiaries share the parent's registration_number. Keep only
    the parent (linked_charity_number = 0) so per-reg aggregates don't double-
    count trustees, classifications, policies, etc."""
    v = (row.get("linked_charity_number") or "0").strip()
    return v in ("", "0")


def _city_from_address(row: dict) -> str | None:
    """UK addresses run building → street → locality → town → county. The last
    populated of lines 5..3 is usually the town/city."""
    for k in ("charity_contact_address5", "charity_contact_address4",
              "charity_contact_address3"):
        v = to_str(row.get(k), 200)
        if v:
            return v
    return to_str(
        row.get("charity_contact_address2") or row.get("charity_contact_address1"),
        200,
    )


_POSTCODE_OUTWARD = re.compile(r"^([A-Z]{1,2}\d[A-Z\d]?)", re.IGNORECASE)


def _state_from_postcode(row: dict) -> str | None:
    """Use the postcode 'outward' code (e.g. 'EC1A' from 'EC1A 1BB') as a
    coarse region identifier so list views can filter by area."""
    pc = (row.get("charity_contact_postcode") or "").strip().upper()
    if not pc:
        return None
    head = pc.split()[0] if " " in pc else pc
    m = _POSTCODE_OUTWARD.match(head)
    return m.group(1) if m else head[:8] or None


def _is_latest_cycle(row: dict) -> bool:
    flag = (row.get("latest_fin_period_submitted_ind") or "").strip().lower()
    if flag in ("true", "1", "yes", "t"):
        return True
    return (row.get("fin_period_order_number") or "").strip() == "1"


# ---------------------------------------------------------------------------
# Charity-level processors (one entry per registered_charity_number)
# ---------------------------------------------------------------------------

def process_charity_meta(path: Path) -> dict[str, dict]:
    meta: dict[str, dict] = {}
    for row in read_pipe(path):
        if not _is_parent(row):
            continue
        reg = to_str(
            row.get("registered_charity_number") or row.get("organisation_number"),
            50,
        )
        if not reg or reg in meta:
            continue
        meta[reg] = {
            "reg": reg,
            "name": to_str(row.get("charity_name"), 500) or "",
            "city": _city_from_address(row),
            "state": _state_from_postcode(row),
            "mission": to_str(row.get("charity_activities"), 65000),
            "latest_year": to_year(
                row.get("latest_acc_fin_period_end_date")
                or row.get("date_of_registration")
            ) or "0",
            "latest_income": to_int(row.get("latest_income")),
            "latest_expenditure": to_int(row.get("latest_expenditure")),
        }
    return meta


def process_governing(path: Path) -> dict[str, str]:
    """reg -> mission (charitable_objects, usually richer than charity_activities)."""
    out: dict[str, str] = {}
    for row in read_pipe(path):
        if not _is_parent(row):
            continue
        reg = to_str(row.get("registered_charity_number"), 50)
        if not reg or reg in out:
            continue
        objects = to_str(row.get("charitable_objects"), 65000)
        if objects:
            out[reg] = objects
    return out


_HOSPITAL_KW = re.compile(r"hospital|medic|health", re.IGNORECASE)
_SCHOOL_KW = re.compile(r"school|college|educat|training", re.IGNORECASE)


def process_classification(path: Path) -> dict[str, dict]:
    """reg -> {descs: [...], hospital: 0/1, school: 0/1}.
    Only classification_type = 'What' (what the charity does) is collected;
    'How' and 'Who' have no obvious destination column."""
    out: dict[str, dict] = {}
    for row in read_pipe(path):
        if not _is_parent(row):
            continue
        if (row.get("classification_type") or "").strip().lower() != "what":
            continue
        reg = to_str(row.get("registered_charity_number"), 50)
        descr = to_str(row.get("classification_description"), 200)
        if not reg or not descr:
            continue
        rec = out.setdefault(reg, {"descs": [], "hospital": 0, "school": 0})
        rec["descs"].append(descr)
        if _HOSPITAL_KW.search(descr):
            rec["hospital"] = 1
        if _SCHOOL_KW.search(descr):
            rec["school"] = 1
    return out


_POLICY_RULES = {
    "conflict_policy":      re.compile(r"conflict", re.IGNORECASE),
    # CCEW catalogues "Serious incident reporting" — the UK Charity Commission
    # equivalent of US Form 990 whistleblower policies.
    "whistleblower_policy": re.compile(r"whistleblow|serious incident", re.IGNORECASE),
    "doc_retention_policy": re.compile(r"retention|preserv", re.IGNORECASE),
}


def process_policy(path: Path) -> dict[str, dict]:
    out: dict[str, dict] = {}
    for row in read_pipe(path):
        if not _is_parent(row):
            continue
        reg = to_str(row.get("registered_charity_number"), 50)
        name = to_str(row.get("policy_name"), 200)
        if not reg or not name:
            continue
        rec = out.setdefault(reg, {})
        for col, rgx in _POLICY_RULES.items():
            if rgx.search(name):
                rec[col] = 1
    return out


def process_trustee(path: Path) -> dict[str, dict]:
    """reg -> {count: trustees, chair: name-of-first-chair}."""
    out: dict[str, dict] = {}
    for row in read_pipe(path):
        if not _is_parent(row):
            continue
        reg = to_str(row.get("registered_charity_number"), 50)
        if not reg:
            continue
        rec = out.setdefault(reg, {"count": 0, "chair": None})
        rec["count"] += 1
        is_chair = (row.get("trustee_is_chair") or "").strip().lower() in ("true", "1", "yes", "t")
        if is_chair and not rec["chair"]:
            rec["chair"] = to_str(row.get("trustee_name"), 300)
    return out


def process_areas(path: Path) -> dict[str, set]:
    by_reg: dict[str, set] = {}
    for row in read_pipe(path):
        if not _is_parent(row):
            continue
        reg = to_str(row.get("registered_charity_number"), 50)
        if not reg:
            continue
        kind = (row.get("geographic_area_type") or "").strip().lower()
        descr = to_str(row.get("geographic_area_description"), 100)
        if not descr:
            continue
        if kind in ("country", "continent") and descr.upper() not in (
            "ENGLAND", "WALES", "SCOTLAND", "NORTHERN IRELAND", "UNITED KINGDOM"
        ):
            by_reg.setdefault(reg, set()).add(descr)
    return by_reg


# ---------------------------------------------------------------------------
# AR-cycle financial overlays
# ---------------------------------------------------------------------------

def _apply_partb_row(target: dict, row: dict) -> None:
    rev = to_int(row.get("income_total_income_and_endowments"))
    if rev is not None:
        target["total_revenue"] = rev
    exp = to_int(row.get("expenditure_total"))
    if exp is not None:
        target["total_expenses"] = exp
    target["program_expenses"] = to_int(row.get("expenditure_charitable_expenditure"))
    target["fundraising_expenses"] = to_int(row.get("expenditure_raising_funds"))
    target["mgmt_expenses"] = to_int(row.get("expenditure_governance"))
    target["grants_paid"] = to_int(row.get("expenditure_grants_institution"))
    target["total_assets"] = to_int(row.get("assets_total_fixed"))
    target["net_assets"] = to_int(row.get("assets_total_assets_and_liabilities"))
    target["employees"] = to_int(row.get("count_employees"))


def _apply_parta_row(target: dict, row: dict) -> None:
    vols = to_int(row.get("count_volunteers"))
    if vols is not None:
        target["volunteers"] = vols
    if to_bool(row.get("grant_making_is_main_activity")):
        target["grants_to_orgs"] = 1


def process_ar_history(path: Path) -> dict[str, int]:
    """reg -> 1 if the most recent AR cycle reported a qualified audit opinion.
    CCEW publishes `accounts_qualified` per AR cycle; we keep the latest year
    (highest fin_period_end_date) per reg as a proxy for current audit health."""
    latest_year: dict[str, str] = {}
    flag: dict[str, int] = {}
    for row in read_pipe(path):
        reg = to_str(row.get("registered_charity_number"), 50)
        if not reg:
            continue
        year = to_year(row.get("fin_period_end_date")) or ""
        prev = latest_year.get(reg, "")
        if year and year >= prev:
            latest_year[reg] = year
            flag[reg] = to_bool(row.get("accounts_qualified"))
    return flag


# ---------------------------------------------------------------------------
# Row builders
# ---------------------------------------------------------------------------

def _cap_years_per_charity(rows: dict[tuple, dict], n: int) -> dict[tuple, dict]:
    """Keep only the N most recent (reg, year) rows per charity.
    Tax years are 4-digit strings so lexical sort matches numeric sort.
    Stub rows whose year is '0' (registration-year fallback) sort last."""
    by_reg: dict[str, list[tuple]] = {}
    for key in rows:
        by_reg.setdefault(key[0], []).append(key)

    kept: dict[tuple, dict] = {}
    for keys in by_reg.values():
        keys.sort(key=lambda k: k[1], reverse=True)
        for k in keys[:n]:
            kept[k] = rows[k]
    return kept


def _make_row(meta_entry: dict, year: str) -> dict:
    r = empty_row()
    r.update({
        "country_code": "GB",
        "sub_jurisdiction": "EW",
        "data_source": "CCEW",
        "registration_number": meta_entry["reg"],
        "ein": None,
        "name": meta_entry["name"],
        "form_type": "AR",
        "tax_year": year,
        "city": meta_entry["city"],
        "state": meta_entry["state"],
        "mission": meta_entry["mission"],
    })
    return r


def discover_top_years(ar_file: Path, cap: int = 5) -> list[str]:
    """Single light pass over ar_history to find the N most recent calendar
    years. Used by `--mode all --stream` to drive year-batched processing
    without ever loading all (reg, year) tuples at once."""
    years: set[str] = set()
    for row in read_pipe(ar_file):
        y = to_year(
            row.get("fin_period_end_date") or row.get("ar_cycle_reference")
        )
        if y:
            years.add(y)
    return sorted(years, reverse=True)[:cap]


def apply_per_charity_overlays(
    rows: dict[tuple, dict],
    gov: dict,
    classif: dict,
    policy: dict,
    trustee: dict,
    areas: dict,
    audited_flag: dict,
) -> None:
    """Apply the once-loaded per-charity overlays to a batch of rows."""
    for (reg, _year), r in rows.items():
        if reg in gov:
            r["mission"] = gov[reg]
        c = classif.get(reg)
        if c:
            for i, d in enumerate(c["descs"][:3], 1):
                r[f"program_desc{i}"] = to_str(d, 65000)
            r["program_count"] = len(c["descs"]) or None
            r["operates_hospital"] = c["hospital"]
            r["operates_school"] = c["school"]
            if c["descs"]:
                r["categories"] = json_or_none(c["descs"])
        p = policy.get(reg)
        if p:
            for col in ("conflict_policy", "whistleblower_policy", "doc_retention_policy"):
                if p.get(col):
                    r[col] = 1
        t = trustee.get(reg)
        if t:
            r["voting_members"] = t["count"] or None
            if t.get("chair"):
                r["ceo_name"] = t["chair"]
                r["ceo_title"] = "Chair"
        cs = areas.get(reg)
        if cs:
            r["foreign_countries"] = json_or_none(sorted(cs))
            r["foreign_activities"] = 1
        if reg in audited_flag:
            r["accounts_qualified"] = audited_flag[reg]


def build_rows_for_year(
    target_year: str,
    meta: dict[str, dict],
    ar_file: Path,
    parta_file: Path | None,
    partb_file: Path | None,
) -> dict[tuple, dict]:
    """Build {(reg, target_year): row} from a single AR cycle year.
    Re-reads the AR + parta + partb files filtering by year; trades I/O for
    memory. Per-charity overlays (gov, classif, policy, etc.) are applied
    by the caller after this returns."""
    rows: dict[tuple, dict] = {}
    for row in read_pipe(ar_file):
        reg = to_str(row.get("registered_charity_number"), 50)
        if not reg or reg not in meta:
            continue
        year = to_year(
            row.get("fin_period_end_date") or row.get("ar_cycle_reference")
        )
        if year != target_year:
            continue
        r = _make_row(meta[reg], year)
        r["total_revenue"] = to_int(row.get("total_gross_income"))
        r["total_expenses"] = to_int(row.get("total_gross_expenditure"))
        rows[(reg, year)] = r

    if partb_file and rows:
        for row in read_pipe(partb_file):
            reg = to_str(row.get("registered_charity_number"), 50)
            if not reg:
                continue
            year = to_year(
                row.get("fin_period_end_date") or row.get("ar_cycle_reference")
            )
            if year != target_year:
                continue
            target = rows.get((reg, year))
            if target is not None:
                _apply_partb_row(target, row)

    if parta_file and rows:
        for row in read_pipe(parta_file):
            reg = to_str(row.get("registered_charity_number"), 50)
            if not reg:
                continue
            year = to_year(
                row.get("fin_period_end_date") or row.get("ar_cycle_reference")
            )
            if year != target_year:
                continue
            target = rows.get((reg, year))
            if target is not None:
                _apply_parta_row(target, row)

    return rows


def build_meta_only_rows(
    meta: dict[str, dict],
    regs_already_inserted: set[str],
) -> dict[tuple, dict]:
    """For charities that never appeared in any AR cycle (or whose cycles
    fell outside the year cap), insert a single row using the meta-level
    latest_income / latest_expenditure fallback."""
    rows: dict[tuple, dict] = {}
    for reg, m in meta.items():
        if reg in regs_already_inserted:
            continue
        r = _make_row(m, m["latest_year"])
        r["total_revenue"] = m["latest_income"]
        r["total_expenses"] = m["latest_expenditure"]
        rows[(reg, m["latest_year"])] = r
    return rows


def build_rows(
    mode: str,
    main_file: Path,
    ar_file: Path | None,
    parta_file: Path | None,
    partb_file: Path | None,
    area_file: Path | None,
    gov_file: Path | None,
    class_file: Path | None,
    policy_file: Path | None,
    trustee_file: Path | None,
) -> dict[tuple, dict]:
    print(f"  Reading main register: {main_file.name}", flush=True)
    meta = process_charity_meta(main_file)

    rows: dict[tuple, dict] = {}

    if mode == "all":
        if ar_file:
            print(f"  Enumerating AR cycles: {ar_file.name}", flush=True)
            for row in read_pipe(ar_file):
                reg = to_str(row.get("registered_charity_number"), 50)
                if not reg or reg not in meta:
                    continue
                year = to_year(
                    row.get("fin_period_end_date") or row.get("ar_cycle_reference")
                ) or "0"
                r = _make_row(meta[reg], year)
                r["total_revenue"] = to_int(row.get("total_gross_income"))
                r["total_expenses"] = to_int(row.get("total_gross_expenditure"))
                rows[(reg, year)] = r
        regs_seen = {k[0] for k in rows}
        for reg, m in meta.items():
            if reg in regs_seen:
                continue
            r = _make_row(m, m["latest_year"])
            r["total_revenue"] = m["latest_income"]
            r["total_expenses"] = m["latest_expenditure"]
            rows[(reg, m["latest_year"])] = r
    else:
        for reg, m in meta.items():
            r = _make_row(m, m["latest_year"])
            r["total_revenue"] = m["latest_income"]
            r["total_expenses"] = m["latest_expenditure"]
            rows[(reg, m["latest_year"])] = r

    # ── Layer partb financials (richer than ar_history; only filed by
    #    charities with income above £500k).
    if partb_file:
        print(f"  Merging partb financials: {partb_file.name}", flush=True)
        for row in read_pipe(partb_file):
            reg = to_str(row.get("registered_charity_number"), 50)
            if not reg:
                continue
            if mode == "latest":
                if not _is_latest_cycle(row):
                    continue
                m = meta.get(reg)
                target = rows.get((reg, m["latest_year"])) if m else None
            else:
                year = to_year(
                    row.get("fin_period_end_date") or row.get("ar_cycle_reference")
                ) or "0"
                target = rows.get((reg, year))
            if target is not None:
                _apply_partb_row(target, row)

    # ── Layer parta (volunteers + grant-making flag).
    if parta_file:
        print(f"  Merging parta data: {parta_file.name}", flush=True)
        for row in read_pipe(parta_file):
            reg = to_str(row.get("registered_charity_number"), 50)
            if not reg:
                continue
            if mode == "latest":
                if not _is_latest_cycle(row):
                    continue
                m = meta.get(reg)
                target = rows.get((reg, m["latest_year"])) if m else None
            else:
                year = to_year(
                    row.get("fin_period_end_date") or row.get("ar_cycle_reference")
                ) or "0"
                target = rows.get((reg, year))
            if target is not None:
                _apply_parta_row(target, row)

    # ── Per-charity overlays applied to every (reg, year) row for that charity.
    gov = process_governing(gov_file) if gov_file else {}
    classif = process_classification(class_file) if class_file else {}
    policy = process_policy(policy_file) if policy_file else {}
    trustee = process_trustee(trustee_file) if trustee_file else {}
    areas = process_areas(area_file) if area_file else {}
    audited_flag = process_ar_history(ar_file) if ar_file else {}

    if gov:
        print(f"  Mission overlay from governing-document: {len(gov)} regs", flush=True)
    if classif:
        print(f"  Classification overlay: {len(classif)} regs", flush=True)
    if policy:
        print(f"  Policy overlay: {len(policy)} regs", flush=True)
    if trustee:
        print(f"  Trustee overlay: {len(trustee)} regs", flush=True)
    if areas:
        print(f"  Area-of-operation overlay: {len(areas)} regs", flush=True)
    if audited_flag:
        print(f"  Accounts-qualified overlay: {len(audited_flag)} regs", flush=True)

    if mode == "all":
        rows = _cap_years_per_charity(rows, 5)

    for (reg, _year), r in rows.items():
        if reg in gov:
            r["mission"] = gov[reg]
        c = classif.get(reg)
        if c:
            for i, d in enumerate(c["descs"][:3], 1):
                r[f"program_desc{i}"] = to_str(d, 65000)
            r["program_count"] = len(c["descs"]) or None
            r["operates_hospital"] = c["hospital"]
            r["operates_school"] = c["school"]
            if c["descs"]:
                r["categories"] = json_or_none(c["descs"])
        p = policy.get(reg)
        if p:
            for col in ("conflict_policy", "whistleblower_policy", "doc_retention_policy"):
                if p.get(col):
                    r[col] = 1
        t = trustee.get(reg)
        if t:
            r["voting_members"] = t["count"] or None
            if t.get("chair"):
                r["ceo_name"] = t["chair"]
                r["ceo_title"] = "Chair"
        cs = areas.get(reg)
        if cs:
            r["foreign_countries"] = json_or_none(sorted(cs))
            r["foreign_activities"] = 1
        if reg in audited_flag:
            r["accounts_qualified"] = audited_flag[reg]

    return rows


# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------

def _find(files: list[Path], substr: str) -> Path | None:
    for f in files:
        if substr in f.name.lower():
            return f
    return None


def build_argparser() -> argparse.ArgumentParser:
    p = argparse.ArgumentParser(description="Load UK CCEW charity register into MySQL")
    p.add_argument("--host", default="127.0.0.1")
    p.add_argument("--port", type=int, default=3306)
    p.add_argument("--user", default="root")
    p.add_argument(
        "--password",
        default=os.environ.get("CHARITY_DB_PASSWORD", ""),
        help="MySQL password. Prefer the CHARITY_DB_PASSWORD environment "
             "variable so the credential stays out of the process list.",
    )
    p.add_argument("--database", default="irs990")
    p.add_argument(
        "--input",
        default=None,
        help=(
            "Path to a CCEW .txt/.csv file or a directory containing them. "
            "If omitted, files are downloaded automatically from the CCEW website."
        ),
    )
    p.add_argument(
        "--mode",
        choices=("latest", "all"),
        default="latest",
        help=(
            "latest (default): one row per charity using its most recent filing. "
            "all: one row per (charity, fiscal year) covering every AR cycle."
        ),
    )
    return p


def main() -> int:
    args = build_argparser().parse_args()

    _tmp = None
    try:
        input_is_url = args.input is not None and args.input.startswith("http")
        if args.input is None or input_is_url:
            page_url = args.input if input_is_url else DOWNLOAD_PAGE
            _tmp = tempfile.TemporaryDirectory(prefix="ccew_")
            tmp_dir = Path(_tmp.name)
            auto_download(tmp_dir, page_url=page_url)
            input_path = tmp_dir
        else:
            input_path = Path(args.input)

        files = iter_input_files(input_path, "*.txt") + iter_input_files(input_path, "*.csv")
        if not files and input_path.is_file():
            files = [input_path]

        # 'publicextract.charity.' (with trailing dot) only matches the main
        # register file; underscore-suffixed siblings like
        # publicextract.charity_annual_return_history.txt are skipped.
        main_file = next(
            (f for f in files
             if "publicextract.charity." in f.name.lower()
                or f.name.lower().endswith("_charity.txt")),
            None,
        )
        if not main_file:
            print("  No main charity file found.", flush=True)
            return 1

        partb_file = _find(files, "annual_return_partb")
        parta_file = _find(files, "annual_return_parta")
        ar_file = _find(files, "annual_return_history")
        area_file = _find(files, "area_of_operation")
        gov_file = _find(files, "governing_document")
        class_file = _find(files, "classification")
        policy_file = _find(files, "policy")
        trustee_file = _find(files, "trustee")

        # ── Year-batched streaming path (--mode all) ─────────────────────
        # Loads meta + per-charity overlays once (~400 MB), then processes
        # one AR cycle year at a time and bulk-inserts before moving on.
        # Peak memory stays bounded regardless of how many years exist.
        if args.mode == "all" and ar_file is not None:
            import gc

            print(f"  Reading main register: {main_file.name}", flush=True)
            meta = process_charity_meta(main_file)

            print("  Loading per-charity overlays …", flush=True)
            gov = process_governing(gov_file) if gov_file else {}
            classif = process_classification(class_file) if class_file else {}
            policy = process_policy(policy_file) if policy_file else {}
            trustee = process_trustee(trustee_file) if trustee_file else {}
            areas = process_areas(area_file) if area_file else {}
            audited_flag = process_ar_history(ar_file) if ar_file else {}

            print(f"  Discovering top years in: {ar_file.name}", flush=True)
            top_years = discover_top_years(ar_file, cap=5)
            print(f"  Will process {len(top_years)} year(s): {', '.join(top_years)}", flush=True)

            conn = connect(args)
            total_inserted = 0
            regs_inserted: set[str] = set()
            try:
                for year in top_years:
                    print(f"  ── Year {year}: building rows …", flush=True)
                    year_rows = build_rows_for_year(
                        year, meta, ar_file, parta_file, partb_file,
                    )
                    if not year_rows:
                        print(f"    (no rows for {year})", flush=True)
                        continue
                    apply_per_charity_overlays(
                        year_rows, gov, classif, policy, trustee, areas, audited_flag,
                    )
                    rows_list = [r for r in year_rows.values() if r["name"]]
                    n = bulk_insert(conn, rows_list)
                    total_inserted += n
                    regs_inserted.update(k[0] for k in year_rows)
                    print(f"    inserted {n} rows for {year} (running total: {total_inserted})", flush=True)
                    # Free per-year structures before processing the next year
                    year_rows.clear()
                    rows_list.clear()
                    del year_rows, rows_list
                    gc.collect()

                # Charities not seen in any of the top years → meta-only fallback
                fallback = build_meta_only_rows(meta, regs_inserted)
                if fallback:
                    apply_per_charity_overlays(
                        fallback, gov, classif, policy, trustee, areas, audited_flag,
                    )
                    fallback_list = [r for r in fallback.values() if r["name"]]
                    n = bulk_insert(conn, fallback_list)
                    total_inserted += n
                    print(f"  Inserted {n} meta-only rows (no AR cycle in top years)", flush=True)
            finally:
                conn.close()

            print(f"  Inserted/updated {total_inserted} CCEW rows.", flush=True)
            return 0

        # ── Original single-batch path (--mode latest) ───────────────────
        rows = build_rows(
            args.mode, main_file, ar_file, parta_file, partb_file,
            area_file, gov_file, class_file, policy_file, trustee_file,
        )

        rows_list = [r for r in rows.values() if r["name"]]
        if not rows_list:
            print("  No CCEW rows parsed.", flush=True)
            return 1

        conn = connect(args)
        try:
            n = bulk_insert(conn, rows_list)
            print(f"  Inserted/updated {n} CCEW rows.", flush=True)
        finally:
            conn.close()

    finally:
        if _tmp is not None:
            _tmp.cleanup()

    return 0


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