"""Resident population aged 18 and over by state, from the Census Bureau's Vintage 2025 state estimates, as declared in
after-review-r3.json: rows with SUMLEV 040, SEX 0 and ORIGIN 0, summed over RACE 1 to 6 and AGE 18 to 85 (85 stands for 85
and over), on 1 July 2021 (POPESTIMATE2021, for the 2022 cycle) and 1 July 2025 (POPESTIMATE2025, for the 2026 cycle).

The file's hash must match data/sources-r3.json. Before writing, three checks on the file's own arithmetic, so a misread
code cannot pass: for every state the SEX 0 total equals SEX 1 plus SEX 2, the ORIGIN 0 total equals ORIGIN 1 plus
ORIGIN 2, and every (state, sex, origin, race) holds each age from 0 to 85 exactly once.

Usage: python3 -I -B tools/population.py <dir holding census/sc-est2025-alldata6.csv> data/population_18plus.json
"""
import collections
import csv
import hashlib
import json
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
SRC = json.loads((ROOT / "data" / "sources-r3.json").read_text(encoding="utf-8"))
NAME = "census/sc-est2025-alldata6.csv"
FIELDS = {"2022": "POPESTIMATE2021", "2026": "POPESTIMATE2025"}
# state FIPS code: (postal code, name as the file spells it)
FIPS = {"01": ("AL", "Alabama"), "02": ("AK", "Alaska"), "04": ("AZ", "Arizona"), "05": ("AR", "Arkansas"),
        "06": ("CA", "California"), "08": ("CO", "Colorado"), "09": ("CT", "Connecticut"), "10": ("DE", "Delaware"),
        "11": ("DC", "District of Columbia"), "12": ("FL", "Florida"), "13": ("GA", "Georgia"), "15": ("HI", "Hawaii"),
        "16": ("ID", "Idaho"), "17": ("IL", "Illinois"), "18": ("IN", "Indiana"), "19": ("IA", "Iowa"),
        "20": ("KS", "Kansas"), "21": ("KY", "Kentucky"), "22": ("LA", "Louisiana"), "23": ("ME", "Maine"),
        "24": ("MD", "Maryland"), "25": ("MA", "Massachusetts"), "26": ("MI", "Michigan"), "27": ("MN", "Minnesota"),
        "28": ("MS", "Mississippi"), "29": ("MO", "Missouri"), "30": ("MT", "Montana"), "31": ("NE", "Nebraska"),
        "32": ("NV", "Nevada"), "33": ("NH", "New Hampshire"), "34": ("NJ", "New Jersey"), "35": ("NM", "New Mexico"),
        "36": ("NY", "New York"), "37": ("NC", "North Carolina"), "38": ("ND", "North Dakota"), "39": ("OH", "Ohio"),
        "40": ("OK", "Oklahoma"), "41": ("OR", "Oregon"), "42": ("PA", "Pennsylvania"), "44": ("RI", "Rhode Island"),
        "45": ("SC", "South Carolina"), "46": ("SD", "South Dakota"), "47": ("TN", "Tennessee"), "48": ("TX", "Texas"),
        "49": ("UT", "Utah"), "50": ("VT", "Vermont"), "51": ("VA", "Virginia"), "53": ("WA", "Washington"),
        "54": ("WV", "West Virginia"), "55": ("WI", "Wisconsin"), "56": ("WY", "Wyoming")}


def adults(path, want_sha=None, fips=FIPS):
    """State totals of residents aged 18 and over, after the hash and the file's own arithmetic check out. want_sha and
    fips default to the recorded file and every state; the tests pass a planted file's own hash and its states."""
    want_sha = want_sha or next(f for f in SRC["files"] if f["file"] == NAME)["sha256"]
    got = hashlib.sha256(path.read_bytes()).hexdigest()
    if got != want_sha:
        raise SystemExit(f"{NAME}: sha256 {got} is not the recorded {want_sha}")
    total = collections.Counter()   # (state, sex, origin, field) -> adults, summed over race
    ages = collections.Counter()    # (state, sex, origin, race, age) -> rows
    names = {}
    with open(path, encoding="utf-8", newline="") as f:
        for r in csv.DictReader(f):
            if r["SUMLEV"] != "040" or r["STATE"] not in fips:
                continue
            assert r["RACE"] in {"1", "2", "3", "4", "5", "6"}, r["RACE"]
            st = fips[r["STATE"]][0]
            names[st] = r["NAME"]
            age = int(r["AGE"])
            ages[(st, r["SEX"], r["ORIGIN"], r["RACE"], age)] += 1
            if age >= 18:
                for field in FIELDS.values():
                    total[(st, r["SEX"], r["ORIGIN"], field)] += int(r[field])
    checks = {"states": len(names), "names_match": all(names.get(c) == n for c, n in fips.values())}
    assert checks["states"] == len(fips) and checks["names_match"], checks
    for st, _ in fips.values():
        for sex in "012":
            for origin in "012":
                for race in "123456":
                    assert all(ages[(st, sex, origin, race, a)] == 1 for a in range(86)), (st, sex, origin, race)
        for field in FIELDS.values():
            for o in "012":
                assert total[(st, "0", o, field)] == total[(st, "1", o, field)] + total[(st, "2", o, field)], (st, o, field)
            assert total[(st, "0", "0", field)] == total[(st, "0", "1", field)] + total[(st, "0", "2", field)], (st, field)
    checks.update({"sex_totals_add_up": True, "origin_totals_add_up": True, "every_age_0_to_85_once": True})
    out = {c: {cycle: total[(c, "0", "0", field)] for cycle, field in FIELDS.items()} for c, _ in fips.values()}
    return out, checks


def main(data_dir, out_path):
    states, checks = adults(Path(data_dir) / NAME)
    doc = {"note": ("Resident population aged 18 and over on 1 July 2021 (key 2022, for the 2022 cycle) and 1 July 2025 "
                    "(key 2026), from the Census Bureau's Vintage 2025 state estimates, summed over race, origin and single "
                    "years of age 18 to 85 and over. Written by tools/population.py; see after-review-r3.json."),
           "source": next(f for f in SRC["files"] if f["file"] == NAME), "fields": FIELDS, "checks": checks,
           "states": states}
    Path(out_path).write_text(json.dumps(doc, indent=1, sort_keys=True) + "\n", encoding="utf-8")
    print(f"wrote {out_path}: {len(states)} states, checks {checks}")


if __name__ == "__main__":
    main(sys.argv[1], sys.argv[2])
