"""Portable recomputation of E17 selected public CSVs; no original ZIP or network required."""
from pathlib import Path
from fractions import Fraction as Q
from collections import defaultdict,Counter
import csv,json,hashlib
BASE=Path(__file__).resolve().parent;SOURCE=BASE/'econ17-sources';M={}
def read(name):
 with (SOURCE/name).open(encoding='utf-8-sig',newline='') as f:return list(csv.DictReader(f))
def put(key,value):M[key]=Q(value)
def frac(s):return Q(s.replace(',',''))
levels=read('actual-BEA-fixed-vintage-GDP-levels-and-derived-implicit-deflator.csv');quarters={}
for r in levels:
 p=r['period'];N=frac(r['sourceNominalToken']);Y=frac(r['sourceRealToken']);P=100*N/Y
 assert N==Q(r['nominalGDP']) and Y==Q(r['realGDP']) and P==Q(r['priceIndex'])
 for key,v in [('nominal',N),('real',Y),('derivedDeflator',P)]:put('country.'+p+'.'+key,v)
 if p!='annual2024':quarters[p]=(N,Y,P)
keys=sorted(quarters)
for a,b in zip(keys,keys[1:]):
 N0,Y0,P0=quarters[a];N1,Y1,P1=quarters[b];put('country.'+b+'.ordinaryRealGrowth',Y1/Y0-1);put('country.'+b+'.ordinaryDerivedDeflatorGrowth',P1/P0-1);put('country.'+b+'.annualizedRealFromRoundedLevels',(Y1/Y0)**4-1);put('country.'+b+'.annualizedDerivedDeflatorFromRoundedLevels',(P1/P0)**4-1)
for r in read('actual-BEA-published-price-and-deflator-annualized-rates.csv'):
 put('country.'+r['period']+'.publishedPriceAnnualizedPercent',r['publishedGDPPriceIndexAnnualizedPercent']);put('country.'+r['period']+'.publishedDeflatorAnnualizedPercent',r['publishedImplicitDeflatorAnnualizedPercent'])
people=read('actual9876-ACS-income-and-published-adjustment-factor.csv');available=[r for r in people if r['PINCP']!=''];weights=sum((Q(r['PWGTP']) for r in available),Q(0));rawTotal=sum((Q(r['PWGTP'])*Q(r['PINCP']) for r in available),Q(0));adjustedTotal=sum((Q(r['PWGTP'])*Q(r['PINCP'])*Q(r['ADJINC'])/1000000 for r in available),Q(0));put('person.sourceRows',len(people));put('person.available',len(available));put('person.unavailable',len(people)-len(available));put('person.availablePersonWeight',weights);put('person.weightedRawMean',rawTotal/weights);put('person.weightedAdjustedMean',adjustedTotal/weights)
for sign,label in [(-1,'negative'),(0,'zero'),(1,'positive')]:put('person.'+label,sum((Q(r['PINCP'])>0)-(Q(r['PINCP'])<0)==sign for r in available))
for r in read('actual-four-ACS-positions-raw-and-derived-constant-dollar-income.csv'):
 raw=Q(r['PINCP']);factor=Q(r['ADJINC'])/1000000;adjusted=raw*factor;assert adjusted==Q(r['adjustedIncome2024USDExact']);stem='person.row'+r['source_row_id']
 put(stem+'.nominal',raw);put(stem+'.factor',factor);put(stem+'.adjusted',adjusted);put(stem+'.weight',r['PWGTP'])
sku=read('actual2313-retail-SKU85123A-original-XML-tokens-and-inclusion-flags.csv');periods=read('derived13-retail-SKU-month-quantity-per-covered-day-and-weighted-price.csv');group=defaultdict(list)
for r in sku:
 q=Q(r['Quantity']);p=Q(r['UnitPriceXMLToken']);assert p==Q(r['UnitPriceGBPExact']);cancel=r['InvoiceNo'].lower().startswith('c');good=q>0 and p>0 and not cancel
 assert str(cancel)==r['isCancellation'] and str(good)==r['selectedPositiveNonCancellation']
 group[r['month']].append((q,p,good));
put('company.skuRows',len(sku));put('company.months',len(periods));put('company.cancellationRows',sum(r['isCancellation']=='True' for r in sku));monthValues={}
for r in periods:
 label=r['month'];rs=group[label];selected=[(q,p) for q,p,g in rs if g];qty=sum((q for q,p in selected),Q(0));amount=sum((q*p for q,p in selected),Q(0));days=Q(r['coveredCalendarDays']);weighted=amount/qty;rate=qty/days
 assert qty==Q(r['positiveQuantity']) and amount==Q(r['positiveAmountGBP']) and weighted==Q(r['weightedUnitPriceGBP']) and rate==Q(r['quantityPerCalendarDay'])
 for key,v in [('sourceRows',len(rs)),('positiveRows',len(selected)),('quantity',qty),('amount',amount),('days',days),('weightedPrice',weighted),('quantityPerDay',rate),('partial',int(r['partialCalendarMonth']=='True'))]:put('company.'+label+'.'+key,v)
 monthValues[label]=(rate,weighted)
q0,p0=monthValues['2011-01'];q1,p1=monthValues['2011-02'];put('company.JanFeb.quantityPerDayGrowth',q1/q0-1);put('company.JanFeb.weightedPriceGrowth',p1/p0-1)
for r in read('assumed-normalized-ADAS-scenarios-not-estimated.csv'):
 a,b,c,d,Pe=[Q(r[k]) for k in ['a','b','c','d','Pe']];P=(a-c+d*Pe)/(b+d);Y=a-b*P;assert Y==c+d*(P-Pe) and P==Q(r['assumedEquilibriumPrice']) and Y==Q(r['assumedEquilibriumOutput']);put('assumed.'+r['scenario']+'.P',P);put('assumed.'+r['scenario']+'.Y',Y)
inputs={p.name:hashlib.sha256(p.read_bytes()).hexdigest() for p in sorted(SOURCE.glob('*.csv'))}
result={'chapter':'ECON-17','scope':'Selected public CSV recomputation; actual source selection/authenticity peer and browser separate. Derived deflator from rounded levels is not a published index level.','metricCount':len(M),'inputHashes':inputs,'metrics':{k:{'exactFraction':str(v),'approximateValue':float(v)} for k,v in M.items()}}
(BASE/'econ17-results.json').write_text(json.dumps(result,ensure_ascii=False,indent=2)+'\n',encoding='utf-8');print(json.dumps({'metricCount':len(M),'sourceRows':len(people),'selectedSKURows':len(sku)}))
