#!/usr/bin/env python3
"""AI21 native-only source reconstruction. Python standard library only.
Usage: python actual-source-study.py [native_source_directory] [output_directory]
Input: three retained original CSVs only; no models/engine/answers imported.
Actual observations differ from declared fixed scores, costs and thresholds.
Card1995/Hansen NLS historical male cohort; UCI IranianChurn2020,
DOI10.24432/C5JW3Z CC BY4.0; retained WorldBank WDI factual inputs.
"""
from pathlib import Path
from fractions import Fraction as F
from fractions import Fraction as Q
from itertools import product
import csv,json,hashlib,collections,sys
here=Path(__file__).resolve().parent
S=Path(sys.argv[1])if len(sys.argv)>1 else here.parent/'ai21-sources'
out=Path(sys.argv[2])if len(sys.argv)>2 else here/'reproduced-python'
out.mkdir(parents=True,exist_ok=True)
q=lambda x:str(x.numerator)if x.denominator==1 else f'{x.numerator}/{x.denominator}'
def read(n):return list(csv.DictReader((S/n).open(encoding='utf8',newline='')))
SHA={'actual360-four-country-growth-CPI-1980-2024.csv': '523e0d7eb4ddabe95be0e54fd466ca8a571ad285b094e115521ac9b9d148934f', 'actual3613-NLS-original52-fields.csv': '00a4db8e972751609914fe3f091c317c20b4f3d70890cbdfd085824611516d9d', 'actual3150-churn-original14-fields.csv': 'f0b8583e410c87c9b90f27d833b913338999e1e3740cb7cc6150bda701f08dfd'}
for name,h in SHA.items():assert hashlib.sha256((S/name).read_bytes()).hexdigest()==h,name
def f(x):return x if isinstance(x,Q)else Q(str(x))

def ratio(a,b):return a/b if b else None

def gap(v):return max(v)-min(v)if v and all(x is not None for x in v)else None

def rows(raw):return[{**r,'score':f(r['score']),'weight':f(r.get('weight',1)),'role':r.get('role','unspecified')}for r in raw]

def audit(raw,threshold='1/2',groupThresholds=None):
 rs=rows(raw);groups=list(dict.fromkeys(r['group']for r in rs));gs=[];pr=[]
 for g in groups:
  block=[r for r in rs if r['group']==g];th=f((groupThresholds or{}).get(g,threshold));cells={(y,d):sum((r['weight']for r in block if r['target']==y and int(r['score']>=th)==d),Q())for y,d in product([0,1],repeat=2)};tn,fp,fn,tp=cells[0,0],cells[0,1],cells[1,0],cells[1,1];mass=tn+fp+fn+tp;positive=tp+fn;negative=tn+fp;selected=tp+fp
  gs.append(dict(group=g,records=len(block),zeroWeightRecords=sum(r['weight']==0 for r in block),mass=mass,threshold=th,positiveMass=positive,negativeMass=negative,selectedMass=selected,truePositive=tp,falsePositive=fp,trueNegative=tn,falseNegative=fn,baseRate=ratio(positive,mass),selectionRate=ratio(selected,mass),truePositiveRate=ratio(tp,positive),falsePositiveRate=ratio(fp,negative),falseNegativeRate=ratio(fn,positive),positivePredictiveValue=ratio(tp,selected),negativePredictiveValue=ratio(tn,tn+fn),accuracy=ratio(tp+tn,mass),meanBrier=ratio(sum((r['weight']*(r['score']-r['target'])**2 for r in block),Q()),mass)))
  pr +=[{**r,'threshold':th,'prediction':int(r['score']>=th)}for r in block]
 g=lambda k:gap([r[k]for r in gs]);tpr=g('truePositiveRate');fpr=g('falsePositiveRate');rates=[r['selectionRate']for r in gs];mass=sum((r['mass']for r in gs),Q())
 return dict(records=len(rs),groups=gs,predictions=pr,totalMass=mass,accuracy=ratio(sum((r['truePositive']+r['trueNegative']for r in gs),Q()),mass),selectionRateGap=g('selectionRate'),truePositiveRateGap=tpr,falsePositiveRateGap=fpr,equalizedOddsGap=max(tpr,fpr)if tpr is not None and fpr is not None else None,positivePredictiveValueGap=g('positivePredictiveValue'),minSelectionToMaxRatio=ratio(min(rates),max(rates))if rates and all(x is not None for x in rates)else None,allGroupDenominatorsDefined={n:bool(gs)and all(r[k]is not None for r in gs)for n,k in [('selection','selectionRate'),('TPR','truePositiveRate'),('FPR','falsePositiveRate'),('PPV','positivePredictiveValue')]})

def decision(a):
 costFP=f(a.get('costFalsePositive',1));costFN=f(a.get('costFalseNegative',1));results=[];selected=None
 for c in a['candidates']:
  z=audit(a['rows'],c.get('threshold','1/2'),c.get('groupThresholds'));loss=ratio(sum((costFP*r['falsePositive']+costFN*r['falseNegative']for r in z['groups']),Q()),z['totalMass']);constraints=[]
  for k in ['selectionRateGap','equalizedOddsGap']:
   if k+'Limit'in a:constraints.append(dict(criterion=k,value=z[k],limit=f(a[k+'Limit']),satisfied=z[k]is not None and z[k]<=f(a[k+'Limit'])))
  r=dict(id=c['id'],threshold=f(c.get('threshold','1/2')),groupThresholds={k:f(v)for k,v in c.get('groupThresholds',{}).items()},meanValidationCost=loss,validationMass=z['totalMass'],selectionRateGap=z['selectionRateGap'],equalizedOddsGap=z['equalizedOddsGap'],constraints=constraints,feasible=loss is not None and all(c['satisfied']for c in constraints),groups=z['groups']);results.append(r)
  if r['feasible']and(selected is None or loss<selected['meanValidationCost']):selected=r
 return dict(candidatePolicies=results,selectedPolicy=selected,validationRows=len(a['rows']),costFalsePositive=costFP,costFalseNegative=costFN,selectionRateGapLimit=f(a['selectionRateGapLimit'])if'selectionRateGapLimit'in a else None,equalizedOddsGapLimit=f(a['equalizedOddsGapLimit'])if'equalizedOddsGapLimit'in a else None,noFeasiblePolicy=selected is None)

models={k:dict(records=[],scope={},featureNames=[])for k in ['country','person','company']};lineage=[];eligibility=[]
country='actual360-four-country-growth-CPI-1980-2024.csv';raw=read(country);lookup={(r['countryISO3'],int(r['year']),r['indicatorID']):(i+1,r)for i,r in enumerate(raw)}
for iso in sorted({r['countryISO3']for r in raw}):
 for year in range(1981,2025):
  row,r=lookup[iso,year,'NY.GDP.MKTP.KD.ZG'];lr,gdp=lookup[iso,year-1,'NY.GDP.MKTP.KD.ZG'];cr,cpi=lookup[iso,year-1,'FP.CPI.TOTL.ZG'];x=[(F(gdp['valueToken'])+30)/60,(F(cpi['valueToken'])+100)/300];assert all(0<=v<=1 for v in x);role='train'if year<=2005 else'validation'if year<=2014 else'test';score=x[0]
  rec=dict(id=iso+':'+str(year),role=role,group=iso,sourceFile=country,namedCSVDataRow=row,upstreamRowToken=r['originalSourceRow'],nativeFields=r,input=list(map(q,x)),score=q(score),target=int(F(r['valueToken'])>=0),sourceReferences=[dict(file=country,namedCSVDataRow=lr,indicator=gdp['indicatorID'],valueToken=gdp['valueToken'],upstreamRowToken=gdp['originalSourceRow']),dict(file=country,namedCSVDataRow=cr,indicator=cpi['indicatorID'],valueToken=cpi['valueToken'],upstreamRowToken=cpi['originalSourceRow'])]);models['country']['records'].append(rec)
models['country'].update(featureNames=['(previousGDPgrowth+30)/60','(previousCPIinflation+100)/300'],weights=['1','0'],bias='0',interaction='0')
models['country']['scope']=dict(nativeRows=360,coreRows=176,groups='Original ISO3 country codes DEU/JPN/KOR/USA; geographic technical comparison, not an automatically protected-demographic criterion.',score='Fixed score(previousGDPgrowth+30)/60, not an estimated probability. Previous CPI is retained as a zero-direct-weight feature for attribution/proxy discussion; not used to fit predictions.',target='Observed current GDPgrowth>=0, not public welfare or policy entitlement.',time='Same final retained WDIvintage2026-10-08; no announcement/revision vintage reconstruction. Repeated countries and common shocks are dependent.',roles='1981–2005 train100;2006–2014 validation36;2015–2024 test40. Score fixed; train only provides reference means. Threshold selected on validation only.',causal='No effect of changing inflation, growth or national policy identified from these observational records.')
def choose(rows,n):return[rows[j*(len(rows)-1)//(min(n,len(rows))-1)]for j in range(min(n,len(rows)))]if len(rows)>1 else rows[:]
def role(j):return'train'if j%10<6 else'validation'if j%10<8 else'test'
person='actual3613-NLS-original52-fields.csv';raw=read(person);groups=collections.defaultdict(list);missing=collections.Counter();eligibleN=0
for row,r in enumerate(raw,1):
 reason='eligible'if all(r[k]not in ['.','NA','']for k in ['wage76','ed76','age76','black'])else'missing-relevant-observed-field'
 if reason=='eligible':assert F(r['wage76'])>0 and r['black']in ['0','1'];groups[r['black']].append((row,r));eligibleN+=1
 else:missing[r['black']]+=1
 eligibility.append(dict(case='person',sourceFile=person,namedCSVDataRow=row,sourceRowToken=r['sourceRow'],nativeGroup=r['black'],eligibility=reason,selectedCore='0'))
selected=set()
for g,rs in sorted(groups.items()):
 for j,(row,r)in enumerate(choose(rs,120)):
  selected.add(row);x=[F(r['ed76'])/20,F(r['age76'])/40];assert all(0<=v<=1 for v in x);score=F(4,5)*x[0]+F(1,5)*x[1];native={k:v for k,v in r.items()if k not in ['sourceRow','learningRole','learningRolePosition']};assert len(native)==52
  models['person']['records'].append(dict(id='NLS:'+r['id'],role=role(j),group='black-code:'+g,sourceFile=person,namedCSVDataRow=row,upstreamRowToken=r['sourceRow'],nativeFields=native,input=list(map(q,x)),score=q(score),target=int(F(r['wage76'])>=500),withinGroupSelectedPosition=j))
for e in eligibility:e['selectedCore']='1'if e['case']=='person'and e['namedCSVDataRow']in selected else'0'
models['person']['records'].sort(key=lambda r:r['namedCSVDataRow']);models['person'].update(featureNames=['ed76/20','age76/40'],weights=['4/5','1/5'],bias='0',interaction='0')
models['person']['scope']=dict(nativeRows=3613,eligibleRelevantCompleteRows=eligibleN,missingWageRows=sum(r['wage76']=='.'for r in raw),excludedMissingByNativeBlackCode=dict(missing),eligibleByNativeBlackCode={k:len(v)for k,v in groups.items()},selectedRows=len(models['person']['records']),selection='Up to120 equally spaced rows per native black0/1 group within relevant-complete raw source-row order. Purposeful balanced selection; selected-frame proportions are not survey/population estimates. Original NLS weight retained but not used.',groups='Historical original black binary code per Card/Hansen codebook:1ifBlack,0other recorded values. It is neither inferred nor a complete modern self-identified racial taxonomy. All records are men from this historical cohort; no gender comparison is possible.',target='Stipulated teaching outcome wage76>=500 raw cents/hour in1976. Not job qualification, hiring decision, annualincome or contemporary welfare. Missing wage does not establish nonemployment/censoring.',score='Fixed4/5*(ed76/20)+1/5*(age76/40), not a fitted model, a calibrated probability or an education causal return.',roles='Within-group selectedpositionmod10:0–5train,6–7validation,8–9test; purposeful, not random. Original priorlearningRole columns retained unchanged but ignored.',causal='Historical group gaps and attribution do not identify discrimination, a protected-attribute intervention or effects of education.')
company='actual3150-churn-original14-fields.csv';raw=read(company);groups=collections.defaultdict(list)
for row,r in enumerate(raw,1):assert r['Churn']in ['0','1']and r['Complains']in ['0','1']and r['Age Group']in ['1','2','3','4','5'];groups[r['Age Group']].append((row,r))
for g,rs in sorted(groups.items()):
 chosen=choose(rs,48);selectedRows={r[0]for r in chosen}
 for row,r in rs:eligibility.append(dict(case='company',sourceFile=company,namedCSVDataRow=row,sourceRowToken=r['sourceRow'],nativeGroup=g,eligibility='eligible',selectedCore='1'if row in selectedRows else'0'))
 for j,(row,r)in enumerate(chosen):
  failure=F(r['Call  Failure']);assert failure>=0;x=[F(r['Complains']),min(failure,F(20))/20];native={k:v for k,v in r.items()if k not in ['sourceRow','learningRole','learningRolePosition']};assert len(native)==14
  models['company']['records'].append(dict(id='churn-row:'+r['sourceRow'],role=role(j),group='AgeGroup:'+g,sourceFile=company,namedCSVDataRow=row,upstreamRowToken=r['sourceRow'],nativeFields=native,input=list(map(q,x)),score=q(F(4,5)*x[0]+F(1,5)*x[1]),target=int(r['Churn']),withinGroupSelectedPosition=j))
models['company']['records'].sort(key=lambda r:r['namedCSVDataRow']);models['company'].update(featureNames=['Complains','min(CallFailure,20)/20'],weights=['4/5','1/5'],bias='0',interaction='0')
models['company']['scope']=dict(nativeRows=3150,selectedRows=len(models['company']['records']),nativeAgeGroupCounts={g:len(v)for g,v in groups.items()},selection='Up to48 equally spaced rows within each native AgeGroup in original order. Purposefully age-balanced; raw group denominators are retained and selected prevalence is not a population estimate.',groups='Original ordinal AgeGroup1(younger)through5(older); no inferred protected status or legal rule.',time='Official UCIcovariates aggregate first9months; target is month12churn. No individual calendar dates or actual retention treatment outcomes are available.',score='Fixed4/5*Complains+1/5*min(CallFailure,20)/20, not a fitted/calibrated probability. Status/CustomerValue are retained in native downloads but omitted from this score; no leakage claim for unobserved operational fields.',target='Observed Churn0/1. Decision1 can be read as a hypothetical contact flag; usefulness, consent, burden, offer effect and costs are unobserved assumptions.',causal='Neither complaint attribution nor group gaps establish that suppressing complaints would prevent churn; service quality and recording processes may confound association.',roles='Within-group selectedpositionmod10 train0–5/validation6–7/test8–9; no IID/deployment inference.')
for kind,M in models.items():
 for r in M['records']:lineage.append(dict(case=kind,id=r['id'],role=r['role'],group=r['group'],sourceFile=r['sourceFile'],namedCSVDataRow=r['namedCSVDataRow'],upstreamRowToken=r['upstreamRowToken'],nativeTargetToken=r['nativeFields']['valueToken']if kind=='country'else r['nativeFields']['wage76']if kind=='person'else r['nativeFields']['Churn'],teachingTarget=r['target'],score=r['score'],inputJSON=json.dumps(r['input'],separators=(',',':'))))
 assert len({r['id']for r in M['records']})==len(M['records'])
 train=[r for r in M['records']if r['role']=='train'];M['trainingReferenceMean']=[q(sum((F(r['input'][j])for r in train),F(0))/len(train))for j in range(2)];M['candidateThresholds']=['2/5','1/2','3/5'];M['roleCounts']=dict(collections.Counter(r['role']for r in M['records']))


tables={};metrics={};line=[];predictions=[];candidates=[];groupMetrics=[];contributions=[];references=[];choices={}
def cell(v):
 if v is None:return'undefined'
 if isinstance(v,F):return q(v)
 if isinstance(v,bool):return'1'if v else'0'
 return v
for kind,M in models.items():
 rs=[dict(id=r['id'],group=r['group'],target=r['target'],score=r['score'],role=r['role'])for r in M['records']]
 val=[r for r in rs if r['role']=='validation'];choice=decision(dict(rows=val,candidates=[dict(id='threshold:'+t,threshold=t)for t in M['candidateThresholds']],costFalsePositive=1,costFalseNegative=2));chosen=choice['selectedPolicy'];assert chosen is not None;choices[kind]=chosen['id'];threshold=chosen['threshold']
 metrics[kind+'.selectedThreshold']=threshold;metrics[kind+'.validationMeanCost']=chosen['meanValidationCost']
 for c in choice['candidatePolicies']:candidates.append(dict(case=kind,policy=c['id'],threshold=c['threshold'],validationRows=len(val),validationCost=c['meanValidationCost'],selectionGap=c['selectionRateGap'],equalizedOddsGap=c['equalizedOddsGap'],feasible=c['feasible'],selected=c['id']==chosen['id']))
 native={r['id']:r for r in M['records']}
 for r in M['records']:
  line.append(dict(case=kind,id=r['id'],role=r['role'],group=r['group'],sourceFile=r['sourceFile'],namedCSVDataRow=r['namedCSVDataRow'],upstreamRowToken=r['upstreamRowToken'],nativeTargetToken=r['nativeFields']['valueToken']if kind=='country'else r['nativeFields']['wage76']if kind=='person'else r['nativeFields']['Churn'],teachingTarget=r['target'],score=r['score'],input1=r['input'][0],input2=r['input'][1]))
  prediction=int(F(r['score'])>=threshold);predictions.append(dict(case=kind,id=r['id'],role=r['role'],group=r['group'],target=r['target'],score=r['score'],threshold=threshold,prediction=prediction,correct=prediction==r['target'],sourceFile=r['sourceFile'],namedCSVDataRow=r['namedCSVDataRow']))
  reference=sum((F(w)*F(mu)for w,mu in zip(M['weights'],M['trainingReferenceMean'])),F())+F(M['bias']);phi=[F(w)*(F(x)-F(mu))for w,x,mu in zip(M['weights'],r['input'],M['trainingReferenceMean'])];assert sum(phi)==F(r['score'])-reference
  for j in range(2):contributions.append(dict(case=kind,id=r['id'],featureIndex=j,featureName=M['featureNames'][j],input=r['input'][j],trainingMean=M['trainingReferenceMean'][j],directWeight=M['weights'][j],contribution=phi[j],prediction=r['score'],referencePrediction=reference))
 for role in ['all','train','validation','test']:
  ar=audit(rs if role=='all'else[r for r in rs if r['role']==role],threshold)
  for g in ar['groups']:groupMetrics.append(dict(case=kind,role=role,group=g['group'],records=g['records'],mass=g['mass'],tp=g['truePositive'],fp=g['falsePositive'],tn=g['trueNegative'],fn=g['falseNegative'],baseRate=g['baseRate'],selectionRate=g['selectionRate'],TPR=g['truePositiveRate'],FPR=g['falsePositiveRate'],PPV=g['positivePredictiveValue'],NPV=g['negativePredictiveValue'],accuracy=g['accuracy'],Brier=g['meanBrier']))
  if role=='test':
   for key,name in [('accuracy','accuracy'),('selectionRateGap','selectionGap'),('equalizedOddsGap','equalizedOddsGap'),('positivePredictiveValueGap','PPVGap')]:metrics[kind+'.test.'+name]=ar[key]
   metrics[kind+'.test.meanCost']=ratio(sum((g['falsePositive']+2*g['falseNegative']for g in ar['groups']),F()),ar['totalMass'])
   metrics[kind+'.test.rows']=ar['records']
 for j in range(2):references.append(dict(case=kind,featureIndex=j,featureName=M['featureNames'][j],trainingRows=M['roleCounts']['train'],mean=M['trainingReferenceMean'][j],directWeight=M['weights'][j]))
 metrics[kind+'.coreRows']=len(M['records']);metrics[kind+'.trainingRows']=M['roleCounts']['train'];metrics[kind+'.validationRows']=M['roleCounts']['validation']
for name,data in [('native-source-lineage',line),('native-relevant-eligibility-and-selection',eligibility),('validation-policy-candidates',candidates),('core-frozen-policy-outcomes',predictions),('group-role-confusion-and-rates',groupMetrics),('core-linear-reference-contributions',contributions),('training-feature-references',references)]:
 assert data;tables[name]=[{k:cell(v)for k,v in row.items()}for row in data]
 with(out/(name+'.csv')).open('w',encoding='utf8',newline='')as stream:writer=csv.DictWriter(stream,fieldnames=list(data[0]),lineterminator='\n');writer.writeheader();writer.writerows(tables[name])
full=dict(chapter='AI21',metrics={k:cell(v)for k,v in metrics.items()},selectedPolicies=choices,coreRows={k:len(v['records'])for k,v in models.items()},scope='Actual retained observations, purposeful frame, fixed scores and validation-only cutoff selection. Descriptive fairness metrics and linear reference contributions are not population, moral, causal or legal/deployment certification. All original source files preserved.')
(out/'full-results.json').write_text(json.dumps(full,ensure_ascii=False,indent=2)+'\n',encoding='utf8')
manifest=dict(program='Python standard-library Fraction native-only reconstruction',nativeSHA256=SHA,sourceInputFiles=3,newDownloads=0,originalAllCSVBodyFields=255145,coreRecords=len(predictions),eligibilityRows=len(eligibility),metrics=len(metrics),outputs=[dict(file=name+'.csv',rows=len(rs),columns=len(rs[0]),sha256=hashlib.sha256((out/(name+'.csv')).read_bytes()).hexdigest())for name,rs in tables.items()],scope='Every selected record and native eligibility preserved. No test targets used to select candidates; original survey weights unused. Missing wages are not nonemployment. Fixed source scores are not fitted probabilities. Attribution is not a causal effect.')
(out/'manifest.json').write_text(json.dumps(manifest,ensure_ascii=False,indent=2)+'\n',encoding='utf8');print(json.dumps(dict(status='PASS',CSV=len(tables),core=len(predictions),metrics=len(metrics))))
