#!/usr/bin/env python3
"""
Load IRS 990 XML filings into a MySQL database.

Extracts all fields needed by both parse_990s.py and score_charities.py,
computes the 4R charity scores, and stores everything in MySQL indexed by EIN.
Also saves city and state from the filer address.

Usage:
    python load_to_mysql.py [--host HOST] [--port PORT] [--user USER]
                            [--password PASSWORD] [--database DATABASE]

Requires: mysql-connector-python (pip install mysql-connector-python)
"""

import argparse
import json
import math
import os
import re
import sys
import xml.etree.ElementTree as ET
from pathlib import Path

try:
    # Hardened parser: refuses DTDs and entity expansion ("billion laughs"
    # DoS). Optional so pre-existing hosts keep working; install it via
    # requirements.txt for full protection.
    import defusedxml.ElementTree as SafeET
except ImportError:  # pragma: no cover
    SafeET = None

import mysql.connector

NS = "{http://www.irs.gov/efile}"

# ---------------------------------------------------------------------------
# Religious keyword lists (from score_charities.py)
# ---------------------------------------------------------------------------
RELIGIOUS_KEYWORDS_STRONG = [
    "church",
    "mosque",
    "synagogue",
    "temple",
    "cathedral",
    "chapel",
    "diocese",
    "archdiocese",
    "parish",
    "congregation",
    "seminary",
    "monastery",
    "convent",
    "abbey",
]
RELIGIOUS_KEYWORDS_MODERATE = [
    "ministry",
    "ministries",
    "gospel",
    "bible",
    "biblical",
    "scripture",
    "christian",
    "baptist",
    "methodist",
    "lutheran",
    "catholic",
    "presbyterian",
    "episcopal",
    "pentecostal",
    "evangelical",
    "apostolic",
    "orthodox",
    "jewish",
    "islamic",
    "muslim",
    "hindu",
    "buddhist",
    "sikh",
    "faith",
    "worship",
    "prayer",
    "spiritual",
    "divinity",
    "theology",
    "missionary",
    "missionaries",
    "religious",
    "salvation",
    "covenant",
    "revival",
    "crusade",
    "discipleship",
    "pastor",
    "imam",
    "rabbi",
]

CEO_TITLES = [
    "CHIEF EXECUTIVE",
    "CEO",
    "EXECUTIVE DIRECTOR",
    "EXEC DIR",
    "EXEC. DIR",
    "PRESIDENT AND CEO",
    "PRESIDENT/CEO",
    "PRESIDENT & CEO",
]

# ---------------------------------------------------------------------------
# FIPS 10-4 country code -> estimated annual median income (USD, PPP)
# Used for ARK AID Recipient metric: score = min(100, 50000 / median_income)
# Countries <$500 are floored to $500 (score=100%), >$6000 score approaches 0%
# IRS uses FIPS codes, NOT ISO 3166 — ~30 codes differ.
# ---------------------------------------------------------------------------
FIPS_MEDIAN_INCOME = {
    "AF": 600,  # Afghanistan
    "AL": 5500,  # Albania
    "AG": 4500,  # Algeria
    "AQ": 2000,  # American Samoa
    "AN": 28000,  # Andorra
    "AO": 3500,  # Angola
    "AV": 15000,  # Antigua and Barbuda
    "AR": 12000,  # Argentina
    "AM": 4500,  # Armenia
    "AS": 45000,  # Australia
    "AU": 40000,  # Austria
    "AJ": 5000,  # Azerbaijan
    "BF": 20000,  # Bahamas
    "BA": 25000,  # Bahrain
    "BG": 1800,  # Bangladesh
    "BB": 13000,  # Barbados
    "BO": 7000,  # Belarus
    "BE": 38000,  # Belgium
    "BH": 5500,  # Belize
    "BN": 1200,  # Benin
    "BT": 3500,  # Bhutan
    "BL": 3800,  # Bolivia
    "BK": 6000,  # Bosnia and Herzegovina
    "BC": 8000,  # Botswana
    "BR": 9000,  # Brazil
    "BX": 35000,  # Brunei
    "BU": 9000,  # Bulgaria
    "UV": 800,  # Burkina Faso
    "BM": 1500,  # Burma (Myanmar)
    "BY": 600,  # Burundi
    "CB": 1600,  # Cambodia
    "CM": 1600,  # Cameroon
    "CA": 38000,  # Canada
    "CV": 3500,  # Cape Verde
    "CT": 500,  # Central African Republic
    "CD": 800,  # Chad
    "CI": 14000,  # Chile
    "CH": 10000,  # China
    "CO": 6500,  # Colombia
    "CN": 800,  # Comoros
    "CG": 500,  # Congo (Dem. Rep.) [FIPS=CG for DRC]
    "CF": 2500,  # Congo (Rep.)
    "CS": 11000,  # Costa Rica
    "IV": 2500,  # Cote d'Ivoire
    "HR": 14000,  # Croatia
    "CU": 5000,  # Cuba
    "CY": 28000,  # Cyprus
    "EZ": 22000,  # Czech Republic
    "DA": 42000,  # Denmark
    "DJ": 2000,  # Djibouti
    "DO": 7000,  # Dominica
    "DR": 8000,  # Dominican Republic
    "EC": 6000,  # Ecuador
    "EG": 3500,  # Egypt
    "ES": 4500,  # El Salvador
    "EK": 10000,  # Equatorial Guinea
    "ER": 800,  # Eritrea
    "EN": 20000,  # Estonia
    "WZ": 3000,  # Eswatini (Swaziland)
    "ET": 900,  # Ethiopia
    "FJ": 5000,  # Fiji
    "FI": 38000,  # Finland
    "FR": 36000,  # France
    "GB": 4500,  # Gabon
    "GA": 800,  # Gambia
    "GG": 5000,  # Georgia
    "GM": 40000,  # Germany
    "GH": 2500,  # Ghana
    "GR": 20000,  # Greece
    "GJ": 8000,  # Grenada
    "GT": 5000,  # Guatemala
    "GV": 1200,  # Guinea
    "PU": 1500,  # Guinea-Bissau
    "GY": 5000,  # Guyana
    "HA": 800,  # Haiti
    "HO": 2800,  # Honduras
    "HU": 16000,  # Hungary
    "IC": 42000,  # Iceland
    "IN": 2200,  # India
    "ID": 4500,  # Indonesia
    "IR": 6000,  # Iran
    "IZ": 5000,  # Iraq
    "EI": 45000,  # Ireland
    "IS": 30000,  # Israel
    "IT": 32000,  # Italy
    "JM": 5500,  # Jamaica
    "JA": 35000,  # Japan
    "JO": 4500,  # Jordan
    "KZ": 10000,  # Kazakhstan
    "KE": 1800,  # Kenya
    "KR": 2000,  # Kiribati
    "KN": 1800,  # North Korea
    "KS": 32000,  # South Korea
    "KU": 35000,  # Kuwait
    "KG": 1500,  # Kyrgyzstan
    "LA": 2800,  # Laos
    "LG": 16000,  # Latvia
    "LE": 8000,  # Lebanon
    "LT": 1500,  # Lesotho
    "LI": 600,  # Liberia
    "LY": 7000,  # Libya
    "LS": 80000,  # Liechtenstein
    "LH": 20000,  # Lithuania
    "LU": 60000,  # Luxembourg
    "MK": 6500,  # North Macedonia
    "MA": 500,  # Madagascar
    "MI": 600,  # Malawi
    "MY": 11000,  # Malaysia
    "MV": 10000,  # Maldives
    "ML": 900,  # Mali
    "MT": 25000,  # Malta
    "RM": 3000,  # Marshall Islands
    "MR": 1500,  # Mauritania
    "MP": 11000,  # Mauritius
    "MX": 9000,  # Mexico
    "FM": 3500,  # Micronesia
    "MD": 4000,  # Moldova
    "MN": 4500,  # Mongolia
    "MJ": 9000,  # Montenegro
    "MO": 3500,  # Morocco
    "MZ": 500,  # Mozambique
    "WA": 5500,  # Namibia
    "NR": 10000,  # Nauru
    "NP": 1200,  # Nepal
    "NL": 42000,  # Netherlands
    "NZ": 35000,  # New Zealand
    "NU": 2500,  # Nicaragua
    "NG": 600,  # Niger
    "NI": 2500,  # Nigeria
    "NO": 50000,  # Norway
    "MU": 20000,  # Oman
    "PK": 1600,  # Pakistan
    "PS": 14000,  # Palau
    "PM": 6000,  # Panama
    "PP": 2800,  # Papua New Guinea
    "PA": 5500,  # Paraguay
    "PE": 6500,  # Peru
    "RP": 3800,  # Philippines
    "PL": 16000,  # Poland
    "PO": 22000,  # Portugal
    "QA": 50000,  # Qatar
    "RO": 13000,  # Romania
    "RS": 12000,  # Russia
    "RW": 800,  # Rwanda
    "SC": 8000,  # Saint Kitts and Nevis
    "ST": 8000,  # Saint Lucia
    "VC": 7500,  # Saint Vincent and the Grenadines
    "WS": 4500,  # Samoa
    "SM": 35000,  # San Marino
    "TP": 2000,  # Sao Tome and Principe
    "SA": 25000,  # Saudi Arabia
    "SG": 1500,  # Senegal
    "RI": 7500,  # Serbia
    "SE": 15000,  # Seychelles
    "SL": 500,  # Sierra Leone
    "SN": 55000,  # Singapore
    "LO": 18000,  # Slovakia
    "SI": 25000,  # Slovenia
    "BP": 2000,  # Solomon Islands
    "SO": 500,  # Somalia
    "SF": 7000,  # South Africa
    "OD": 500,  # South Sudan
    "SP": 28000,  # Spain
    "CE": 4000,  # Sri Lanka
    "SU": 1500,  # Sudan
    "NS": 6000,  # Suriname
    "SW": 42000,  # Sweden
    "SZ": 52000,  # Switzerland
    "SY": 1500,  # Syria
    "TW": 25000,  # Taiwan
    "TI": 1200,  # Tajikistan
    "TZ": 1100,  # Tanzania
    "TH": 7000,  # Thailand
    "TT": 2200,  # Timor-Leste
    "TO": 700,  # Togo
    "TN": 5500,  # Tonga
    "TD": 12000,  # Trinidad and Tobago
    "TS": 4000,  # Tunisia
    "TU": 12000,  # Turkey
    "TX": 7500,  # Turkmenistan
    "TV": 4000,  # Tuvalu
    "UG": 900,  # Uganda
    "UP": 4000,  # Ukraine
    "AE": 40000,  # United Arab Emirates
    "UK": 38000,  # United Kingdom
    "US": 35000,  # United States
    "UY": 12000,  # Uruguay
    "UZ": 2500,  # Uzbekistan
    "NH": 3000,  # Vanuatu
    "VE": 3500,  # Venezuela
    "VM": 3000,  # Vietnam
    "YM": 800,  # Yemen
    "ZA": 1500,  # Zambia
    "ZI": 1200,  # Zimbabwe
    "RQ": 22000,  # Puerto Rico
    "GQ": 14000,  # Guam
    "VQ": 20000,  # US Virgin Islands
    "WQ": 4000,  # Wake Island
    "CQ": 3000,  # Northern Mariana Islands
}

# Fallback median incomes for Schedule F broad regions (USD, PPP)
SCHEDULE_F_REGION_MEDIAN = {
    "central america and the caribbean": 5000,
    "east asia and the pacific": 6000,
    "europe (including iceland & greenland)": 25000,
    "europe (including iceland and greenland)": 25000,
    "middle east and north africa": 6000,
    "north america": 30000,
    "russia and neighboring states": 8000,
    "russia and the newly independent states": 8000,
    "south america": 7000,
    "south asia": 2000,
    "sub-saharan africa": 1500,
}


# ---------------------------------------------------------------------------
# XML helpers
# ---------------------------------------------------------------------------
def t(el, tag):
    child = el.find(f"{NS}{tag}")
    if child is not None and child.text:
        return child.text.strip()
    return None


def ti(el, tag):
    v = t(el, tag)
    if v is None:
        return None
    try:
        return int(v)
    except ValueError:
        try:
            return int(float(v))
        except ValueError:
            return None


def tf(el, tag):
    v = t(el, tag)
    if v is None:
        return None
    try:
        return float(v)
    except ValueError:
        return None


def tbool(el, tag):
    v = t(el, tag)
    if v is None:
        return False
    return v.lower() in ("true", "1", "x")


def safe_div(a, b):
    if not b or b == 0:
        return 0.0
    if a is None:
        return 0.0
    return a / b


def is_ceo_title(title):
    if not title:
        return False
    upper = title.upper()
    return any(kw in upper for kw in CEO_TITLES)


# ---------------------------------------------------------------------------
# Field extraction (merged from both scripts)
# ---------------------------------------------------------------------------
def extract_header(root):
    header = root.find(f"{NS}ReturnHeader")
    if header is None:
        return None

    filer = header.find(f"{NS}Filer")
    if filer is None:
        return None

    ein = t(filer, "EIN")
    if not ein:
        return None

    bname = filer.find(f"{NS}BusinessName")
    name = ""
    if bname is not None:
        name = t(bname, "BusinessNameLine1Txt") or ""
        line2 = t(bname, "BusinessNameLine2Txt")
        if line2:
            name += " " + line2
    name = name or "Unknown"

    form_type = t(header, "ReturnTypeCd") or ""
    tax_year = t(header, "TaxYr") or ""

    # Address
    city = None
    state = None
    us_addr = filer.find(f"{NS}USAddress")
    if us_addr is not None:
        city = t(us_addr, "CityNm")
        state = t(us_addr, "StateAbbreviationCd")
    else:
        foreign_addr = filer.find(f"{NS}ForeignAddress")
        if foreign_addr is not None:
            city = t(foreign_addr, "CityNm")
            state = t(foreign_addr, "ProvinceOrStateNm")

    officer = header.find(f"{NS}BusinessOfficerGrp")
    officer_name = t(officer, "PersonNm") if officer is not None else None
    officer_title = t(officer, "PersonTitleTxt") if officer is not None else None

    return {
        "ein": ein,
        "name": name,
        "form_type": form_type,
        "tax_year": tax_year,
        "city": city,
        "state": state,
        "officer_name": officer_name,
        "officer_title": officer_title,
    }


def extract_from_990(doc, root):
    d = {}
    d["total_revenue_cy"] = ti(doc, "CYTotalRevenueAmt")
    d["total_revenue_py"] = ti(doc, "PYTotalRevenueAmt")
    d["total_expenses"] = ti(doc, "CYTotalExpensesAmt")
    d["program_expenses"] = ti(doc, "TotalProgramServiceExpensesAmt")
    d["fundraising_expenses"] = ti(doc, "CYTotalFundraisingExpenseAmt")
    d["grants_paid"] = ti(doc, "CYGrantsAndSimilarPaidAmt")
    d["salaries"] = ti(doc, "CYSalariesCompEmpBnftPaidAmt")
    d["total_assets"] = ti(doc, "TotalAssetsEOYAmt")
    d["net_assets"] = ti(doc, "NetAssetsOrFundBalancesEOYAmt")
    d["gross_receipts"] = ti(doc, "GrossReceiptsAmt")

    func_exp = doc.find(f"{NS}TotalFunctionalExpensesGrp")
    if func_exp is not None:
        d["mgmt_expenses"] = ti(func_exp, "ManagementAndGeneralAmt")
        d["fundraising_func"] = ti(func_exp, "FundraisingAmt")
    else:
        d["mgmt_expenses"] = None
        d["fundraising_func"] = None

    d["mission"] = t(doc, "ActivityOrMissionDesc") or t(doc, "MissionDesc") or ""
    d["program_desc1"] = t(doc, "Desc") or ""
    p2 = doc.find(f"{NS}ProgSrvcAccomActy2Grp")
    d["program_desc2"] = t(p2, "Desc") if p2 is not None else ""
    p3 = doc.find(f"{NS}ProgSrvcAccomActy3Grp")
    d["program_desc3"] = t(p3, "Desc") if p3 is not None else ""

    prog_count = 1 if d["program_desc1"] else 0
    if d["program_desc2"]:
        prog_count += 1
    if d["program_desc3"]:
        prog_count += 1
    for _ in doc.findall(f"{NS}ProgSrvcAccomActyOtherGrp"):
        prog_count += 1
    d["program_count"] = prog_count

    d["voting_members"] = ti(doc, "VotingMembersGoverningBodyCnt") or ti(
        doc, "GoverningBodyVotingMembersCnt"
    )
    d["independent_members"] = ti(doc, "VotingMembersIndependentCnt") or ti(
        doc, "IndependentVotingMemberCnt"
    )
    d["employees"] = ti(doc, "TotalEmployeeCnt")
    d["volunteers"] = ti(doc, "TotalVolunteersCnt")
    d["conflict_policy"] = tbool(doc, "ConflictOfInterestPolicyInd")
    d["whistleblower_policy"] = tbool(doc, "WhistleblowerPolicyInd")
    d["doc_retention_policy"] = tbool(doc, "DocumentRetentionPolicyInd")
    d["form990_to_board"] = tbool(doc, "Form990ProvidedToGvrnBodyInd")
    d["audited"] = tbool(doc, "IndependentAuditFinclStmtInd") or tbool(
        doc, "ConsolidatedAuditFinclStmtInd"
    )
    d["comp_process_ceo"] = tbool(doc, "CompensationProcessCEOInd")

    d["grants_to_orgs"] = tbool(doc, "GrantsToOrganizationsInd")
    d["grants_to_individuals"] = tbool(doc, "GrantsToIndividualsInd")
    d["foreign_activities"] = tbool(doc, "ForeignActivitiesInd")
    d["operates_hospital"] = tbool(doc, "OperateHospitalInd")
    d["operates_school"] = tbool(doc, "SchoolOperatingInd")

    d["is_501c3"] = tbool(doc, "Organization501c3Ind")
    d["described_501c3"] = tbool(doc, "DescribedInSection501c3Ind")

    d["schedule_a_filed"] = False
    ret_data = root.find(f"{NS}ReturnData")
    if ret_data is not None:
        for child in ret_data:
            if "ScheduleA" in child.tag:
                d["schedule_a_filed"] = True
                break

    max_comp = 0
    best_officer = None
    for grp in doc.findall(f"{NS}Form990PartVIISectionAGrp"):
        comp = ti(grp, "ReportableCompFromOrgAmt") or 0
        other_comp = ti(grp, "OtherCompensationAmt") or 0
        total = comp + other_comp
        pname = t(grp, "PersonNm")
        ptitle = t(grp, "TitleTxt")
        if is_ceo_title(ptitle) and best_officer is None:
            best_officer = {"name": pname, "title": ptitle, "comp": comp}
        if total > max_comp:
            max_comp = total
            if best_officer is None:
                best_officer = {"name": pname, "title": ptitle, "comp": comp}
    d["ceo_comp"] = max_comp
    d["_best_officer"] = best_officer

    return d


def extract_from_990ez(doc, root):
    d = {}
    d["total_revenue_cy"] = ti(doc, "TotalRevenueAmt")
    d["total_revenue_py"] = None
    d["total_expenses"] = ti(doc, "TotalExpensesAmt")
    d["program_expenses"] = ti(doc, "TotalProgramServiceExpensesAmt")
    d["fundraising_expenses"] = None
    d["grants_paid"] = ti(doc, "GrantsAndSimilarAmountsPaidAmt")
    d["salaries"] = ti(doc, "SalariesOtherCompEmplBnftAmt")
    d["total_assets"] = None
    d["mgmt_expenses"] = None
    d["fundraising_func"] = None
    d["gross_receipts"] = ti(doc, "GrossReceiptsAmt")

    grp = doc.find(f"{NS}Form990TotalAssetsGrp")
    if grp is not None:
        d["total_assets"] = ti(grp, "EOYAmt")

    d["net_assets"] = None
    net_grp = doc.find(f"{NS}NetAssetsOrFundBalancesGrp")
    if net_grp is not None:
        d["net_assets"] = ti(net_grp, "EOYAmt")

    d["mission"] = t(doc, "PrimaryExemptPurposeTxt") or t(doc, "ActivityOrMissionDesc") or ""
    d["program_desc1"] = ""
    d["program_desc2"] = ""
    d["program_desc3"] = ""

    prog_count = 0
    for i, grp_name in enumerate(
        ["ProgSrvcAccomActy2Grp", "ProgSrvcAccomActy3Grp", "ProgSrvcAccomActyOtherGrp"]
    ):
        grp = doc.find(f"{NS}{grp_name}")
        if grp is not None:
            desc = t(grp, "Desc") or t(grp, "DescriptionProgramSrvcAccomTxt") or ""
            if desc:
                prog_count += 1
                if i == 0:
                    d["program_desc1"] = desc
                elif i == 1:
                    d["program_desc2"] = desc
                else:
                    d["program_desc3"] = desc

    if t(doc, "Desc"):
        prog_count += 1
        if not d["program_desc1"]:
            d["program_desc1"] = t(doc, "Desc")

    d["program_count"] = max(prog_count, 1 if d["mission"] else 0)

    d["voting_members"] = None
    d["independent_members"] = None
    d["employees"] = None
    d["volunteers"] = None
    d["conflict_policy"] = False
    d["whistleblower_policy"] = False
    d["doc_retention_policy"] = False
    d["form990_to_board"] = False
    d["audited"] = False
    d["comp_process_ceo"] = False

    d["grants_to_orgs"] = (d["grants_paid"] or 0) > 0
    d["grants_to_individuals"] = False
    d["foreign_activities"] = False
    d["operates_hospital"] = tbool(doc, "OperateHospitalInd")
    d["operates_school"] = tbool(doc, "SchoolOperatingInd")

    d["is_501c3"] = tbool(doc, "Organization501c3Ind")
    d["described_501c3"] = False
    d["schedule_a_filed"] = False
    ret_data = root.find(f"{NS}ReturnData")
    if ret_data is not None:
        for child in ret_data:
            if "ScheduleA" in child.tag:
                d["schedule_a_filed"] = True
                break

    max_comp = 0
    best_officer = None
    for grp in doc.findall(f"{NS}OfficerDirectorTrusteeEmplGrp"):
        pname = t(grp, "PersonNm")
        ptitle = t(grp, "TitleTxt")
        comp = ti(grp, "CompensationAmt") or 0
        if is_ceo_title(ptitle) and best_officer is None:
            best_officer = {"name": pname, "title": ptitle, "comp": comp}
        if comp > max_comp:
            max_comp = comp
            if best_officer is None:
                best_officer = {"name": pname, "title": ptitle, "comp": comp}
    d["ceo_comp"] = max_comp
    d["_best_officer"] = best_officer

    return d


def extract_from_990pf(doc, root):
    d = {}

    analysis = doc.find(f"{NS}AnalysisOfRevenueAndExpenses")
    if analysis is not None:
        d["total_revenue_cy"] = ti(analysis, "TotalRevAndExpnssAmt")
        d["total_expenses"] = ti(analysis, "TotalExpensesRevAndExpnssAmt")
        d["program_expenses"] = ti(analysis, "TotOprExpensesDsbrsChrtblAmt")
        d["grants_paid"] = ti(analysis, "ContriPaidRevAndExpnssAmt")
        d["salaries"] = ti(analysis, "CompOfcrDirTrstRevAndExpnssAmt")
    else:
        d["total_revenue_cy"] = None
        d["total_expenses"] = None
        d["program_expenses"] = None
        d["grants_paid"] = None
        d["salaries"] = None

    d["total_revenue_py"] = None
    d["fundraising_expenses"] = None
    d["fundraising_func"] = None
    d["mgmt_expenses"] = None
    d["gross_receipts"] = ti(doc, "FMVAssetsEOYAmt")

    bs = doc.find(f"{NS}Form990PFBalanceSheetsGrp")
    if bs is not None:
        d["total_assets"] = ti(bs, "TotalAssetsEOYAmt")
        d["net_assets"] = ti(bs, "TotNetAstOrFundBalancesEOYAmt")
    else:
        d["total_assets"] = ti(doc, "TotalAssetsEOYAmt")
        d["net_assets"] = None

    d["mission"] = t(doc, "ActivityOrMissionDesc") or ""
    d["program_desc1"] = ""
    d["program_desc2"] = ""
    d["program_desc3"] = ""
    d["program_count"] = 1 if d["mission"] else 0

    d["voting_members"] = None
    d["independent_members"] = None
    d["employees"] = None
    d["volunteers"] = None
    d["conflict_policy"] = False
    d["whistleblower_policy"] = False
    d["doc_retention_policy"] = False
    d["form990_to_board"] = False
    d["audited"] = False
    d["comp_process_ceo"] = False

    d["grants_to_orgs"] = (d["grants_paid"] or 0) > 0
    d["grants_to_individuals"] = False
    d["foreign_activities"] = False
    d["operates_hospital"] = False
    d["operates_school"] = False

    stmts = doc.find(f"{NS}StatementsRegardingActyGrp")
    if stmts is not None:
        d["foreign_activities"] = tbool(stmts, "ForeignAccountsQuestionInd")

    d["is_501c3"] = tbool(doc, "Organization501c3ExemptPFInd")
    d["described_501c3"] = False
    d["schedule_a_filed"] = False

    max_comp = 0
    best_officer = None
    for grp in doc.findall(f"{NS}OfcrDirTrstKeyEmplInfoGrp"):
        for person in grp.findall(f"{NS}OfficerDirTrstKeyEmplGrp"):
            pname = t(person, "PersonNm")
            ptitle = t(person, "TitleTxt")
            comp = ti(person, "CompensationAmt") or 0
            if is_ceo_title(ptitle) and best_officer is None:
                best_officer = {"name": pname, "title": ptitle, "comp": comp}
            if comp > max_comp:
                max_comp = comp
                if best_officer is None:
                    best_officer = {"name": pname, "title": ptitle, "comp": comp}
    d["ceo_comp"] = max_comp
    d["_best_officer"] = best_officer

    return d


# ---------------------------------------------------------------------------
# Schedule F extraction (foreign activities)
# ---------------------------------------------------------------------------
def extract_schedule_f(root):
    """Extract Schedule F data and ForeignCountryCd from a filing."""
    result = {
        "schedule_f_filed": False,
        "foreign_countries": [],
        "foreign_grant_regions": {},  # region -> total_amount
        "foreign_individual_regions": {},  # region -> {"recipients": N, "amount": M}
        "foreign_offices": None,
        "foreign_employees": None,
        "foreign_expenditures": None,
    }

    ret_data = root.find(f"{NS}ReturnData")
    if ret_data is None:
        return result

    # Extract ForeignCountryCd from the main IRS990 form
    for child in ret_data:
        tag = child.tag.replace(NS, "")
        if tag in ("IRS990", "IRS990EZ", "IRS990PF"):
            for cc in child.findall(f"{NS}ForeignCountryCd"):
                if cc.text:
                    result["foreign_countries"].append(cc.text.strip())
            break

    # Find Schedule F
    sched_f = None
    for child in ret_data:
        if "IRS990ScheduleF" in child.tag:
            sched_f = child
            break

    if sched_f is None:
        return result

    result["schedule_f_filed"] = True

    # Part I totals
    total_offices = ti(sched_f, "TotalOfficeCnt")
    total_employees = ti(sched_f, "TotalEmployeeCnt")
    total_spent = ti(sched_f, "TotalSpentAmt")

    # If totals not present, sum from Part I rows
    if total_offices is None or total_employees is None or total_spent is None:
        sum_offices = 0
        sum_employees = 0
        sum_spent = 0
        for grp in sched_f.findall(f"{NS}AccountActivitiesOutsideUSGrp"):
            sum_offices += ti(grp, "OfficesCnt") or 0
            sum_employees += ti(grp, "EmployeeCnt") or 0
            sum_spent += ti(grp, "RegionTotalExpendituresAmt") or 0
        if total_offices is None:
            total_offices = sum_offices
        if total_employees is None:
            total_employees = sum_employees
        if total_spent is None:
            total_spent = sum_spent

    result["foreign_offices"] = total_offices
    result["foreign_employees"] = total_employees
    result["foreign_expenditures"] = total_spent

    # Part II: Grants to organizations outside US
    for grp in sched_f.findall(f"{NS}GrantsToOrgOutsideUSGrp"):
        region_el = grp.find(f"{NS}RegionTxt")
        if region_el is None or not region_el.text:
            continue
        region = region_el.text.strip()
        cash = ti(grp, "CashGrantAmt") or 0
        noncash = ti(grp, "NonCashAssistanceAmt") or 0
        total = cash + noncash
        if region in result["foreign_grant_regions"]:
            result["foreign_grant_regions"][region] += total
        else:
            result["foreign_grant_regions"][region] = total

    # Part III: Grants to individuals outside US
    for grp in sched_f.findall(f"{NS}ForeignIndividualsGrantsGrp"):
        region_el = grp.find(f"{NS}RegionTxt")
        if region_el is None or not region_el.text:
            continue
        region = region_el.text.strip()
        recipients = ti(grp, "RecipientCnt") or 0
        cash = ti(grp, "CashGrantAmt") or 0
        noncash = ti(grp, "NonCashAssistanceAmt") or 0
        total = cash + noncash
        if region in result["foreign_individual_regions"]:
            result["foreign_individual_regions"][region]["recipients"] += recipients
            result["foreign_individual_regions"][region]["amount"] += total
        else:
            result["foreign_individual_regions"][region] = {
                "recipients": recipients,
                "amount": total,
            }

    return result


def _region_median_income(region_text):
    """Look up median income for a Schedule F region string."""
    key = region_text.lower().strip()
    # Try exact match first
    if key in SCHEDULE_F_REGION_MEDIAN:
        return SCHEDULE_F_REGION_MEDIAN[key]
    # Try substring match
    for region_key, income in SCHEDULE_F_REGION_MEDIAN.items():
        if region_key in key or key in region_key:
            return income
    return 6000  # unknown region fallback (world-ish median)


def _country_need_score(fips_code):
    """Compute ARK AID need score for a country: min(100, 50000 / median_income).
    Clamped: income <500 -> 100, income >50000 -> 1."""
    income = FIPS_MEDIAN_INCOME.get(fips_code, 6000)
    income = max(500, income)
    return min(100, 50000 / income)


# ---------------------------------------------------------------------------
# Scoring functions — ARK AID methodology
# ---------------------------------------------------------------------------
def score_revenue(d):
    """ARK AID Revenue metric: input/output ratio (0-100).
    Uses measurable foreign outflow as the numerator:
    Schedule F Part I foreign expenditures first, then Part II+III assistance."""
    total_rev = d["total_revenue_cy"] or 0
    foreign_exp = d.get("foreign_expenditures") or 0
    countries = d.get("foreign_countries") or []
    grant_regions = d.get("foreign_grant_regions") or {}
    indiv_regions = d.get("foreign_individual_regions") or {}
    prog_exp = d.get("program_expenses") or 0
    foreign_acts = d.get("foreign_activities") or False
    foreign_assistance = 0
    has_foreign_evidence = bool(
        foreign_acts or countries or grant_regions or indiv_regions
    )

    for amount in grant_regions.values():
        if isinstance(amount, (int, float)):
            foreign_assistance += amount
    for info in indiv_regions.values():
        if isinstance(info, dict):
            foreign_assistance += info.get("amount", 0) or 0

    if total_rev <= 0:
        return 50.0 if (foreign_exp > 0 or foreign_assistance > 0) else 25.0

    if foreign_exp > 0:
        ratio = foreign_exp / total_rev
    elif foreign_assistance > 0:
        ratio = foreign_assistance / total_rev
    elif has_foreign_evidence and prog_exp > 0:
        ratio = prog_exp / total_rev
    else:
        ratio = 0

    return round(min(100, max(0, ratio * 100)), 1)


def score_religious(d, org_name):
    """ARK AID Religious metric: Identity (50pts) + Integrity (50pts) -> 0-100.
    Identity: keyword detection in name/mission + church indicator.
    Integrity: requires manual review; defaults to 25/50 (not assessed)."""
    # --- Identity (50 pts) ---
    identity = 0.0
    name_lower = (org_name or "").lower()
    mission_lower = (d["mission"] or "").lower()
    all_desc = " ".join(
        [
            d.get("program_desc1", "") or "",
            d.get("program_desc2", "") or "",
            d.get("program_desc3", "") or "",
        ]
    ).lower()
    all_text = f"{name_lower} {mission_lower} {all_desc}"

    # Also scan Schedule F grant purposes for religious keywords
    grant_purposes = ""
    for region_data in (d.get("foreign_grant_regions") or {}).values():
        if isinstance(region_data, str):
            grant_purposes += " " + region_data.lower()

    # Name keywords (25 pts)
    name_hits = 0
    matched_name = []
    for kw in RELIGIOUS_KEYWORDS_STRONG:
        if re.search(r"\b" + re.escape(kw) + r"\b", name_lower):
            name_hits += 2
            matched_name.append(kw)
    for kw in RELIGIOUS_KEYWORDS_MODERATE:
        if re.search(r"\b" + re.escape(kw) + r"\b", name_lower):
            name_hits += 1
            matched_name.append(kw)
    identity += min(25, name_hits * 8)

    # Mission/description keywords (20 pts)
    mission_hits = 0
    for kw in RELIGIOUS_KEYWORDS_STRONG:
        if re.search(r"\b" + re.escape(kw) + r"\b", all_text):
            if kw not in matched_name:
                mission_hits += 2
    for kw in RELIGIOUS_KEYWORDS_MODERATE:
        if re.search(r"\b" + re.escape(kw) + r"\b", all_text):
            if kw not in matched_name:
                mission_hits += 1
    identity += min(20, mission_hits * 4)

    # Church indicator (5 pts) — 501c3 without Schedule A
    is_church_like = d["is_501c3"] and not d["schedule_a_filed"]
    if is_church_like and (name_hits > 0 or mission_hits > 0):
        identity += 5
    elif is_church_like:
        identity += 3

    identity = min(50, identity)

    # --- Integrity (50 pts) ---
    # Cannot be automated from IRS data; default to 50% credit (25 pts)
    integrity = 25.0

    return round(min(100, max(0, identity + integrity)), 1)


def score_recipient(d):
    """ARK AID Recipient metric: poverty level of beneficiaries (0-100).
    Uses Schedule F country/region data + median income lookup.
    Formula: min(100, 50000 / country_or_region_median_income)."""
    # --- Country-level need score (70 pts) ---
    need_score = None
    countries = d.get("foreign_countries") or []
    grant_regions = d.get("foreign_grant_regions") or {}
    indiv_regions = d.get("foreign_individual_regions") or {}

    # Strategy 1: Use Schedule F Part III recipient counts when available
    if indiv_regions:
        total_weight = 0
        weighted_score = 0

        for region, info in indiv_regions.items():
            if not isinstance(info, dict):
                continue
            recipients = int(info.get("recipients", 0) or 0)
            if recipients <= 0:
                continue
            median = _region_median_income(region)
            rs = min(100, 50000 / max(500, median))
            weighted_score += rs * recipients
            total_weight += recipients

        if total_weight > 0:
            need_score = weighted_score / total_weight

    # Strategy 2: Use Schedule F region amounts if recipient counts unavailable
    if need_score is None and (grant_regions or indiv_regions):
        total_weight = 0
        weighted_score = 0
        # Merge grant and individual region amounts
        all_regions = {}
        for region, amount in grant_regions.items():
            amt = amount if isinstance(amount, (int, float)) else 0
            all_regions[region] = all_regions.get(region, 0) + amt
        for region, info in indiv_regions.items():
            amt = info.get("amount", 0) if isinstance(info, dict) else 0
            all_regions[region] = all_regions.get(region, 0) + amt

        for region, amount in all_regions.items():
            median = _region_median_income(region)
            rs = min(100, 50000 / max(500, median))
            weight = max(amount, 1)  # at least 1 to avoid zero-weight
            weighted_score += rs * weight
            total_weight += weight

        if total_weight > 0:
            need_score = weighted_score / total_weight

    # Strategy 3: Use country list with equal weighting
    if need_score is None and countries:
        total_weight = 0
        weighted_score = 0
        for cc in countries:
            cs = _country_need_score(cc)
            weighted_score += cs
            total_weight += 1
        if total_weight > 0:
            need_score = weighted_score / total_weight

    # Strategy 4: Fallback based on foreign_activities flag
    if need_score is None:
        if d.get("foreign_activities"):
            need_score = 50.0  # foreign but no details
        else:
            need_score = 20.0  # domestic only, limited info

    country_pts = need_score * 0.70  # scale to 70 pts

    # --- Direct beneficiary bonus (30 pts) ---
    direct_pts = 0.0
    # Grants to individuals = direct aid (15 pts)
    if d.get("grants_to_individuals"):
        direct_pts += 15
    # Grant pass-through ratio (15 pts)
    total_exp = d.get("total_expenses") or 0
    grants = d.get("grants_paid") or 0
    if total_exp > 0:
        direct_pts += min(15, safe_div(grants, total_exp) * 15)

    return round(min(100, max(0, country_pts + direct_pts)), 1)


def score_results(d):
    """ARK AID Results metric: professionalism, specialization, concentration (0-100).
    Indicative only — Revenue/Religious/Recipient are themselves Results indicators."""
    # --- Professionalism (33 pts) ---
    prof_pts = 0.0
    emps = d.get("employees") or 0
    if emps > 0:
        prof_pts += min(20, math.log10(emps + 1) * 10)
    foreign_offices = d.get("foreign_offices") or 0
    prof_pts += min(13, foreign_offices * 3)

    # --- Specialization (33 pts) ---
    # Fewer programs = more specialized = higher score
    prog = d.get("program_count") or 0
    if prog <= 0:
        spec_pts = 16.0  # unknown, partial credit
    else:
        spec_pts = max(1, 33 - (prog - 1) * 8)

    # --- Concentration (34 pts) ---
    countries = d.get("foreign_countries") or []
    if countries:
        # Fewer countries = more concentrated
        conc_pts = max(5, 34 - (len(countries) - 1) * 3)
    else:
        # Fall back to governance indicators as proxy
        conc_pts = 0.0
        conc_pts += 5 if d.get("conflict_policy") else 0
        conc_pts += 5 if d.get("whistleblower_policy") else 0
        conc_pts += 4 if d.get("doc_retention_policy") else 0
        conc_pts += 4 if d.get("form990_to_board") else 0
        conc_pts += 5 if d.get("audited") else 0
        total_members = d.get("voting_members") or 0
        indep = d.get("independent_members") or 0
        if total_members > 0:
            conc_pts += safe_div(indep, total_members) * 6
        all_desc = " ".join(
            filter(
                None,
                [
                    d.get("mission", ""),
                    d.get("program_desc1", ""),
                    d.get("program_desc2", ""),
                    d.get("program_desc3", ""),
                ],
            )
        )
        conc_pts += min(5, len(all_desc) / 300)

    return round(min(100, max(0, prof_pts + spec_pts + conc_pts)), 1)


def _clip(value, max_len):
    """Truncate a string to its column length so one oversized field can't
    abort a whole executemany batch under strict SQL mode. Mirrors the
    to_str(..., max_len) convention of the other loaders."""
    if value is None:
        return None
    s = str(value)
    return s[:max_len] if len(s) > max_len else s


# ---------------------------------------------------------------------------
# Process one XML file
# ---------------------------------------------------------------------------
def process_xml(filepath):
    try:
        # ValueError also catches defusedxml's DefusedXmlException on files
        # that carry DTDs / entity definitions.
        tree = SafeET.parse(filepath) if SafeET else ET.parse(filepath)
    except (ET.ParseError, ValueError):
        return None

    root = tree.getroot()
    hdr = extract_header(root)
    if hdr is None:
        return None

    ret_data = root.find(f"{NS}ReturnData")
    if ret_data is None:
        return None

    form_type = hdr["form_type"]
    doc = None
    for child in ret_data:
        tag = child.tag.replace(NS, "")
        if tag == "IRS990" and form_type == "990":
            doc = child
            break
        elif tag == "IRS990EZ" and form_type == "990EZ":
            doc = child
            break
        elif tag == "IRS990PF" and form_type == "990PF":
            doc = child
            break

    if doc is None:
        for child in ret_data:
            tag = child.tag.replace(NS, "")
            if tag in ("IRS990", "IRS990EZ", "IRS990PF"):
                doc = child
                if tag == "IRS990":
                    form_type = "990"
                elif tag == "IRS990EZ":
                    form_type = "990EZ"
                else:
                    form_type = "990PF"
                break

    if doc is None:
        return None

    if form_type == "990":
        fields = extract_from_990(doc, root)
    elif form_type == "990EZ":
        fields = extract_from_990ez(doc, root)
    elif form_type == "990PF":
        fields = extract_from_990pf(doc, root)
    else:
        return None

    # Resolve CEO: prefer the officer found in the form, fall back to header
    best = fields.pop("_best_officer", None)
    ceo_name = hdr["officer_name"]
    ceo_title = hdr["officer_title"]
    ceo_comp = fields["ceo_comp"]
    if best:
        ceo_name = best.get("name") or ceo_name
        ceo_title = best.get("title") or ceo_title

    # Extract Schedule F data
    sf = extract_schedule_f(root)
    fields.update(sf)

    # Compute scores
    rev_score = score_revenue(fields)
    rel_score = score_religious(fields, hdr["name"])
    rec_score = score_recipient(fields)
    res_score = score_results(fields)
    composite = round(
        (rev_score * 0.50 + rel_score * 0.20 + rec_score * 0.15 + res_score * 0.15), 1
    )

    return {
        "country_code": "US",
        "sub_jurisdiction": None,
        "data_source": "IRS",
        "registration_number": _clip(hdr["ein"], 50),
        "ein": _clip(hdr["ein"], 20),
        "name": _clip(hdr["name"], 500),
        "form_type": form_type,
        "tax_year": hdr["tax_year"],
        "city": _clip(hdr["city"], 200),
        "state": _clip(hdr["state"], 50),
        "ceo_name": _clip(ceo_name, 300),
        "ceo_title": _clip(ceo_title, 300),
        "ceo_comp": ceo_comp,
        "total_revenue": fields["total_revenue_cy"],
        "total_revenue_py": fields["total_revenue_py"],
        "total_expenses": fields["total_expenses"],
        "program_expenses": fields["program_expenses"],
        "fundraising_expenses": fields["fundraising_expenses"],
        "mgmt_expenses": fields["mgmt_expenses"],
        "grants_paid": fields["grants_paid"],
        "salaries": fields["salaries"],
        "total_assets": fields["total_assets"],
        "net_assets": fields["net_assets"],
        "gross_receipts": fields["gross_receipts"],
        "mission": _clip(fields["mission"], 65000),
        "program_desc1": _clip(fields["program_desc1"], 65000),
        "program_desc2": _clip(fields["program_desc2"], 65000),
        "program_desc3": _clip(fields["program_desc3"], 65000),
        "program_count": fields["program_count"],
        "voting_members": fields["voting_members"],
        "independent_members": fields["independent_members"],
        "employees": fields["employees"],
        "volunteers": fields["volunteers"],
        "conflict_policy": fields["conflict_policy"],
        "whistleblower_policy": fields["whistleblower_policy"],
        "doc_retention_policy": fields["doc_retention_policy"],
        "form990_to_board": fields["form990_to_board"],
        "audited": fields["audited"],
        "comp_process_ceo": fields["comp_process_ceo"],
        "grants_to_orgs": fields["grants_to_orgs"],
        "grants_to_individuals": fields["grants_to_individuals"],
        "foreign_activities": fields["foreign_activities"],
        "operates_hospital": fields["operates_hospital"],
        "operates_school": fields["operates_school"],
        "is_501c3": fields["is_501c3"],
        "described_501c3": fields["described_501c3"],
        "schedule_a_filed": fields["schedule_a_filed"],
        "schedule_f_filed": sf["schedule_f_filed"],
        "foreign_countries": (
            json.dumps(sf["foreign_countries"]) if sf["foreign_countries"] else None
        ),
        "foreign_grant_regions": (
            json.dumps(sf["foreign_grant_regions"]) if sf["foreign_grant_regions"] else None
        ),
        "foreign_individual_regions": (
            json.dumps(sf["foreign_individual_regions"])
            if sf["foreign_individual_regions"]
            else None
        ),
        "foreign_offices": sf["foreign_offices"],
        "foreign_employees": sf["foreign_employees"],
        "foreign_expenditures": sf["foreign_expenditures"],
        "score_composite": composite,
        "score_revenue": rev_score,
        "score_religious": rel_score,
        "score_recipient": rec_score,
        "score_results": res_score,
    }


# ---------------------------------------------------------------------------
# MySQL schema & loading
# ---------------------------------------------------------------------------
CREATE_TABLE = """
CREATE TABLE IF NOT EXISTS charities (
    id                BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    ein               VARCHAR(20)  DEFAULT NULL,
    country_code      CHAR(2)      NOT NULL DEFAULT 'US',
    sub_jurisdiction  VARCHAR(8)   DEFAULT NULL,
    data_source       VARCHAR(16)  NOT NULL DEFAULT 'IRS',
    registration_number VARCHAR(50) NOT NULL,
    group_id          BIGINT UNSIGNED DEFAULT NULL,
    tax_year          VARCHAR(4)   NOT NULL,
    name              VARCHAR(500) NOT NULL DEFAULT '',
    form_type         VARCHAR(10)  NOT NULL DEFAULT '',
    city              VARCHAR(200) DEFAULT NULL,
    state             VARCHAR(50)  DEFAULT NULL,

    ceo_name          VARCHAR(300) DEFAULT NULL,
    ceo_title         VARCHAR(300) DEFAULT NULL,
    ceo_comp          BIGINT       DEFAULT NULL,

    total_revenue     BIGINT       DEFAULT NULL,
    total_revenue_py  BIGINT       DEFAULT NULL,
    total_expenses    BIGINT       DEFAULT NULL,
    program_expenses  BIGINT       DEFAULT NULL,
    fundraising_expenses BIGINT    DEFAULT NULL,
    mgmt_expenses     BIGINT       DEFAULT NULL,
    grants_paid       BIGINT       DEFAULT NULL,
    salaries          BIGINT       DEFAULT NULL,
    total_assets      BIGINT       DEFAULT NULL,
    net_assets        BIGINT       DEFAULT NULL,
    gross_receipts    BIGINT       DEFAULT NULL,

    mission           TEXT         DEFAULT NULL,
    program_desc1     TEXT         DEFAULT NULL,
    program_desc2     TEXT         DEFAULT NULL,
    program_desc3     TEXT         DEFAULT NULL,
    program_count     INT          DEFAULT NULL,

    voting_members    INT          DEFAULT NULL,
    independent_members INT        DEFAULT NULL,
    employees         INT          DEFAULT NULL,
    volunteers        INT          DEFAULT NULL,
    conflict_policy   BOOLEAN      NOT NULL DEFAULT FALSE,
    whistleblower_policy BOOLEAN   NOT NULL DEFAULT FALSE,
    doc_retention_policy BOOLEAN   NOT NULL DEFAULT FALSE,
    form990_to_board  BOOLEAN      NOT NULL DEFAULT FALSE,
    audited           BOOLEAN      NOT NULL DEFAULT FALSE,
    comp_process_ceo  BOOLEAN      NOT NULL DEFAULT FALSE,

    grants_to_orgs    BOOLEAN      NOT NULL DEFAULT FALSE,
    grants_to_individuals BOOLEAN  NOT NULL DEFAULT FALSE,
    foreign_activities BOOLEAN     NOT NULL DEFAULT FALSE,
    operates_hospital BOOLEAN      NOT NULL DEFAULT FALSE,
    operates_school   BOOLEAN      NOT NULL DEFAULT FALSE,

    is_501c3          BOOLEAN      NOT NULL DEFAULT FALSE,
    described_501c3   BOOLEAN      NOT NULL DEFAULT FALSE,
    schedule_a_filed  BOOLEAN      NOT NULL DEFAULT FALSE,

    schedule_f_filed  BOOLEAN      NOT NULL DEFAULT FALSE,
    foreign_countries JSON         DEFAULT NULL,
    foreign_grant_regions JSON     DEFAULT NULL,
    foreign_individual_regions JSON DEFAULT NULL,
    foreign_offices   INT          DEFAULT NULL,
    foreign_employees INT          DEFAULT NULL,
    foreign_expenditures BIGINT    DEFAULT NULL,

    score_composite   FLOAT        DEFAULT NULL,
    score_revenue     FLOAT        DEFAULT NULL,
    score_religious   FLOAT        DEFAULT NULL,
    score_recipient   FLOAT        DEFAULT NULL,
    score_results     FLOAT        DEFAULT NULL,

    PRIMARY KEY (id),
    UNIQUE KEY uniq_country_reg_year (country_code, registration_number, tax_year),
    INDEX idx_ein (ein),
    INDEX idx_country_code (country_code),
    INDEX idx_country_subjur (country_code, sub_jurisdiction),
    INDEX idx_reg_number (registration_number),
    INDEX idx_group_id (group_id),
    INDEX idx_tax_year (tax_year),
    INDEX idx_state (state),
    INDEX idx_city_state (city, state),
    INDEX idx_name (name(100)),
    INDEX idx_score_composite (score_composite)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
"""

INSERT_SQL = """
INSERT INTO charities (
    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,
    total_assets, net_assets, gross_receipts,
    mission, program_desc1, program_desc2, program_desc3, program_count,
    voting_members, independent_members, employees, volunteers,
    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, foreign_countries, foreign_grant_regions,
    foreign_individual_regions, foreign_offices, foreign_employees,
    foreign_expenditures,
    score_composite, score_revenue, score_religious, score_recipient, score_results
) VALUES (
    %(country_code)s, %(sub_jurisdiction)s, %(data_source)s, %(registration_number)s,
    %(ein)s, %(name)s, %(form_type)s, %(tax_year)s, %(city)s, %(state)s,
    %(ceo_name)s, %(ceo_title)s, %(ceo_comp)s,
    %(total_revenue)s, %(total_revenue_py)s, %(total_expenses)s, %(program_expenses)s,
    %(fundraising_expenses)s, %(mgmt_expenses)s, %(grants_paid)s, %(salaries)s,
    %(total_assets)s, %(net_assets)s, %(gross_receipts)s,
    %(mission)s, %(program_desc1)s, %(program_desc2)s, %(program_desc3)s, %(program_count)s,
    %(voting_members)s, %(independent_members)s, %(employees)s, %(volunteers)s,
    %(conflict_policy)s, %(whistleblower_policy)s, %(doc_retention_policy)s,
    %(form990_to_board)s, %(audited)s, %(comp_process_ceo)s,
    %(grants_to_orgs)s, %(grants_to_individuals)s, %(foreign_activities)s,
    %(operates_hospital)s, %(operates_school)s,
    %(is_501c3)s, %(described_501c3)s, %(schedule_a_filed)s,
    %(schedule_f_filed)s, %(foreign_countries)s, %(foreign_grant_regions)s,
    %(foreign_individual_regions)s, %(foreign_offices)s, %(foreign_employees)s,
    %(foreign_expenditures)s,
    %(score_composite)s, %(score_revenue)s, %(score_religious)s,
    %(score_recipient)s, %(score_results)s
) 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),
    voting_members = VALUES(voting_members),
    independent_members = VALUES(independent_members),
    employees = VALUES(employees),
    volunteers = VALUES(volunteers),
    conflict_policy = VALUES(conflict_policy),
    whistleblower_policy = VALUES(whistleblower_policy),
    doc_retention_policy = VALUES(doc_retention_policy),
    form990_to_board = VALUES(form990_to_board),
    audited = VALUES(audited),
    comp_process_ceo = VALUES(comp_process_ceo),
    grants_to_orgs = VALUES(grants_to_orgs),
    grants_to_individuals = VALUES(grants_to_individuals),
    foreign_activities = VALUES(foreign_activities),
    operates_hospital = VALUES(operates_hospital),
    operates_school = VALUES(operates_school),
    is_501c3 = VALUES(is_501c3),
    described_501c3 = VALUES(described_501c3),
    schedule_a_filed = VALUES(schedule_a_filed),
    schedule_f_filed = VALUES(schedule_f_filed),
    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),
    score_composite = score_composite,
    score_revenue = score_revenue,
    score_religious = score_religious,
    score_recipient = score_recipient,
    score_results = score_results
"""

BATCH_SIZE = 500


def main():
    parser = argparse.ArgumentParser(description="Load IRS 990 data into MySQL")
    parser.add_argument("--host", default="127.0.0.1")
    parser.add_argument("--port", type=int, default=3306)
    parser.add_argument("--user", default="root")
    parser.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.",
    )
    parser.add_argument("--database", default="irs990")
    parser.add_argument(
        "--xml-dir", default=None, help="Directory containing XML files (default: ./2026/)"
    )
    args = parser.parse_args()

    # The database name is interpolated into DDL (identifiers can't be bound
    # as parameters), so restrict it to a safe character set.
    if not re.fullmatch(r"[A-Za-z0-9_]+", args.database):
        print(f"ERROR: invalid database name {args.database!r} "
              f"(allowed: letters, digits, underscore)")
        sys.exit(2)

    # Connect to MySQL
    print(f"Connecting to MySQL at {args.host}:{args.port} as {args.user}...")
    conn = mysql.connector.connect(
        host=args.host,
        port=args.port,
        user=args.user,
        password=args.password,
    )
    cursor = conn.cursor()

    # Create database if needed
    cursor.execute(
        f"CREATE DATABASE IF NOT EXISTS `{args.database}` "
        f"CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci"
    )
    cursor.execute(f"USE `{args.database}`")
    cursor.execute(CREATE_TABLE)
    conn.commit()
    print(f"Using database `{args.database}`, table `charities`.")

    # Find XML files
    base_dir = Path(__file__).parent
    if args.xml_dir:
        xml_dir = Path(args.xml_dir)
    else:
        xml_dir = base_dir / "2026"
        if not xml_dir.exists():
            xml_dir = base_dir

    xml_files = sorted(xml_dir.glob("*_public.xml"))
    if not xml_files:
        xml_files = sorted(base_dir.glob("*_public.xml"))

    total = len(xml_files)
    if total == 0:
        print("No XML files found!")
        sys.exit(1)

    print(f"Found {total} XML files to process...")

    # Parse and keep ALL years per EIN (no deduplication). Records are
    # streamed into batched inserts so memory stays bounded by BATCH_SIZE
    # instead of scaling with the archive contents.
    inserted = 0
    errors = 0
    batch = []
    for i, fp in enumerate(xml_files):
        if (i + 1) % 500 == 0 or i == 0:
            print(f"  Parsing {i+1}/{total}...")

        rec = process_xml(fp)
        if rec:
            batch.append(rec)
        else:
            errors += 1

        if len(batch) >= BATCH_SIZE:
            cursor.executemany(INSERT_SQL, batch)
            conn.commit()
            inserted += len(batch)
            batch = []
            if inserted % 2000 == 0:
                print(f"  Inserted {inserted}...")

    if batch:
        cursor.executemany(INSERT_SQL, batch)
        conn.commit()
        inserted += len(batch)

    print(f"Parsed and inserted {inserted} filings ({errors} errors/skipped)")
    print(f"\nDone! Loaded {inserted} organizations into `{args.database}`.`charities`.")

    # Print summary
    cursor.execute("SELECT COUNT(*) FROM charities")
    count = cursor.fetchone()[0]
    cursor.execute("SELECT COUNT(DISTINCT state) FROM charities WHERE state IS NOT NULL")
    states = cursor.fetchone()[0]
    cursor.execute(
        "SELECT AVG(score_composite), MIN(score_composite), " "MAX(score_composite) FROM charities"
    )
    avg_s, min_s, max_s = cursor.fetchone()
    print(f"  Total rows: {count}")
    print(f"  States represented: {states}")
    if avg_s is not None:
        print(f"  Composite score: avg={avg_s:.1f}  min={min_s:.1f}  max={max_s:.1f}")

    cursor.close()
    conn.close()


if __name__ == "__main__":
    main()
