"""The Room Study: 2024 RECS pre-1980 housing shares.
Usage: python us-housing-age-analysis.py recs2024_public_v1.csv > age-results.csv
Download the input from https://www.eia.gov/consumption/residential/data/2024/csv/recs2024_public_v1.csv
Source version: preliminary May 2026. Standard-library Python only.
Sixty jackknife replicate weights; approximate 95% intervals use +/- 2 SE.
All-tenure margins are benchmark-calibrated; their near-zero replicate errors
are NOT estimates of total uncertainty and are deliberately not published.
"""
import csv, math, sys

def analyze(path):
    regions = ['United States', 'Northeast', 'Midwest', 'South', 'West']
    groups = {(r,t): {'n':0,'den':[0.0]*61,'num':[0.0]*61}
              for r in regions for t in ['All','Owner','Renter']}
    with open(path, newline='', encoding='utf-8-sig') as handle:
        for item in csv.DictReader(handle):
            year, ownership = int(item['YEARMADERANGE']), int(item['KOWNRENT'])
            assert year in range(1,10) and ownership in (1,2,3)
            reg = item['REGIONC'].title()
            assert reg in regions[1:]
            weights = [float(item['NWEIGHT'+(str(i) if i else '')]) for i in range(61)]
            assert weights[0] > 0 and min(weights) >= 0
            for r in ['United States',reg]:
                for t in ['All','Owner' if ownership==1 else 'Renter']:
                    g=groups[r,t];g['n']+=1
                    for i,w in enumerate(weights):
                        g['den'][i]+=w
                        if year<=4:g['num'][i]+=w
    for (r,t),g in groups.items():
        estimates=[100*n/d for n,d in zip(g['num'],g['den'])]
        se=math.sqrt(59/60*sum((v-estimates[0])**2 for v in estimates[1:]))
        fixed=t=='All'
        yield [r,t,g['n'],g['den'][0],g['num'][0],estimates[0],
               '' if fixed else se,'' if fixed else estimates[0]-2*se,
               '' if fixed else estimates[0]+2*se,
               'ACS benchmark-calibrated; no interval' if fixed else 'Conditional jackknife; excludes nonsampling and benchmark error']

if __name__=='__main__':
    if len(sys.argv)!=2:raise SystemExit(__doc__)
    writer=csv.writer(sys.stdout)
    writer.writerow(['region','tenure','sample_n','weighted_homes','weighted_pre1980_homes','pre1980_percent_TRS','conditional_jackknife_SE_pp','approx_95_low','approx_95_high','uncertainty_note'])
    writer.writerows(analyze(sys.argv[1]))
