#!/usr/bin/env python3
"""
Loader for the Scottish Charity Regulator (OSCR) register.

Source: https://www.oscr.org.uk/about-charities/search-the-register/download-the-scottish-charity-register/
OSCR publishes a single CSV with one row per charity (current state, not history).
Sub-jurisdiction = 'SC'.
"""
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("charity number") or row.get("scottish charity number"), 50)
        if not reg:
            continue
        year = to_year(row.get("year end") or row.get("financial year end")) or "0"

        r = empty_row()
        r.update({
            "country_code": "GB",
            "sub_jurisdiction": "SC",
            "data_source": "OSCR",
            "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("principal office/trustees address") or row.get("town"), 200),
            "state": to_str(row.get("local authority"), 50),
            "mission": to_str(row.get("activities") or row.get("purposes"), 65000),
            "total_revenue": to_int(row.get("most recent year income")),
            "total_expenses": to_int(row.get("most recent year expenditure")),
            "volunteers": to_int(row.get("approximate number of volunteers") or row.get("volunteers")),
        })

        # OSCR doesn't expose explicit overseas-activities flag, but lists "geographical
        # spread"; we capture non-UK entries as foreign_countries.
        spread = (row.get("geographical spread") or "").strip()
        if spread:
            countries = [c.strip() for c in spread.replace(";", ",").split(",") if c.strip()]
            non_uk = [c for c in countries if c.lower() not in (
                "scotland", "england", "wales", "northern ireland", "united kingdom", "uk",
            )]
            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 OSCR (Scotland) 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 OSCR rows parsed.", flush=True)
        return 1

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


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