"""METR02 independent source replay: Fraction arithmetic, with explicit public-selection fallback."""
from pathlib import Path
from fractions import Fraction as Q
from decimal import Decimal
from collections import defaultdict
import csv,hashlib,json,os,sys,zipfile
O=Path(__file__).resolve().parent;R=O.parent.parent;D=O/'metr02-sources';RAW=R/'work/textbooks-2026/raw';metrics={};exact={};audit=[];checks=0;originalCells=0
publicOnly=os.environ.get('TEXTBOOK_PUBLIC_ONLY')=='1'or'--public-only'in sys.argv
sha=lambda p:hashlib.sha256(p.read_bytes()).hexdigest()
def read(n):
 p=D/n;audit.append(dict(file=str(p.relative_to(O)),sha256=sha(p),role='public selection or calculated table checked, not a numeric oracle for original inputs'));return list(csv.DictReader(p.open(encoding='utf-8-sig',newline='')))
def ck(a,b):
 global checks
 checks+=1;assert a==b,(a,b)
def put(k,v):v=Q(v);metrics[k]=float(v);exact[k]=str(v)
def nullable(s):return None if s is None or s.strip()in['','.']else Q(s)
names={'country':'actual16-country-2024-longevity-GDP-pairs.csv','person':'actual3613-person-schooling-source-trimmed-log-wage-pairs.csv','company':'actual410-establishment-before-after-FTE-pairs.csv'};selected={k:read(n)for k,n in names.items()};source={}
for kind,name in [('country','worldbank-panel.json'),('person','proximity.zip'),('company','njmin.zip')]:
 p=RAW/name
 if not publicOnly and p.exists():
  audit.append(dict(file=str(p.relative_to(R)),sha256=sha(p),mode='original retained bytes reread',originalDownloadedOn='2026-10-20',reviewedOn='2026-10-27'))
  if kind=='country':
   raw=json.loads(p.read_text(encoding='utf8'),parse_float=Decimal)[1];lookup={(r['countryiso3code'],r['date'],r['indicator']['id']):(i,r)for i,r in enumerate(raw,1)};rows=[]
   for i,r in enumerate(raw,1):
    if r['date']=='2024'and r['indicator']['id']=='NY.GDP.PCAP.KD':
     j,life=lookup[(r['countryiso3code'],'2024','SP.DYN.LE00.IN')];x,y=Q(life['value']),Q(r['value']);rows.append(dict(sourceRow=i,xSourceRow=j,code=r['countryiso3code'],group='life_ge_80'if x>=80 else'life_lt_80',x=x,y=y,weight=Q(1)));originalCells+=8
   rows.sort(key=lambda r:r['code'])
  elif kind=='person':
   with zipfile.ZipFile(p)as z:lines=z.read('nls.dat').decode('ascii').splitlines()
   rows=[]
   for i,s in enumerate(lines,1):
    x=nullable(s[17:19]);rows.append(dict(sourceRow=i,code=str(int(Q(s[0:5]))),group='schooling_le12'if x<=12 else'schooling_gt12',x=x,y=nullable(s[85:97]),weight=Q(1)));originalCells+=3
  else:
   with zipfile.ZipFile(p)as z:lines=z.read('public.dat').decode('ascii').splitlines()
   rows=[]
   for i,s in enumerate(lines,1):
    b=[nullable(s[a-1:b])for a,b in [(26,30),(32,36),(38,42)]];a=[nullable(s[a-1:b])for a,b in [(122,126),(128,132),(134,138)]];fte=lambda t:None if None in t else t[0]+t[1]/2+t[2]
    rows.append(dict(sourceRow=i,code=str(int(Q(s[0:3]))),group='NJ'if Q(s[8:9])==1 else'PA',x=fte(b),y=fte(a),weight=Q(1)));originalCells+=8
 else:
  rows=[{k:int(v)if k in['sourceRow','xSourceRow']else nullable(v)if k in['x','y','weight']else v for k,v in r.items()}for r in selected[kind]];audit.append(dict(kind=kind,mode='public whole selected records; no original available or public-only requested',newCollection=False))
 source[kind]=rows;ck(len(rows),len(selected[kind]))
 for r,s in zip(rows,selected[kind]):
  for k,v in r.items():ck(v,int(s[k])if k in['sourceRow','xSourceRow']else nullable(s[k])if k in['x','y','weight']else s[k])
S=read('actual-projection-summaries-exact.csv');FIT=read('actual-all-source-rows-predictions-and-residuals.csv');GROUP=read('actual-same-X-finite-law-group-summaries.csv')
def calculate(rows):
 p=[(r,r['x'],r['y'])for r in rows if r['x']is not None and r['y']is not None];n=len(p);mx=sum(x for r,x,y in p)/n;my=sum(y for r,x,y in p)/n;xx=sum((x-mx)**2 for r,x,y in p);xy=sum((x-mx)*(y-my)for r,x,y in p);yy=sum((y-my)**2 for r,x,y in p);b=xy/xx;a=my-b*mx;e=[y-a-b*x for r,x,y in p];sse=sum(v*v for v in e);g=defaultdict(list)
 for r,x,y in p:g[x].append(y)
 within=sum(sum((y-sum(ys)/len(ys))**2 for y in ys)for ys in g.values());approx=sum(len(ys)*(sum(ys)/len(ys)-a-b*x)**2 for x,ys in g.items());ck(sse,within+approx);ck(sum(e),0);ck(sum(x*v for (r,x,y),v in zip(p,e)),0)
 return dict(n=n,meanX=mx,meanY=my,Sxx=xx,Sxy=xy,SST=yy,intercept=a,slope=b,SSE=sse,MSE=sse/n,R2=1-sse/yy,withinMSE=within/n,approximationMSE=approx/n),p,g
for kind,rows in source.items():
 z,p,g=calculate(rows);s=next(r for r in S if r['case']==kind)
 for key,v in z.items():
  put(kind+'_'+key,v)
  if key in s:ck(Q(s[key]),v)
 for key,v in [('source_records',len(rows)),('complete_pairs',len(p)),('unavailable_pairs',len(rows)-len(p))]:ck(int(s[key]),v);put(kind+'_'+key,v)
 fs=[r for r in FIT if r['case']==kind];ck(len(fs),len(rows))
 for row,fr in zip(rows,fs):
  ck(row['sourceRow'],int(fr['source_row']));ck(row['code'],fr['original_code']);ck(row['group'],fr['group']);ck(row['x'],nullable(fr['x_exact']));ck(row['y'],nullable(fr['y_exact']));complete=row['x']is not None and row['y']is not None;ck(fr['complete_pair'],str(complete));f=z['intercept']+z['slope']*row['x']if complete else None;ck(nullable(fr['prediction_exact']),f);ck(nullable(fr['residual_exact']),None if f is None else row['y']-f)
 gs=[r for r in GROUP if r['case']==kind];ck(len(gs),len(g))
 for row,(x,ys)in zip(gs,sorted(g.items())):
  mu=sum(ys)/len(ys);v=sum((y-mu)**2 for y in ys)/len(ys)
  for key,vv in dict(x_exact=x,rows=len(ys),mass_exact=Q(len(ys),len(p)),conditional_mean_exact=mu,conditional_variance_exact=v,line_prediction_exact=z['intercept']+z['slope']*x,group_mean_residual_exact=mu-z['intercept']-z['slope']*x).items():ck(Q(row[key]),vv)
 ck(z['withinMSE']+z['approximationMSE'],z['MSE'])
ck([r['sourceRow']for r in source['company']if r['code']=='407'],[42,168])
T=read('assumed-six-row-practice-change-law.csv');toy=[dict(x=Q(x),y=Q(y),weight=Q(1))for x,y in [(0,-1),(0,1),(1,0),(1,2),(2,3),(2,5)]]
for r,s in zip(toy,T):
 for k in ['x','y','weight']:ck(r[k],Q(s[k]))
z,p,g=calculate(toy)
for k,v in z.items():put('assumed_'+k,v)
candidate=sum((r['y']-r['x'])**2 for r in toy)/len(toy);mappedB=5*z['slope']/2;mappedA=3+5*z['intercept']-mappedB*10;sy=[Q(3),Q(5)];sm=sum(sy)/2
for key,v in dict(candidateMSE=candidate,minimumMSE=z['MSE'],objectiveGap=candidate-z['MSE'],conditionalRisk=z['withinMSE'],approximationRisk=z['approximationMSE'],unitMappedIntercept=mappedA,unitMappedSlope=mappedB,unitMappedMSE=25*z['MSE'],singularMinimumMSE=sum((y-sm)**2 for y in sy)/2,singularQueryAtSupport=sm,originAllZeroMSE=sum(y*y for y in sy)/2,continuousSquareProjectionMSE=Q(1,5)-Q(1,2)+Q(4,9)-Q(1,6)+Q(1,36)).items():put('assumed_'+key,v)
ck(z['intercept'],Q(-1,3));ck(z['slope'],2);ck(z['MSE'],Q(11,9));ck(z['withinMSE'],1);ck(z['approximationMSE'],Q(2,9));ck(z['R2'],Q(24,35))
for i,x in enumerate([Q(0),Q(1),Q(2)]):put('assumed_group'+str(i)+'_mean',sum(g[x])/len(g[x]));put('assumed_group'+str(i)+'_meanResidual',sum(g[x])/len(g[x])-z['intercept']-z['slope']*x)
result=dict(chapter='METR-02',metrics=metrics,exactMetrics=exact,inputAudit=audit,originalSourceFieldsCompared=originalCells,selectedAndDerivedComparisons=checks,scope='Original finite pair arithmetic and separate assumed teaching laws; no cases/model/engine outputs read as numeric input, no actual iid or causal certification.')
p=O/'metr02-results.json';p.write_text(json.dumps(result,ensure_ascii=False,indent=2)+'\n',encoding='utf8');print('METR02 Python',len(metrics),'metrics;',originalCells,'original fields;',checks,'comparisons; public-only',publicOnly)
