#!/usr/bin/env python3
"""AI19 native-only evaluation study, Python standard library.
Usage: python actual-source-study.py [native_source_directory] [output_directory]
Inputs are four retained original files only, never JS/model/expected answers.
Exact Fraction fitting, selection, losses, calibration ranks and label sets.
Temporal/class-position/common-company samples do not establish IID or
exchangeability. This is not a real-time-vintage forecasting experiment.
UCI Optdigits: Alpaydin/Kaynak1998, DOI10.24432/C50P49, CC BY4.0.
"""
from pathlib import Path
from fractions import Fraction as F
import csv,json,hashlib,sys,math
here=Path(__file__).resolve().parent
S=Path(sys.argv[1])if len(sys.argv)>1 else here.parent/'ai19-sources'
O=Path(sys.argv[2])if len(sys.argv)>2 else here/'reproduced-python';O.mkdir(parents=True,exist_ok=True)
SHA={'actual360-four-country-growth-CPI-1980-2024.csv':'523e0d7eb4ddabe95be0e54fd466ca8a571ad285b094e115521ac9b9d148934f','actual30-Apple-product-sales-FY2019-2024.csv':'b163b104c02e0362e0d61fdb3bb220350a97e6e25f6eb6098b742bfac2aa5598','optdigits.tra':'e1b683cc211604fe8fd8c4417e6a69f31380e0c61d4af22e93cc21e9257ffedd','optdigits.tes':'6ebb3d2fee246a4e99363262ddf8a00a3c41bee6014c373ed9d9216ba7f651b8'}
for name,h in SHA.items():assert hashlib.sha256((S/name).read_bytes()).hexdigest()==h,('original hash',name)
J=lambda x:json.dumps(x,ensure_ascii=False,separators=(',',':'))
qs=lambda q:str(q.numerator)if q.denominator==1 else str(q.numerator)+'/'+str(q.denominator)
def mean(v):return sum(v,F(0))/len(v)if v else None
def text(q):return ''if q is None else qs(q)
def read(name,header=True):
 with(S/name).open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f)if header else csv.reader(f))
M={k:[]for k in ['country','person','company']};lineage=[];prototypes={}
def add(k,r):M[k].append(r)
def origin(kind,id,name,row,upstream,role,group,native):lineage.append(dict(case=kind,id=id,nativeFile=name,namedCSVDataRow=row,upstreamRowToken=upstream,role=role,group=group,nativeTokensJSON=J(native)))
name='actual360-four-country-growth-CPI-1980-2024.csv';raw=read(name);assert len(raw)==360 and all(len(r)==8 for r in raw);lookup={(r['countryISO3'],int(r['year'])):(i+1,r)for i,r in enumerate(raw)if r['indicatorID']=='NY.GDP.MKTP.KD.ZG'}
for iso in sorted({r['countryISO3']for r in raw}):
 mu=mean([F(lookup[iso,y][1]['valueToken'])for y in range(1980,2000)])
 for year in range(1980,2025):
  row,r=lookup[iso,year];role='train'if year<2000 else'validation'if year<2008 else'calibration'if year<2016 else'test';origin('country',f'{iso}:GDP:{year}',name,row,r['originalSourceRow'],role,iso,r)
  if year>1980:add('country',dict(id=f'{iso}:{year}',nativeFile=name,namedCSVDataRow=row,role=role,group=iso,target=F(r['valueToken']),predictionA=F(lookup[iso,year-1][1]['valueToken']),predictionB=mu))
selected=[]
for name in ['optdigits.tra','optdigits.tes']:
 raw=read(name,False);assert len(raw)==(3823 if name.endswith('.tra')else 1797)
 assert all(len(r)==65 and all(0<=int(x)<=16 for x in r[:64])and 0<=int(r[64])<=9 for r in raw)
 for label in range(10):
  native=[(i+1,r)for i,r in enumerate(raw)if int(r[64])==label]
  for j in range(6):
   row,r=native[j*(len(native)-1)//5];role=('calibration'if j<3 else'test')if name.endswith('.tes')else('validation'if j in [2,5]else'train');pixels=list(map(int,r[:64]));quad=[sum(pixels[8*a+b]for a in range(a0,a0+4)for b in range(b0,b0+4))for a0,b0 in [(0,0),(0,4),(4,0),(4,4)]];selected.append(dict(id=name+':'+str(row),nativeFile=name,namedCSVDataRow=row,role=role,group='digit:'+str(label),target=str(label),featuresA=list(map(F,quad)),featuresB=list(map(F,pixels)),nativeTokens=r))
selected.sort(key=lambda r:(r['nativeFile'],r['namedCSVDataRow']))
for key in ['A','B']:
 prototypes[key]={str(label):[mean([r['features'+key][i]for r in selected if r['role']=='train'and r['target']==str(label)])for i in range(4 if key=='A'else 64)]for label in range(10)}
def distance(r,key,label):return sum((a-b)**2 for a,b in zip(r['features'+key],prototypes[key][label]))
for r in selected:
 for key in ['A','B']:r['prediction'+key]=min(prototypes[key],key=lambda label:distance(r,key,label))
 origin('person',r['id'],r['nativeFile'],r['namedCSVDataRow'],'',r['role'],r['group'],r['nativeTokens']);add('person',r)
name='actual30-Apple-product-sales-FY2019-2024.csv';raw=read(name);assert len(raw)==30 and all(len(r)==7 and r['originalUSDMillionsToken'].replace(',','')==r['valueUSDMillions']for r in raw);lookup={(r['product'],int(r['fiscalYear'])):(i+1,r)for i,r in enumerate(raw)}
for product in dict.fromkeys(r['product']for r in raw):
 y0,y1,y2=[F(lookup[product,y][1]['valueUSDMillions'])for y in [2019,2020,2021]];mu=(y0+y1+y2)/3;slope=(y2-y0)/2
 for year in range(2019,2025):
  row,r=lookup[product,year];role='train'if year<=2021 else'validation'if year==2022 else'calibration'if year==2023 else'test';origin('company',product+':'+str(year),name,row,'',role,product,r)
  if year>=2022:add('company',dict(id=product+':'+str(year),nativeFile=name,namedCSVDataRow=row,role=role,group=product,target=F(r['valueUSDMillions']),predictionA=F(lookup[product,year-1][1]['valueUSDMillions']),predictionB=mu+slope*(year-2020)))
tables={};headers={};metrics={};core=[];roles=[];calibration=[];tests=[];selections=[];groups=[]
for kind,rows in M.items():
 for r in rows:
  for key in ['A','B']:r['loss'+key]=F(r['target']!=r['prediction'+key])if kind=='person'else(r['target']-r['prediction'+key])**2
  r['difference']=r['lossA']-r['lossB']
 vm={key:mean([r['loss'+key]for r in rows if r['role']=='validation'])for key in ['A','B']};winner=min(['A','B'],key=lambda key:vm[key]);cal=[r for r in rows if r['role']=='calibration'];test=[r for r in rows if r['role']=='test']
 def score(r,label=None):return distance(r,winner,r['target']if label is None else label)if kind=='person'else abs(r['target']-r['prediction'+winner])
 scores=list(map(score,cal));k=math.ceil(F(len(cal)+1)*F(9,10));q=sorted(scores)[k-1]if k<=len(cal)else None
 for r in rows:core.append(dict(case=kind,id=r['id'],nativeFile=r['nativeFile'],namedCSVDataRow=r['namedCSVDataRow'],role=r['role'],group=r['group'],target=r['target']if kind=='person'else qs(r['target']),predictionA=r['predictionA']if kind=='person'else qs(r['predictionA']),predictionB=r['predictionB']if kind=='person'else qs(r['predictionB']),lossA=qs(r['lossA']),lossB=qs(r['lossB']),differenceAminusB=qs(r['difference']),selectedProfile=winner))
 for role in ['train','validation','calibration','test']:
  rs=[r for r in rows if r['role']==role];ma=mean([r['lossA']for r in rs]);mb=mean([r['lossB']for r in rs]);roles.append(dict(case=kind,role=role,records=len(rs),meanLossA=text(ma),meanLossB=text(mb),meanDifferenceAminusB=text(None if ma is None else ma-mb)));metrics[f'{kind}.{role}.records']=len(rs)
  for key,val in [('meanLossA',ma),('meanLossB',mb),('meanDifferenceAminusB',None if ma is None else ma-mb)]:metrics[f'{kind}.{role}.{key}']=None if val is None else qs(val)
 for i,(r,s)in enumerate(zip(cal,scores)):calibration.append(dict(case=kind,id=r['id'],group=r['group'],calibrationOrder=i+1,score=qs(s)))
 covered=0;set_sizes=[]
 for r in test:
  s=score(r);inc=q is None or s<=q;covered+=inc;cs={str(label):qs(score(r,str(label)))for label in range(10)}if kind=='person'else{};ids=[label for label,value in cs.items()if q is None or F(value)<=q];set_sizes.append(len(ids))
  tests.append(dict(case=kind,id=r['id'],group=r['group'],target=r['target']if kind=='person'else qs(r['target']),prediction=r['prediction'+winner]if kind=='person'else qs(r['prediction'+winner]),score=qs(s),threshold='+Infinity'if q is None else qs(q),covered=int(inc),lower=''if kind=='person'else'-Infinity'if q is None else qs(r['prediction'+winner]-q),upper=''if kind=='person'else'+Infinity'if q is None else qs(r['prediction'+winner]+q),includedLabelsJSON=J(ids)if kind=='person'else'',candidateScoresJSON=J(cs)if kind=='person'else''))
 for group in dict.fromkeys(r['group']for r in test):
  rs=[r for r in test if r['group']==group];ma=mean([r['lossA']for r in rs]);mb=mean([r['lossB']for r in rs]);groups.append(dict(case=kind,group=group,records=len(rs),meanLossA=qs(ma),meanLossB=qs(mb),meanDifferenceAminusB=qs(ma-mb)))
 selections.append(dict(case=kind,selectedProfile=winner,validationMeanLossA=qs(vm['A']),validationMeanLossB=qs(vm['B']),calibrationCount=len(cal),alpha='1/10',rank=k,threshold='+Infinity'if q is None else qs(q),testCount=len(test),testCovered=covered,testCoverage=qs(F(covered,len(test))),meanLabelSetSize=qs(F(sum(set_sizes),len(test)))if kind=='person'else'',iidOrExchangeabilityEstablished='false'))
 for key,value in [('calibrationCount',len(cal)),('rank',k),('threshold',None if q is None else qs(q)),('testCount',len(test)),('testCovered',covered),('testCoverage',qs(F(covered,len(test))))]:metrics[f'{kind}.{key}']=value
 if kind=='person':
  b=sum(r['target']==r['predictionA']and r['target']!=r['predictionB']for r in test);c=sum(r['target']!=r['predictionA']and r['target']==r['predictionB']for r in test);m=b+c;p=min(F(1),F(2*sum(math.comb(m,j)for j in range(min(b,c)+1)),2**m));metrics.update({'person.paired.Aonly':b,'person.paired.Bonly':c,'person.paired.conditionalP':qs(p),'person.meanLabelSetSize':qs(F(sum(set_sizes),len(test)))})
for name,rows in [('source-selection-lineage',lineage),('paired-core-predictions',core),('case-role-summary',roles),('conformal-calibration-scores',calibration),('conformal-test-results',tests),('validation-selections',selections),('test-group-mean-differences',groups)]:
 assert rows;tables[name]=rows
 with(O/(name+'.csv')).open('w',encoding='utf8',newline='')as f:w=csv.DictWriter(f,fieldnames=list(rows[0]),lineterminator='\n');w.writeheader();w.writerows(rows)
full=dict(chapter='AI19',metrics=metrics,selectedProfiles={r['case']:r['selectedProfile']for r in selections},scope='Native-only exact fitting/evaluation/calibration; three actual retained cases. Conditional independent-sign McNemar reference is descriptive unless its design is justified. No IID/exchangeability or operational-vintage certificate.',candidateMatrixPolicy='Only ten candidate scores per actual digit test row are output; no unused Cartesian paths.')
(O/'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 reproduction',nativeSHA256=SHA,nativeBodyFields=368390,outputs=[dict(file=name+'.csv',rows=len(rows),columns=len(rows[0]),sha256=hashlib.sha256((O/(name+'.csv')).read_bytes()).hexdigest())for name,rows in tables.items()],corePairedPredictions=len(core),calibrationScores=len(calibration),testOutputs=len(tests),metrics=len(metrics),license='UCI CC BY4.0, Alpaydin/Kaynak1998 DOI10.24432/C50P49; retained WorldBank/Apple factual tokens with original attribution.')
(O/'manifest.json').write_text(json.dumps(manifest,ensure_ascii=False,indent=2)+'\n',encoding='utf8');print(J(dict(status='PASS',csv=len(tables),core=len(core),calibration=len(calibration),test=len(tests),metrics=len(metrics))))
