"""ECON19 standalone stdlib reproduction from the four chapter input CSVs.
Exact rational values and analytic radicals are distinguished from Decimal80 display.
No JS engine or prior chapter outputs are used. Run with Python3.12+.
"""
from pathlib import Path
from fractions import Fraction as Q
from decimal import Decimal,localcontext
import csv,json,hashlib,sys,math,zipfile,io,xml.etree.ElementTree as ET
HERE=Path(__file__).resolve().parent;S=HERE/'econ19-sources'
def read(n):return list(csv.DictReader((S/n).open(encoding='utf-8-sig',newline='')))
def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest()
def dec(q):return Decimal(q.numerator)/Decimal(q.denominator)
def root(q):
 a,b=math.isqrt(q.numerator),math.isqrt(q.denominator)
 return Q(a,b) if a*a==q.numerator and b*b==q.denominator else None
def sqrtD(q):
 with localcontext() as c:c.prec=80;return +dec(q).sqrt()
def f(q):return '' if q is None else str(q)
def write(n,rows):
 with (S/n).open('w',encoding='utf-8',newline='')as file:
  out=csv.DictWriter(file,fieldnames=list(rows[0]));out.writeheader();out.writerows(rows)
def compute():
 M={};types={};expressions={};undefined={}
 def put(k,v,reason=None):
  if v is None:M[k]=None;types[k]='undefined';undefined[k]=reason;return
  if isinstance(v,Decimal):M[k]=str(v);types[k]='Decimal80 evaluation of exact radical';return
  M[k]=str(Q(v));types[k]='exact rational'
 monthly=read('actual48-US-bread-milk-monthly-price-observations.csv');annual=read('derived4-selected-year-price-means.csv');people=read('actual3613-person-raw-wage1976-original-fields.csv');retail=read('actual2-first-same-invoice-original8-fields.csv')
 assert len(monthly)==48 and len(people)==3613 and len(retail)==2
 means={}
 for good in ['bread','milk']:
  rs=[r for r in monthly if r['good']==good];assert len(rs)==24
  for year in [2023,2024]:
   ys=[r for r in rs if r['date'].startswith(str(year))];assert [r['date'] for r in ys]==[f'{year}-{m:02d}-01'for m in range(1,13)]
   mean=sum((Q(r['value_original'])for r in ys),Q())/12;means[good,year]=mean;put(f'country.{good}.{year}.mean',mean)
   ar=next(r for r in annual if r['good']==good and int(r['year'])==year);assert Q(ar['arithmetic_mean_exact'])==mean
  for r in rs:put('country.'+good+'.'+r['date'],Q(r['value_original']))
 put('country.originalMonthlyValues',len(monthly));put('country.monthsPerSelectedYear',12)
 available=[r for r in people if r['raw_wage1976_cents_original']!='.'];assert len(available)==3017
 put('person.originalRows',len(people));put('person.availableRawWages',len(available));put('person.missingRawWages',len(people)-len(available))
 wages=[]
 for i,r in enumerate(people,1):
  assert int(r['source_row'])==i
  value=None if r['raw_wage1976_cents_original']=='.' else Q(r['raw_wage1976_cents_original'])/100
  assert r['raw_wage_available']==str(value is not None);assert r['derived_wage1976_USD_exact']==f(value)
  if value is not None:wages.append(value)
 put('person.meanRawWageUSD1976',sum(wages,Q())/len(wages));put('person.minRawWageUSD1976',min(wages));put('person.maxRawWageUSD1976',max(wages));put('person.firstHourlyWageUSD1976',Q(people[0]['derived_wage1976_USD_exact']));put('person.assumedTwoHourBudget',Q(people[0]['derived_wage1976_USD_exact'])*2)
 edges=[Q(0),Q(5),Q(10),Q(15),Q(20),Q(40)];bins=[]
 for i,lo in enumerate(edges):
  hi=edges[i+1]if i+1<len(edges)else None;count=sum(w>=lo and(hi is None or w<hi)for w in wages)
  bins.append(dict(bin=i,lower_USD1976_exact=str(lo),upper_USD1976_exact=f(hi),upper_exclusive=True,available_rows=count,denominator_available=3017,denominator_original=3613));put(f'person.bin{i}.count',count)
 assert sum(r['available_rows']for r in bins)==3017
 assert retail[0]['InvoiceNo']==retail[1]['InvoiceNo']=='536365'
 prices=[Q(r['UnitPrice'])for r in retail];quantities=[Q(r['Quantity'])for r in retail];amount=sum((p*x for p,x in zip(prices,quantities)),Q())
 for i,r in enumerate(retail):
  assert int(r['source_row'])==i+1 and int(r['original_excel_row'])==i+2
  for key in ['Quantity','UnitPrice','InvoiceDate']:put(f'company.line{i+1}.{key}',Q(r[key]))
 put('company.partialTwoLineAmount',amount)
 integers=[dict(first_quantity=i,second_quantity=j,spending_exact=str(prices[0]*i+prices[1]*j),assumed_product_utility=i*j)for i in range(int(amount/prices[0])+1)for j in range(int(amount/prices[1])+1)if prices[0]*i+prices[1]*j<=amount]
 maxprod=max(r['assumed_product_utility']for r in integers);assert [(r['first_quantity'],r['second_quantity'])for r in integers if r['assumed_product_utility']==maxprod]==[(6,6)]
 put('company.integerAffordableBundles',len(integers));put('company.integerProductMaximum',maxprod)
 anchors={'country':([means[g,2023]for g in ['bread','milk']],[means[g,2024]for g in ['bread','milk']],Q(20)),'person':([Q(1),Q(1)],[Q(2),Q(1)],Q(people[0]['derived_wage1976_USD_exact'])*2),'company':(prices,[prices[0]*Q(11,10),prices[1]],amount)}
 def fit(fam,p,m):
  if fam=='product':return m*m/(4*p[0]*p[1]),[m/(2*p[0]),m/(2*p[1])],'singleton'
  if fam=='leontief':u=m/sum(p);return u,[u,u],'singleton'
  ratios=[1/p[0],1/p[1]];u=max(ratios)*m
  if ratios[0]==ratios[1]and m:return u,None,'closed-segment'
  return u,[m/p[0],Q()]if ratios[0]>ratios[1]else[Q(),m/p[1]],'singleton'
 def profile(kind,fam,p,q,m,key):
  u,x,xkind=fit(fam,p,m);v,z,zkind=fit(fam,q,m)
  put(key+'.oldUtility',u);put(key+'.newUtility',v);put(key+'.oldSetDimension',int(xkind=='closed-segment'));put(key+'.newSetDimension',int(zkind=='closed-segment'))
  for j in [0,1]:put(key+f'.oldDemand{j+1}',None if x is None else x[j],'Complete tied segment,no uniquely identified coordinate'if x is None else None);put(key+f'.newDemand{j+1}',None if z is None else z[j],'Complete tied segment,no uniquely identified coordinate'if z is None else None)
  if fam=='product':
   ratio=q[0]*q[1]/(p[0]*p[1]);r=root(ratio)
   if r is not None:cv=m*(r-1);ev=m*(1-1/r)
   else:
    with localcontext()as c:c.prec=80;rr=dec(ratio).sqrt();cv=dec(m)*(rr-1);ev=dec(m)*(1-1/rr)
   cve=f'{m}*(sqrt({ratio})-1)';eve=f'{m}*(1-1/sqrt({ratio}))'
  else:
   oldcost=u*(min(q)if fam=='linear'else sum(q));newcost=v*(min(p)if fam=='linear'else sum(p));cv=oldcost-m;ev=m-newcost;cve=str(cv);eve=str(ev)
  put(key+'.CV',cv);put(key+'.EV',ev);expressions[key+'.CV']=cve;expressions[key+'.EV']=eve
  return dict(kind=kind,family=fam,old_price1_exact=str(p[0]),old_price2_exact=str(p[1]),new_price1_exact=str(q[0]),new_price2_exact=str(q[1]),assumed_budget_exact=str(m),old_utility_exact=str(u),new_utility_exact=str(v),old_set_kind=xkind,new_set_kind=zkind,old_x1_exact=f(None if x is None else x[0]),old_x2_exact=f(None if x is None else x[1]),new_x1_exact=f(None if z is None else z[0]),new_x2_exact=f(None if z is None else z[1]),CV_expression=cve,EV_expression=eve,CV_value=f(cv),EV_value=f(ev),value_status='exact-rational'if isinstance(cv,Q)else'Decimal80-radical-display',scope='Explicitly assumed preferences/budget;no actual welfare identification')
 profiles=[];sensitivity=[]
 for kind,(p,q,m)in anchors.items():
  for fam in ['product','linear','leontief']:profiles.append(profile(kind,fam,p,q,m,'conditional.'+kind+'.'+fam))
  for scale in [Q(1,2),Q(3,4),Q(1),Q(5,4),Q(3,2)]:
   r=profile(kind,'product',p,[p[0]*scale,p[1]],m,'sensitivity.'+kind+'.'+str(scale));r['assumed_first_price_multiplier']=str(scale);sensitivity.append(r)
 outputs={'assumed9-preference-and-duality-profiles.csv':profiles,'derived6-raw-wage-bins.csv':bins,'assumed86-affordable-integer-retail-bundles.csv':integers,'assumed15-first-price-sensitivity-profiles.csv':sensitivity}
 return dict(scope='Standalone stdlib author reproduction;exact rational versus Decimal80 radical display distinguished',metrics=M,metricTypes=types,exactExpressions=expressions,undefinedReasons=undefined,inputHashes={n:sha(S/n)for n in ['actual48-US-bread-milk-monthly-price-observations.csv','derived4-selected-year-price-means.csv','actual3613-person-raw-wage1976-original-fields.csv','actual2-first-same-invoice-original8-fields.csv']}),outputs

def original_audit():
 # Optional original Card archive validation in the full workspace. Public-only
 # reproducibility does not claim that archive or original FRED HTTP bytes exist.
 raw=HERE.parents[1]/'work/textbooks-2026/raw/proximity.zip'
 if not raw.exists():return 'Public selected CSV mode;original archive not present'
 z=zipfile.ZipFile(raw);ls=z.read('nls.dat').decode('ascii').splitlines();people=read('actual3613-person-raw-wage1976-original-fields.csv')
 assert len(ls)==len(people)==3613
 for i,(line,r)in enumerate(zip(ls,people),1):assert r['source_row']==str(i) and r['source_person_code']==line[:5].strip() and r['raw_wage1976_cents_original']==line[127:132].strip()
 return 'Original Card3613x3 fields independently reselected;FRED rendered snapshots and retailXML are separately audited in author source gate'
if __name__=='__main__':
 result,derived=compute()
 if '--write-derived'in sys.argv:
  for n,rs in derived.items():write(n,rs)
 else:
  for n,expected in derived.items():
   actual=read(n);assert actual==[{k:str(v)for k,v in r.items()}for r in expected],n
 (HERE/'econ19-results.json').write_text(json.dumps(result,ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
 print(json.dumps(dict(metrics=len(result['metrics']),undefined=len(result['undefinedReasons']),originalMode=original_audit(),derivedRows={k:len(v)for k,v in derived.items()})))
