"""Reproduce ECON13 from official retained originals or disclosed public selections.
No cases JSON, model contract or earlier calculation result is a numerical input.
Original ACS records are public disclosure-protected values, not uncensored incomes.
"""
from pathlib import Path
from fractions import Fraction as F
from html.parser import HTMLParser
import csv,json,hashlib,re,subprocess,shutil,zipfile,io
O=Path(__file__).resolve().parent;D=O/'econ13-sources';A=O.parents[1]/'work/textbook-rewrite-2026/source-audit-econ13'
metrics={};exact={};audit={};checks=0;originalCells=0
def put(k,v):q=F(v);metrics[k]=float(q);exact[k]=str(q)
def selected(n):
 f=D/n;audit[n]={'sha256':hashlib.sha256(f.read_bytes()).hexdigest(),'mode':'public necessary source selection or derived verification target'};return list(csv.DictReader(f.open(encoding='utf8',newline='')))
def mark(f,mode):audit[f.name]={'sha256':hashlib.sha256(f.read_bytes()).hexdigest(),'mode':mode}
periods=['annual2024','2023Q4','2024Q1','2024Q2','2024Q3','2024Q4']
keys={'gdp':(9,1),'consumption':(9,2),'investment':(9,26),'exports':(10,44),'imports':(10,47),'government':(10,50),'gdi':(10,62),'income_receipts_rest_world':(10,69),'income_payments_rest_world':(10,70),'gnp':(10,71)}
ss=selected('actual-BEA-2025-03-27-vintage-GDP-expenditure-income-levels.csv');nom={};real={};original=A/'BEA-2024-GDP-third-estimate-2025-03-27.pdf'
if original.exists()and shutil.which('pdftotext'):
 mark(original,'retained original PDF, fresh pdftotext process, Table3 pages9/10')
 raw=subprocess.check_output(['pdftotext','-layout',str(original),'-'],text=True,encoding='utf8');pages=raw.split('\f')
 assert 'March 27, 2025'in raw and 'Real GDP increased 2.8 percent in 2024'in raw
 for key,(page,line)in keys.items():
  candidates=[re.findall(r'-?[\d,]+\.\d',row)for row in pages[page-1].splitlines()if re.search(r'\s'+str(line)+r'\s*$',row)]
  values=next(v for v in candidates if len(v)>=12)
  for i,period in enumerate(periods):nom[key,period]=F(values[i].replace(',',''));real[key,period]=F(values[i+6].replace(',',''))
 for r in ss:
  assert nom[r['measure'],r['period']]==F(r['current_billion_USD'])and real[r['measure'],r['period']]==F(r['chained2017_billion_USD']);checks+=2;originalCells+=2
else:
 audit['nationalAccountFallback']='Public original-table selections; no local complete-PDF replay.'
 for r in ss:nom[r['measure'],r['period']]=F(r['current_billion_USD']);real[r['measure'],r['period']]=F(r['chained2017_billion_USD'])
for key in keys:
 for period in periods:put('country_'+key+'_'+period+'_nominal',nom[key,period]);put('country_'+key+'_'+period+'_chained',real[key,period])
recs={r['period']:r for r in selected('derived-national-account-published-reconciliations.csv')}
for period in periods:
 r=recs[period];n=sum(nom[k,period]for k in ['consumption','investment','government','exports'])-nom['imports',period];z=sum(real[k,period]for k in ['consumption','investment','government','exports'])-real['imports',period]
 vals={'sum_current_C_I_G_X_minus_M':n,'published_current_rounding_gap':nom['gdp',period]-n,'GDP_minus_GDI_published_gap':nom['gdp',period]-nom['gdi',period],'sum_chained_major_components':z,'chained_nonadditivity_gap':real['gdp',period]-z}
 for key,v in vals.items():assert F(r[key])==v;checks+=1;put('country_'+period+'_'+key,v)
 gap=nom['gdp',period]+nom['income_receipts_rest_world',period]-nom['income_payments_rest_world',period]-nom['gnp',period]
 assert abs(gap)<=F(1,5);checks+=1;put('country_'+period+'_GNP_published_rounding_gap',gap)
ratio=real['gdp','2024Q4']/real['gdp','2024Q3'];growth=[F('2.8'),F('2.4'),100*(ratio-1),100*(ratio**4-1),100*(real['gdp','2024Q4']/real['gdp','2023Q4']-1)]
for i,(r,v)in enumerate(zip(selected('actual-and-derived-GDP-growth-period-distinctions.csv'),growth)):assert F(r['rate_percent'])==v;checks+=1;put('country_growth_'+str(i)+'_percent',v)

fields=['SERIALNO','SPORDER','STATE','AGEP','ADJINC','PWGTP','PINCP','WAGP'];sel=selected('actual9876-ACS2024-Delaware-person-income-fields-missing-preserved.csv');original=A/'Census-ACS2024-1year-Delaware-person.zip'
if original.exists():
 mark(original,'retained original ACS ZIP, complete person CSV newly parsed')
 with zipfile.ZipFile(original)as z:records=list(csv.DictReader(io.StringIO(z.read('psam_p10.csv').decode('utf-8-sig'))))
 assert len(records[0])==286
 for i,(r,s)in enumerate(zip(records,sel),1):
  assert s['source_row_id']==str(i);checks+=1
  for k in fields:assert s[k]==r[k];checks+=1;originalCells+=1
else:records=sel;audit['ACSFallback']='Public eight-field selected source records, all9876 rows and missing values preserved.'
assert len(records)==len(sel)==9876
valid=lambda r:r['PINCP']!=''
eligible=[r for r in records if int(r['AGEP'])>=18 and valid(r)]
value=lambda r:F(r['PINCP'])*F(r['ADJINC'])/10**6
sumw=sum(int(r['PWGTP'])for r in eligible);num=sum((int(r['PWGTP'])*value(r)for r in eligible),F());weighted=num/sumw;simple=sum(map(value,eligible),F())/len(eligible)
def quantile(p):
 target=p*sumw;cumulative=0
 for r in sorted(eligible,key=value):
  cumulative+=int(r['PWGTP'])
  if cumulative>=target:return value(r)
summary={'source_rows':len(records),'source_columns':286,'source_person_weight_total':sum(int(r['PWGTP'])for r in records),'target_age_lower_bound':18,'adult_rows':sum(int(r['AGEP'])>=18 for r in records),'adult_available_income_rows':len(eligible),'adult_unavailable_income_rows':sum(int(r['AGEP'])>=18 and not valid(r)for r in records),'adult_person_weight_total':sumw,'adult_negative_income_rows':sum(value(r)<0 for r in eligible),'adult_zero_income_rows':sum(value(r)==0 for r in eligible),'weighted_income_numerator_2024_USD':num,'weighted_mean_personal_income_2024_USD':weighted,'unweighted_mean_personal_income_2024_USD':simple,'lower_weighted_median_personal_income_2024_USD':quantile(F(1,2)),'actual_ADJINC':F(records[0]['ADJINC']),'adjustment_factor_exact':F(records[0]['ADJINC'])/10**6}
target=selected('derived-ACS-adult-available-personal-income-summary.csv')[0]
for key,v in summary.items():assert F(target[key])==v;checks+=1;put('person_'+key,v)
put('person_all_age_missing_PINCP',sum(not valid(r)for r in records));put('person_unique_source_household_person_keys',len({(r['SERIALNO'],r['SPORDER'])for r in records}));put('person_first_adjusted_income',value(records[0]));put('person_first_age',records[0]['AGEP']);put('person_first_weight',records[0]['PWGTP'])
for r in selected('derived-ACS-adult-weighted-income-quantiles.csv'):
 v=quantile(F(r['percentile'])/100);assert F(r['lower_weighted_quantile_2024_USD'])==v;checks+=1;put('person_quantile_'+r['percentile'],v)
conditions=[lambda x:x<0,lambda x:x==0,lambda x:0<x<25000,lambda x:25000<=x<50000,lambda x:50000<=x<100000,lambda x:x>=100000]
for i,(r,test)in enumerate(zip(selected('derived-ACS-adult-signed-income-weighted-bins.csv'),conditions)):
 rows=[x for x in eligible if test(value(x))];n=len(rows);w=sum(int(x['PWGTP'])for x in rows)
 for key,v in [('actual_source_rows',n),('person_weight_sum',w),('adult_available_person_weight_total',sumw),('weighted_fraction',F(w,sumw))]:assert F(r[key])==v;checks+=1
 put('person_bin_'+str(i)+'_source_rows',n);put('person_bin_'+str(i)+'_weight',w);put('person_bin_'+str(i)+'_fraction',F(w,sumw))

class Rows(HTMLParser):
 def __init__(self):super().__init__();self.rows=[];self.row=None;self.cell=None
 def handle_starttag(self,t,a):
  if t=='tr':self.row=[]
  if t in ['td','th']and self.row is not None:self.cell=[]
 def handle_data(self,s):
  if self.cell is not None:self.cell.append(s)
 def handle_endtag(self,t):
  if t in ['td','th']and self.cell is not None:self.row.append(' '.join(''.join(self.cell).split()));self.cell=None
  if t=='tr'and self.row is not None:self.rows.append(self.row);self.row=None
sel=selected('actual-Costco-FY2024-and2023-quarter-versus-year-accounts.csv');original=A/'Costco-FY2024-official-operating-results.html';company={};periodsCompany=['Q4_2024_16weeks_million_USD','Q4_2023_17weeks_million_USD','FY2024_52weeks_million_USD','FY2023_53weeks_million_USD']
if original.exists():
 mark(original,'retained original issuer release HTML; table cells newly parsed');parsed=Rows();parsed.feed(original.read_text(encoding='utf8'))
 for r in sel:
  row=next(row for row in parsed.rows if row and row[0]==r['source_label']);nums=[F(s.replace(',',''))for s in row[1:]if re.fullmatch(r'[\d,]+',s)];assert len(nums)==4
  for k,v in zip(periodsCompany,nums):assert F(r[k])==v;checks+=1;originalCells+=1;company[r['category'],k]=v
else:
 audit['companyFallback']='Public factual income-statement selection; no local complete-HTML replay.'
 for r in sel:
  for k in periodsCompany:company[r['category'],k]=F(r[k])
for r in sel:
 for k in periodsCompany:put('company_'+r['category']+'_'+k,company[r['category'],k])
for k in periodsCompany:
 assert company['net_sales',k]+company['membership_fees',k]==company['total_revenue',k]
 assert company['total_revenue',k]-company['merchandise_costs',k]-company['sga',k]==company['operating_income',k];checks+=2
 put('company_'+k+'_operating_margin',company['operating_income',k]/company['total_revenue',k])
put('company_FY2024_weeks',52);put('company_FY2023_weeks',53);put('company_FY2024_weekly_revenue',company['total_revenue',periodsCompany[2]]/52);put('company_FY2023_weekly_revenue',company['total_revenue',periodsCompany[3]]/53)
chain=selected('hypothetical-three-stage-value-added-account.csv')
for i,r in enumerate(chain):
 output,intermediate=[F(r[k])for k in ['output_value','intermediate_input_value']];v=output-intermediate;assert F(r['value_added'])==v;checks+=1
 put('hypothetical_stage_'+str(i)+'_output',output);put('hypothetical_stage_'+str(i)+'_input',intermediate);put('hypothetical_stage_'+str(i)+'_VA',v)
put('hypothetical_gross_sales',sum(F(r['output_value'])for r in chain));put('hypothetical_value_added',sum(F(r['output_value'])-F(r['intermediate_input_value'])for r in chain))
(O/'econ13-results.json').write_text(json.dumps(dict(chapter='ECON-13',metrics=metrics,exactMetrics=exact,inputAudit=audit,originalSourceCellsCompared=originalCells,selectedAndDerivedComparisons=checks,limits='Fixed vintage published values, public disclosure-protected personal income and point weighting, multinational fiscal accounts; no SE/CI, current-vintage, natural-identity, causal-effect or actual firm national-value-added claim.'),ensure_ascii=False,indent=2)+'\n',encoding='utf8')
print('ECON13 Python:',len(metrics),'metrics;',checks,'checks;',originalCells,'original cells')
