"""The Room Study: reproduce the 2025 SHED parent co-residence age bands.

Download the 2025 CSV ZIP from:
https://www.federalreserve.gov/consumerscommunities/shed_data.htm
Extract public2025.csv, then run:
    python young-adults-living-with-parents-reproduce.py public2025.csv
Python 3 standard library only. Prints aggregate results; writes no respondent data.
Prepared 14 October 2026. No network access, API key or paid software needed.
"""
import csv
import hashlib
import json
import math
import sys
from pathlib import Path

EXPECTED_SHA256 = 'c728d566008309c9abd87a026069ee70c2b58e7aef2d5c701884d371101d2a97'
path = Path(sys.argv[1]) if len(sys.argv) == 2 else None
if path is None:
    raise SystemExit('Usage: python young-adults-living-with-parents-reproduce.py public2025.csv')
checksum = hashlib.sha256(path.read_bytes()).hexdigest()
if checksum != EXPECTED_SHA256:
    raise SystemExit('The source file differs from our checked July 2026 version. Review the Federal Reserve revision notes before comparing results.')

# The analysed column names and values are ASCII; Latin-1 preserves file bytes.
with path.open(encoding='latin-1', newline='') as stream:
    rows = [{k: r[k] for k in ['ppage','L0_d','weight','L0_d_iflag']} for r in csv.DictReader(stream)]
assert len(rows) == 12934
results = []
for lo, hi in [(18,24),(25,29),(30,34),(35,44),(18,29)]:
    band = [r for r in rows if lo <= int(r['ppage']) <= hi]
    assert all(r['L0_d'] in ('Yes','No') and float(r['weight']) > 0 for r in band)
    weighted = lambda rs: math.fsum(float(r['weight']) for r in rs)
    yes = weighted([r for r in band if r['L0_d'] == 'Yes'])
    total = weighted(band)
    observed = [r for r in band if float(r['L0_d_iflag']) == 0]
    results.append(dict(age_min=lo,age_max=hi,weighted_percent=100*yes/total,
        unweighted_respondents=len(band),unweighted_yes=sum(r['L0_d']=='Yes' for r in band),
        imputed_answers=len(band)-len(observed),weighted_yes=yes,weighted_denominator=total,
        percent_excluding_imputed=100*weighted([r for r in observed if r['L0_d']=='Yes'])/weighted(observed)))
print(json.dumps(dict(source_sha256=checksum,results=results),indent=2))
