"""
Shared helpers for non-US charity loaders (CRA, CCEW, OSCR, CCNI).

Goal: write rows into the same `charities` table as load_to_mysql.py with the
multi-country columns populated. Score sub-fields are left NULL for sources
that don't expose Schedule-F-equivalent data; CharityScoreCalculator handles
nulls and renormalises the composite at read time.
"""
from __future__ import annotations

import argparse
import csv
import json
import os
import re
from pathlib import Path
from typing import Iterable, Iterator

try:
    import pymysql
except ImportError:  # pragma: no cover
    pymysql = None


# Same column order used by load_to_mysql.py's INSERT_SQL.
SHARED_COLUMNS = [
    "country_code", "sub_jurisdiction", "data_source", "registration_number",
    "ein", "name", "form_type", "tax_year", "city", "state",
    "ceo_name", "ceo_title", "ceo_comp",
    "total_revenue", "total_revenue_py", "total_expenses", "program_expenses",
    "fundraising_expenses", "mgmt_expenses", "grants_paid", "salaries",
    "sch3_band_counts",
    "total_assets", "net_assets", "gross_receipts",
    "mission", "program_desc1", "program_desc2", "program_desc3", "program_count",
    "categories",
    "voting_members", "independent_members", "employees", "volunteers",
    "conflict_policy", "whistleblower_policy", "doc_retention_policy",
    "form990_to_board", "audited", "accounts_qualified", "comp_process_ceo",
    "grants_to_orgs", "grants_to_individuals", "foreign_activities",
    "operates_hospital", "operates_school",
    "is_501c3", "described_501c3", "schedule_a_filed",
    "schedule_f_filed", "foreign_countries", "foreign_grant_regions",
    "foreign_individual_regions", "foreign_offices", "foreign_employees",
    "foreign_expenditures",
    "score_composite", "score_revenue", "score_religious", "score_recipient",
    "score_results", "score_confidence",
]


INSERT_SQL = f"""
INSERT INTO charities ({", ".join(SHARED_COLUMNS)})
VALUES ({", ".join("%(" + c + ")s" for c in SHARED_COLUMNS)})
ON DUPLICATE KEY UPDATE
    name = VALUES(name),
    form_type = VALUES(form_type),
    city = VALUES(city),
    state = VALUES(state),
    ceo_name = VALUES(ceo_name),
    ceo_title = VALUES(ceo_title),
    ceo_comp = VALUES(ceo_comp),
    total_revenue = VALUES(total_revenue),
    total_revenue_py = VALUES(total_revenue_py),
    total_expenses = VALUES(total_expenses),
    program_expenses = VALUES(program_expenses),
    fundraising_expenses = VALUES(fundraising_expenses),
    mgmt_expenses = VALUES(mgmt_expenses),
    grants_paid = VALUES(grants_paid),
    salaries = VALUES(salaries),
    total_assets = VALUES(total_assets),
    net_assets = VALUES(net_assets),
    gross_receipts = VALUES(gross_receipts),
    mission = VALUES(mission),
    program_desc1 = VALUES(program_desc1),
    program_desc2 = VALUES(program_desc2),
    program_desc3 = VALUES(program_desc3),
    program_count = VALUES(program_count),
    categories = VALUES(categories),
    sch3_band_counts = VALUES(sch3_band_counts),
    accounts_qualified = VALUES(accounts_qualified),
    voting_members = VALUES(voting_members),
    independent_members = VALUES(independent_members),
    employees = VALUES(employees),
    volunteers = VALUES(volunteers),
    grants_to_orgs = VALUES(grants_to_orgs),
    grants_to_individuals = VALUES(grants_to_individuals),
    foreign_activities = VALUES(foreign_activities),
    foreign_countries = VALUES(foreign_countries),
    foreign_grant_regions = VALUES(foreign_grant_regions),
    foreign_individual_regions = VALUES(foreign_individual_regions),
    foreign_offices = VALUES(foreign_offices),
    foreign_employees = VALUES(foreign_employees),
    foreign_expenditures = VALUES(foreign_expenditures),
    schedule_f_filed = VALUES(schedule_f_filed),
    score_composite = VALUES(score_composite),
    score_revenue = VALUES(score_revenue),
    score_religious = VALUES(score_religious),
    score_recipient = VALUES(score_recipient),
    score_results = VALUES(score_results),
    score_confidence = VALUES(score_confidence)
"""


def empty_row() -> dict:
    """Return a dict with every shared column keyed to None / default."""
    row = {c: None for c in SHARED_COLUMNS}
    # Boolean columns are NOT NULL DEFAULT FALSE in the schema. Pre-fill 0 so
    # rows for sources that don't expose these flags still satisfy the schema.
    for boolcol in (
        "conflict_policy","whistleblower_policy","doc_retention_policy",
        "form990_to_board","audited","comp_process_ceo",
        "grants_to_orgs","grants_to_individuals","foreign_activities",
        "operates_hospital","operates_school",
        "is_501c3","described_501c3","schedule_a_filed","schedule_f_filed",
    ):
        row[boolcol] = 0
    row["name"] = ""
    row["form_type"] = ""
    return row


# --- Type coercion helpers ---------------------------------------------------

_MONEY_STRIP = re.compile(r"[^0-9.\-]")


def to_int(value) -> int | None:
    if value is None:
        return None
    if isinstance(value, (int,)):
        return value
    s = str(value).strip()
    if not s or s.lower() in ("null", "n/a", "na", "-"):
        return None
    s = _MONEY_STRIP.sub("", s)
    if s in ("", "-", "."):
        return None
    try:
        return int(float(s))
    except (TypeError, ValueError):
        return None


def to_float(value) -> float | None:
    if value is None:
        return None
    if isinstance(value, (int, float)):
        return float(value)
    s = str(value).strip()
    if not s or s.lower() in ("null", "n/a", "na", "-"):
        return None
    s = _MONEY_STRIP.sub("", s)
    if s in ("", "-", "."):
        return None
    try:
        return float(s)
    except (TypeError, ValueError):
        return None


def to_bool(value) -> int:
    if value is None:
        return 0
    if isinstance(value, bool):
        return 1 if value else 0
    s = str(value).strip().lower()
    return 1 if s in ("1", "y", "yes", "true", "t", "x", "on") else 0


def to_str(value, max_len: int | None = None) -> str | None:
    if value is None:
        return None
    s = str(value).strip()
    if not s:
        return None
    if max_len is not None and len(s) > max_len:
        s = s[:max_len]
    return s


def to_year(value) -> str | None:
    """Extract 4-digit year from various date formats."""
    if value is None:
        return None
    s = str(value).strip()
    if not s:
        return None
    m = re.search(r"(19|20)\d{2}", s)
    return m.group(0) if m else None


def json_or_none(value) -> str | None:
    if value in (None, "", [], {}):
        return None
    return json.dumps(value)


# --- CSV reading -------------------------------------------------------------

def iter_csv_rows(path: Path, encoding_candidates: Iterable[str] = ("utf-8-sig", "utf-8", "cp1252", "latin-1")) -> Iterator[dict]:
    """Yield rows from a CSV, trying multiple encodings (regulators ship inconsistent files)."""
    last_err = None
    for enc in encoding_candidates:
        try:
            with open(path, "r", encoding=enc, newline="") as f:
                reader = csv.DictReader(f)
                for row in reader:
                    yield {(k or "").strip(): (v.strip() if isinstance(v, str) else v) for k, v in row.items()}
            return
        except UnicodeDecodeError as e:
            last_err = e
            continue
    raise RuntimeError(f"Could not decode CSV {path}: {last_err}")


def iter_input_files(input_path: Path, pattern: str = "*.csv") -> list[Path]:
    """Resolve --input as either a single file or a directory of matching files."""
    if input_path.is_file():
        return [input_path]
    if input_path.is_dir():
        return sorted(input_path.rglob(pattern))
    return []


# --- DB plumbing -------------------------------------------------------------

def connect(args) -> "pymysql.connections.Connection":
    if pymysql is None:
        raise RuntimeError("pymysql is required. Install via `pip install pymysql`.")
    return pymysql.connect(
        host=args.host, port=args.port, user=args.user,
        password=args.password, database=args.database,
        charset="utf8mb4", autocommit=False,
    )


def bulk_insert(conn, rows: list[dict], batch_size: int = 500) -> int:
    if not rows:
        return 0
    cur = conn.cursor()
    inserted = 0
    for i in range(0, len(rows), batch_size):
        chunk = rows[i:i+batch_size]
        cur.executemany(INSERT_SQL, chunk)
        inserted += cur.rowcount
        conn.commit()
    cur.close()
    return inserted


def base_argparser(description: str) -> argparse.ArgumentParser:
    p = argparse.ArgumentParser(description=description)
    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", required=True, help="Path to source file or directory")
    return p
