"""Reproduce ECON07 from actual public input rows and explicit assumptions.

Python stdlib/Fraction; no case/model JSON or previous result is a numeric input.
When local originals exist, independently read HMRC's actual HTML table, the
enacted section and original XLSX first row, then compare retained selections.
R separately computes from the public actual-rate/line CSV, not this output.
UCI line attribution: Chen (2015), DOI10.24432/C5BW33, CC BY4.0.
"""
from pathlib import Path
from fractions import Fraction as F
from datetime import datetime
import csv,json,hashlib,re,html,zipfile,io,xml.etree.ElementTree as ET
B=Path(__file__).resolve().parent;D=B/'econ07-sources';W=B.parent.parent/'work/textbook-rewrite-2026'
def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest()
def load(n):return list(csv.DictReader((D/n).open(encoding='utf-8-sig',newline='')))
hist=load('actual-HMRC-historical-standard-rates.csv');a=load('actual-source-first-retail-line-preserved.csv')[0];sourceChecks=0;calculationInputs=['actual-HMRC-historical-standard-rates.csv','actual-source-first-retail-line-preserved.csv'];audit={'caseOrModelJSONUsedAsNumericInput':False,'calculationInputs':[dict(file='econ07-sources/'+n,sha256=sha(D/n)) for n in calculationInputs],'originalChecks':[]}
hm=W/'source-audit-econ07/HMRC-VAT-Notice700-historic-rates.html'
if hm.is_file():
 raw=hm.read_text(encoding='utf8');raw=re.sub(r'<(script|style)\b[^>]*>.*?</\1>','',raw,flags=re.S|re.I);tables=re.findall(r'<table\b[^>]*>.*?</table>',raw,re.S|re.I);selected=[]
 for t in tables:
  rs=[]
  for tr in re.findall(r'<tr\b[^>]*>.*?</tr>',t,re.S|re.I):rs.append([' '.join(html.unescape(re.sub('<[^>]+>','',td)).split()) for td in re.findall(r'<t[dh]\b[^>]*>(.*?)</t[dh]>',tr,re.S|re.I)])
  if len(rs)==8 and rs[1]==['1 April 1973','10%']:selected.append(rs)
 assert len(selected)==1
 for r,(dt,amt) in zip(hist,selected[0][1:]):
  day=datetime.strptime(dt,'%d %B %Y').strftime('%Y-%m-%d');rate=F(re.match('[0-9.]+',amt)[0])/100;assert r['effective_from']==day and F(r['statutory_standard_rate_exact'])==rate and r['source_rate_text']==amt;sourceChecks+=3
 audit['originalChecks'].append(dict(file=str(hm),sha256=sha(hm),independentMethod='Remove script/style; regex table cells; compare seven dated standard rates.'))
law=W/'source-audit-econ07/Finance-No2-Act2010-section3-2010-07-27.html'
if law.is_file():
 txt=' '.join(html.unescape(re.sub('<[^>]+>',' ',law.read_text(encoding='utf8'))).split());assert '17.5 per cent' in txt and '20 per cent' in txt and '4 January 2011' in txt;sourceChecks+=3;audit['originalChecks'].append(dict(file=str(law),sha256=sha(law),independentMethod='Read enacted rate substitution and effective-date text, not a transaction tax-point ruling.'))
zpath=W/'source-audit-econ06/uci-online-retail352.zip'
if zpath.is_file():
 ns='{http://schemas.openxmlformats.org/spreadsheetml/2006/main}';book=zipfile.ZipFile(io.BytesIO(zipfile.ZipFile(zpath).read('Online Retail.xlsx')));ss=[''.join(x.itertext()) for x in ET.fromstring(book.read('xl/sharedStrings.xml')).findall(ns+'si')];headers=None
 with book.open('xl/worksheets/sheet1.xml') as s:
  for _,row in ET.iterparse(s,events=('end',)):
   if row.tag!=ns+'row':continue
   cells={}
   for c in row.findall(ns+'c'):
    v=c.find(ns+'v');v=v.text if v is not None else '';cells[re.sub('[0-9]','',c.get('r'))]=ss[int(v)] if c.get('t')=='s' else v
   values=[cells.get(chr(65+i),'') for i in range(8)]
   if headers is None:headers=values;continue
   assert int(row.get('r'))-1==int(a['source_row_id'])
   for h,v in zip(headers,values):assert a[h]==v,(h,a[h],v);sourceChecks+=1
   break
 audit['originalChecks'].append(dict(file=str(zpath),sha256=sha(zpath),independentMethod='Read original worksheet header and first original invoice line; eight fields compared.'))
audit['originalSourceCellComparisons']=sourceChecks;audit['rawPriceVsClassroomRoundingDifferenceExact']=str(F(51,20)-F(a['UnitPrice']));audit['actualTransactionVATStatusIdentified']=False
M={};X={}
def metric(k,v):v=F(v);M[k]=float(v);X[k]=str(v)
r0,r1=F(hist[-2]['statutory_standard_rate_exact']),F(hist[-1]['statutory_standard_rate_exact']);assert r0==F(7,40) and r1==F(1,5);p,q=F(51,20),F(a['Quantity']);ps0=p/(1+r0)
metric('historical_rate_rows',len(hist));metric('source_quantity',q);metric('source_recorded_price_GBP',a['UnitPrice']);metric('source_recorded_amount_GBP',F(a['UnitPrice'])*q)
for i,r in enumerate(hist,1):metric(f'history_{i}_rate',r['statutory_standard_rate_exact']);metric(f'history_{i}_percent',100*F(r['statutory_standard_rate_exact']))
for k,v in [('rate_change_percentage_points',100*(r1-r0)),('relative_statutory_rate_change',(r1-r0)/r0),('assumed_fixed_net_gross_growth',(1+r1)/(1+r0)-1)]:metric(k,v)
for i,r in enumerate([r0,r1],1):
 for k,v in [('gross',100*(1+r)),('tax',100*r),('tax_share_of_gross',r/(1+r))]:metric(f'fixed_net_{i}_{k}',v)
ac=[]
for i,r in enumerate([r0,r1],1):
 for j,inclusive in enumerate([True,False],1):
  net=p/(1+r) if inclusive else p;gross=p if inclusive else p*(1+r);tax=gross-net;values=dict(net_per_unit_GBP_exact=net,tax_per_unit_GBP_exact=tax,gross_per_unit_GBP_exact=gross,total_net_GBP_exact=q*net,total_tax_GBP_exact=q*tax,total_gross_GBP_exact=q*gross);ac.append(values)
  for k,v in values.items():metric(f'account_{i}_{j}_{k.removesuffix("_exact")}',v)
for r,expected in zip(load('hypothetical-inclusive-exclusive-accounting.csv'),ac):
 for k,v in expected.items():assert F(r[k])==v;sourceChecks+=1
# Declared classroom assumptions, independent of saved hypothetical coefficients.
slopes=[('A',F(1,10),F(1,20)),('B',F(1,2),F(1,5))];rates=sorted(set([F(i,100) for i in range(41)]+[r0]));rows=[];allStates={}
def eq(alpha,beta,gamma,delta,r):
 # Solve the two-price wedge equation via seller-price inversion.
 quantity=(alpha/(1+r)-gamma)/(delta+beta/(1+r));seller=gamma+delta*quantity;buyer=alpha-beta*quantity;wedge=buyer-seller;cs=beta*quantity**2/2;ps=delta*quantity**2/2;revenue=wedge*quantity;qe=(alpha-gamma)/(beta+delta);total=(alpha-gamma)*quantity-(beta+delta)*quantity**2/2;best=(alpha-gamma)**2/(2*(beta+delta));dwl=best-total
 assert cs+ps+revenue==total and dwl==(beta+delta)*(qe-quantity)**2/2 and buyer==(1+r)*seller
 return dict(assumed_quantity_exact=quantity,buyer_price_GBP_per_unit_exact=buyer,seller_price_GBP_per_unit_exact=seller,per_unit_wedge_GBP_exact=wedge,consumer_surplus_GBP_exact=cs,producer_surplus_GBP_exact=ps,tax_revenue_GBP_exact=revenue,total_surplus_GBP_exact=total,efficient_quantity_exact=qe,efficient_total_surplus_GBP_exact=best,deadweight_loss_GBP_exact=dwl)
for name,beta,delta in slopes:
 alpha=p+beta*q;gamma=ps0-delta*q
 for k,v in [('alpha',alpha),('beta',beta),('gamma',gamma),('delta',delta)]:metric(f'model_{name}_{k}',v)
 for i,r in enumerate(rates):
  v=eq(alpha,beta,gamma,delta,r);allStates[name,r]=v;rows.append(v)
  for k,x in v.items():metric(f'model_{name}_rate_{i:02d}_{k.removesuffix("_exact")}',x)
 old,new=allStates[name,r0],allStates[name,r1];dpc=new['buyer_price_GBP_per_unit_exact']-old['buyer_price_GBP_per_unit_exact'];dps=new['seller_price_GBP_per_unit_exact']-old['seller_price_GBP_per_unit_exact'];dt=dpc-dps
 vals=dict(quantity_change_exact=new['assumed_quantity_exact']-old['assumed_quantity_exact'],buyer_price_change_GBP_exact=dpc,seller_price_change_GBP_exact=dps,per_unit_wedge_change_GBP_exact=dt,buyer_share_of_extra_unit_wedge_exact=dpc/dt,seller_share_of_extra_unit_wedge_exact=-dps/dt,consumer_surplus_change_GBP_exact=new['consumer_surplus_GBP_exact']-old['consumer_surplus_GBP_exact'],producer_surplus_change_GBP_exact=new['producer_surplus_GBP_exact']-old['producer_surplus_GBP_exact'],tax_revenue_change_GBP_exact=new['tax_revenue_GBP_exact']-old['tax_revenue_GBP_exact'],deadweight_loss_change_GBP_exact=new['deadweight_loss_GBP_exact']-old['deadweight_loss_GBP_exact'])
 assert vals['buyer_share_of_extra_unit_wedge_exact']+vals['seller_share_of_extra_unit_wedge_exact']==1
 for k,v in vals.items():metric(f'incidence_{name}_{k.removesuffix("_exact")}',v)
 saved=next(x for x in load('hypothetical-old-new-unit-incidence-comparison.csv') if x['model_id']==name)
 for k,v in vals.items():assert F(saved[k])==v;sourceChecks+=1
for r,expected in zip(load('hypothetical-ad-valorem-equilibrium-and-welfare-profiles.csv'),rows):
 for k,v in expected.items():assert F(r[k])==v;sourceChecks+=1
for r in load('hypothetical-old-new-welfare-states.csv'):
 expected=allStates[r['model_id'],F(r['ad_valorem_rate_exact'])]
 for k,v in expected.items():assert F(r[k])==v;sourceChecks+=1
rf=B/'econ07-r-results.csv';cross=tiny=0
if rf.is_file():
 rr=list(csv.DictReader(rf.open(encoding='utf-8-sig')));assert len(rr)==len(M)
 for r in rr:
  k=r['metric'];v=float(r['value']);want=M[k];assert abs(v-want)<=1e-9*max(1,abs(want)),(k,v,want)
  if want and abs(want)<1e-9:assert abs(v/want-1)<=1e-8,(k,v,want);tiny+=1
  cross+=1
audit['independentDerivedCSVCellComparisons']=sourceChecks-audit['originalSourceCellComparisons'];audit['RUsesPublicSelectedRowsNotOriginalWorkbook']=True
result=dict(metrics=M,exactMetrics=X,inputAudit=audit,crossLanguageComparisons=cross,tinyNonzeroRelativeComparisons=tiny,scope='Actual historical facts and stored-line arithmetic; separate assumed tax accounting and quasilinear competitive model. No identified VAT liability, incidence or optimal policy.')
(B/'econ07-results.json').write_text(json.dumps(result,ensure_ascii=False,indent=2,allow_nan=False)+'\n',encoding='utf8');print(json.dumps(dict(metrics=len(M),crossLanguageComparisons=cross,originalSourceCellComparisons=audit['originalSourceCellComparisons'],derivedCSVCells=audit['independentDerivedCSVCellComparisons'])))
