"""Reconstruct Pittsburgh age-by-civilian-employment counts from ACS estimates.

    python3 reconstruct.py
    python3 reconstruct.py --source ./acs-tables --write-clip census.csv --output comparison.json

Download the two 2019–2023 ACS 5-year Detailed Table files named in the source
record to reproduce from the original releases. The bundled CSV includes each
selected source estimate and its published 90% margin of error. The fit uses
point estimates. The concordance below maps Detailed Table line numbers into
four broad age groups, summing the published male and female categories.
"""
import argparse
import csv
import hashlib
import io
import json
import math
import sys
from fractions import Fraction
from pathlib import Path


VERSION = "meridia.population-reconstruction.us-acs.v1"
BASE_URL = "https://www2.census.gov/programs-surveys/acs/summary_file/2023/table-based-SF/data/5YRData/"
TABLE_HASHES = {
    "B23001": "68fde2751e9c950cfaadc97d4b11471dc8ce674c74ffbb2a3295f8f7c60bc2f1",
    "B23025": "7b2b255b52a04442608579b8a6be60d486200352cec291d8ddb9e80a5741d203",
}
CLIP_SHA256 = "0d8d256de5936c8c87aed75f36bdcfa2d729d6754eb983ae6b18f01a9f13c0a0"
TARGET = "1600000US4261000"
DONOR = "1600000US3916000"
AGES = ("16 to 24 years", "25 to 54 years", "55 to 64 years", "65 years and over")
# Official B23001 table line numbers, combined across sexes: all residents
# (including Armed Forces) in the denominator, civilian employed in the numerator.
RESIDENTS = ((3, 10, 17, 89, 96, 103), (24, 31, 38, 45, 110, 117, 124, 131),
             (52, 59, 66, 138, 145, 152), (73, 78, 83, 159, 164, 169))
EMPLOYED = ((7, 14, 21, 93, 100, 107), (28, 35, 42, 49, 114, 121, 128, 135),
            (56, 63, 70, 142, 149, 156), (75, 80, 85, 161, 166, 171))
LINES = {"B23001": sorted({1} | {n for groups in (RESIDENTS, EMPLOYED) for group in groups for n in group}),
         "B23025": [1, 4]}
HEADER = ["GEO_ID", "variable", "estimate", "moe90"]


def source_filename(table):
    return f"acsdt5y2023-{table.lower()}.dat"


def roster():
    return [(geoid, f"{table}_E{n:03d}") for geoid in (TARGET, DONOR)
            for table, lines in LINES.items() for n in lines]


def parse_count(value):
    if not value.isascii() or not value.isdecimal():
        raise ValueError(f"A census cell contains a missing or invalid count: {value!r}.")
    return int(value)


def load_originals(directory):
    """Stream both full tables; hash every byte, retain only the selected cells."""
    cells = {}
    prefixes = tuple((city + "|").encode("ascii") for city in (TARGET, DONOR))
    for table, digest in TABLE_HASHES.items():
        hasher = hashlib.sha256()
        with (directory / source_filename(table)).open("rb") as source:
            first = source.readline()
            hasher.update(first)
            header = first.decode("ascii").strip().split("|")
            if header[0] != "GEO_ID" or len(set(header)) != len(header):
                raise ValueError(f"Unexpected {table} table header.")
            for line in source:
                hasher.update(line)
                if not line.startswith(prefixes):
                    continue
                fields = line.decode("ascii").rstrip("\r\n").split("|")
                if len(fields) != len(header):
                    raise ValueError(f"Unexpected column count for a selected {table} geography.")
                row = dict(zip(header, fields))
                for number in LINES[table]:
                    var = f"{table}_E{number:03d}"
                    key = (row["GEO_ID"], var)
                    if key in cells:
                        raise ValueError(f"Duplicate cell in {table}: {key}.")
                    cells[key] = (parse_count(row[var]), parse_count(row[f"{table}_M{number:03d}"]))
        if hasher.hexdigest() != digest:
            raise ValueError(f"{table} does not match the pinned ACS release SHA-256.")
    return cells


def load_clip(raw):
    if hashlib.sha256(raw).hexdigest() != CLIP_SHA256:
        raise ValueError("The extract does not match the published census.csv SHA-256.")
    reader = csv.reader(io.StringIO(raw.decode("utf-8"), newline=""))
    if next(reader, None) != HEADER:
        raise ValueError("Unexpected public extract columns.")
    cells = {}
    for geoid, variable, estimate, moe in reader:
        key = (geoid, variable)
        if key in cells:
            raise ValueError(f"Duplicate census estimate: {key}.")
        cells[key] = (parse_count(estimate), parse_count(moe))
    return cells


def load_source(path):
    cells = load_originals(path) if path.is_dir() else load_clip(path.read_bytes())
    keys = roster()
    if set(keys) != set(cells):
        raise ValueError("The extract must contain the 110 selected geography/variable cells.")
    text = io.StringIO(newline="")
    writer = csv.writer(text, lineterminator="\n")
    writer.writerow(HEADER)
    for key in keys:
        writer.writerow([*key, *cells[key]])
    clip = text.getvalue().encode("utf-8")
    if hashlib.sha256(clip).hexdigest() != CLIP_SHA256:
        raise ValueError("Selected source cells do not reproduce the pinned public extract.")
    return cells, clip


def apportion(expected, total):
    """Largest remainder, resolving equal fractional parts by the source age order."""
    integers = [math.floor(value) for value in expected]
    remaining = total - sum(integers)
    if not 0 <= remaining <= len(integers):
        raise ValueError("Fractional reconstruction does not match the employment target.")
    order = sorted(range(len(integers)), key=lambda i: expected[i] - integers[i], reverse=True)
    for index in order[:remaining]:
        integers[index] += 1
    return integers


def fit(populations, employed_total, donor_sizes, donor_employed):
    """Fit from marginals and donor cells. Target age-by-employment counts are never inputs."""
    if len(populations) != 4 or len(donor_sizes) != 4 or len(donor_employed) != 4:
        raise ValueError("Four nonoverlapping age groups are required.")
    if any(type(size) is not int or size <= 0 for size in [*populations, *donor_sizes]):
        raise ValueError("Age-group sizes must be positive counts.")
    if type(employed_total) is not int or not 0 < employed_total < sum(populations):
        raise ValueError("The target employed count must lie inside the population total.")
    if any(type(jobs) is not int or not 0 < jobs < size for jobs, size in zip(donor_employed, donor_sizes)):
        raise ValueError("Donor employment rates must lie strictly between zero and one.")
    baseline = [Fraction(size * employed_total, sum(populations)) for size in populations]
    log_odds = [math.log(jobs / (size - jobs)) for jobs, size in zip(donor_employed, donor_sizes)]

    def transferred(offset):
        return [size / (1 + math.exp(-odds - offset)) for size, odds in zip(populations, log_odds)]

    # At these two endpoints every group's fitted rate is respectively no
    # greater or no smaller than the required all-age rate.
    target_log_odds = math.log(employed_total / (sum(populations) - employed_total))
    low, high = target_log_odds - max(log_odds), target_log_odds - min(log_odds)
    for _ in range(80):
        middle = (low + high) / 2
        if sum(transferred(middle)) < employed_total:
            low = middle
        else:
            high = middle
    offset = (low + high) / 2
    return {"common_rate": apportion(baseline, employed_total),
            "transferred_rates": apportion(transferred(offset), employed_total)}, offset


def comparison(cells):
    def counts(city, groups):
        return [sum(cells[city, f"B23001_E{number:03d}"][0] for number in group) for group in groups]

    sizes = counts(TARGET, RESIDENTS)
    donor_sizes = counts(DONOR, RESIDENTS)
    donor_employed = counts(DONOR, EMPLOYED)
    employed_total, employed_moe = cells[TARGET, "B23025_E004"]
    reconstructions, offset = fit(sizes, employed_total, donor_sizes, donor_employed)

    observed = counts(TARGET, EMPLOYED)
    groups = [{"age": age, "population": size, "observed_employed": count,
               "observed_rate_pct": 100 * count / size,
               "donor_population": donor_size, "donor_employed": donor_count}
              for age, size, count, donor_size, donor_count in zip(AGES, sizes, observed, donor_sizes, donor_employed)]
    models = {}
    for key, counts_by_age in reconstructions.items():
        errors = [100 * (count - truth) / size for count, truth, size in zip(counts_by_age, observed, sizes)]
        models[key] = {"employed": counts_by_age,
                       "not_employed": [size - count for size, count in zip(sizes, counts_by_age)],
                       "rates_pct": [100 * count / size for count, size in zip(counts_by_age, sizes)],
                       "errors_pp": errors, "mae_pp": sum(map(abs, errors)) / len(errors),
                       "max_abs_error_pp": max(map(abs, errors))}
    models["transferred_rates"]["log_odds_offset"] = offset
    return {"version": VERSION,
            "source": {"publisher": "U.S. Census Bureau", "period": "2019–2023", "vintage": 2023,
                       "product": "American Community Survey 5-year Detailed Tables",
                       "tables": list(TABLE_HASHES), "universe": "Population age 16 and over",
                       "employment": "Civilian employed residents",
                       "complement": "All other residents age 16 and over, including Armed Forces.",
                       "geography": "incorporated place",
                       "url": "https://www.census.gov/programs-surveys/acs/data/summary-file.2023.html",
                       "files": {table: {"url": BASE_URL + source_filename(table), "sha256": digest,
                                          "variables": f"https://api.census.gov/data/2023/acs/acs5/groups/{table}.html"}
                                 for table, digest in TABLE_HASHES.items()},
                       "clip_sha256": CLIP_SHA256,
                       "uncertainty": "The extract includes 90% margins of error for the source cells. "
                                      "The descriptive scores use point estimates without propagating sampling uncertainty."},
            "target": {"city": "Pittsburgh", "state": "PA", "geoid": TARGET,
                       "population": sum(sizes), "published_population": cells[TARGET, "B23025_E001"][0],
                       "employed": employed_total, "employed_moe90": employed_moe},
            "donor": {"city": "Cleveland", "state": "OH", "geoid": DONOR},
            "groups": groups, "models": models}


def main():
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("--source", type=Path, default=Path(__file__).with_name("census.csv"),
                        help="Published census.csv extract or directory containing both original .dat files")
    parser.add_argument("--write-clip", type=Path, help="Write the verified 110-cell CSV extract")
    parser.add_argument("--output", type=Path, help="Write the comparison JSON (default: standard output)")
    args = parser.parse_args()
    files = [path.resolve() for path in (args.source, args.write_clip, args.output) if path is not None]
    if len(set(files)) != len(files):
        parser.error("Use distinct source, clip destination and JSON destination paths.")
    try:
        cells, clip = load_source(args.source)
        result = json.dumps(comparison(cells), indent=2, allow_nan=False) + "\n"
        if args.write_clip:
            args.write_clip.write_bytes(clip)
        if args.output:
            args.output.write_bytes(result.encode("utf-8"))
        else:
            sys.stdout.write(result)
    except (OSError, ValueError) as error:
        parser.exit(1, f"{parser.prog}: {error}\n")


if __name__ == "__main__":
    main()
