#!/usr/bin/env python3
"""
Loader for the Charity Commission for Northern Ireland (CCNI) register.

Source: https://www.charitycommissionni.org.uk/charity-search/ (CSV export)
CCNI ships a single CSV with one row per charity.
Sub-jurisdiction = 'NI'.
"""
from __future__ import annotations

import sys
from pathlib import Path

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


def process(path: Path) -> list[dict]:
    out: list[dict] = []
    for raw in iter_csv_rows(path):
        row = {(k or "").strip().lower(): v for k, v in raw.items()}
        reg = to_str(row.get("reg charity number") or row.get("charity number") or row.get("nic"), 50)
        if not reg:
            continue
        year = to_year(row.get("date for financial year ending") or row.get("financial year end")) or "0"

        r = empty_row()
        r.update({
            "country_code": "GB",
            "sub_jurisdiction": "NI",
            "data_source": "CCNI",
            "registration_number": reg,
            "ein": None,
            "name": to_str(row.get("charity name"), 500) or "",
            "form_type": "AR",
            "tax_year": year,
            "city": to_str(row.get("public address") or row.get("town"), 200),
            "state": to_str(row.get("district"), 50),
            "mission": to_str(row.get("what the charity does") or row.get("public benefits"), 65000),
            "total_revenue": to_int(row.get("total income")),
            "total_expenses": to_int(row.get("total spending") or row.get("total expenditure")),
            "total_assets": to_int(row.get("total assets")),
            "employees": to_int(row.get("number of employees") or row.get("employees")),
            "volunteers": to_int(row.get("number of volunteers") or row.get("volunteers")),
        })

        # Foreign work: CCNI exposes 'where the charity operates' as a free-text list.
        op_where = (row.get("where the charity operates") or "").strip()
        if op_where:
            entries = [e.strip() for e in op_where.replace(";", ",").split(",") if e.strip()]
            non_uk = [e for e in entries if e.lower() not in (
                "northern ireland", "ni", "uk", "united kingdom", "england", "scotland", "wales",
            )]
            if non_uk:
                r["foreign_countries"] = json_or_none(sorted(set(non_uk)))
                r["foreign_activities"] = 1

        out.append(r)
    return out


def main() -> int:
    parser = base_argparser("Load CCNI (Northern Ireland) charity register into MySQL")
    args = parser.parse_args()
    input_path = Path(args.input)

    csvs = iter_input_files(input_path, "*.csv") or [input_path]
    rows: list[dict] = []
    for csv_path in csvs:
        print(f"  Parsing {csv_path.name}", flush=True)
        rows.extend(process(csv_path))

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

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


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