#!/usr/bin/env python3
"""AI10 actual-data linear recurrence, exact standard-library reproduction.

Run: python ai10-reproduce.py --data-dir ai10-sources --output-dir ai10-reproduced
Reads only three factual CSVs. It never imports a browser engine, a model/source
contract, a stored answer, derived lineage or another checker. Reconstructs
windows, training vocabulary, initialization, full reverse BPTT and one full-batch
SGD update. Modern LSTM/GRU are separate teaching labs, not fitted here.
"""
from pathlib import Path
from fractions import Fraction as Q
import argparse,csv,json,copy,hashlib

NATIVE_FILES=['actual360-four-country-growth-CPI-1980-2024.csv','actual3613-NLS-original52-fields.csv','actual30-Apple-product-sales-FY2019-2024.csv']
def read(p):
 with p.open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))
def value(s):return None if s in [None,'','.']else Q(s)
def exact(v):return ''if v is None else str(v)
def dot(a,b):return sum((x*y for x,y in zip(a,b)),Q(0))
def vector(n):return[Q(0)for _ in range(n)]
def zeros(v):return[zeros(x)for x in v]if isinstance(v,list)else Q(0)
def mapper(v,fn):return[mapper(x,fn)for x in v]if isinstance(v,list)else fn(v)
def leaves(v,prefix=()):
 if isinstance(v,list):
  for i,x in enumerate(v):yield from leaves(x,prefix+(i,))
 else:yield prefix,v
def get(v,index):
 for i in index:v=v[i]
 return v
def update_leaf(v,index,x):
 if not index:return x
 v[index[0]]=update_leaf(v[index[0]],index[1:],x);return v
def initialize(features,vocabulary):
 return dict(A=[[Q(1,2),Q(1,10)],[Q(0),Q(1,2)]],B=[[Q(1,5)]*features,[Q(-1,10)]*features],M=[[Q(1,10)]*features,[Q(-1,20)]*features],U=[[Q(1,5),Q(0)],[Q(0),Q(1,5)]],b=vector(2),C=[Q(1,2),Q(1,4)],d=Q(0),E=[[Q(i%3-1,20),Q((i%2)*2-1,20)]for i in range(len(vocabulary))])
def reconstruct(data_dir):
 country_rows=read(data_dir/NATIVE_FILES[0]);people_rows=read(data_dir/NATIVE_FILES[1]);sales_rows=read(data_dir/NATIVE_FILES[2]);samples={k:[]for k in ['country','person','company']}
 wb={(r['countryISO3'],int(r['year']),r['indicatorID']):r for r in country_rows}
 for iso in ['KOR','USA','DEU','JPN']:
  for target_year in range(1981,2025):
   steps=[]
   for year in range(max(1980,target_year-4),target_year):
    g=wb[(iso,year,'NY.GDP.MKTP.KD.ZG')];p=wb[(iso,year,'FP.CPI.TOTL.ZG')]
    steps.append(dict(x=[value(g['valueToken'])/20,value(p['valueToken'])/10],time=year,source=[int(g['originalSourceRow']),int(p['originalSourceRow'])]))
   y=wb[(iso,target_year,'NY.GDP.MKTP.KD.ZG')]
   samples['country'].append(dict(id=f'{iso}:{target_year}',token=iso,role='train'if target_year<=2014 else'validation'if target_year<=2019 else'test',steps=steps,target=value(y['valueToken'])/20,targetSource=int(y['originalSourceRow']),weight=Q(1),scale=Q(20)))
 for j in range(48):
  source_row=1+(j*3612)//47;r=people_rows[source_row-1];role='train'if j%6<4 else'validation'if j%6==4 else'test';token='education1976:'+r['ed76']
  for target_year in [1978,1980]:
   steps=[]
   for year in [y for y in [1976,1978]if y<target_year]:
    wage=value(r['wage'+str(year)[-2:]])
    steps.append(dict(x=[None if wage is None else wage/1000],time=year,source=source_row))
   wage=value(r['wage'+str(target_year)[-2:]])
   samples['person'].append(dict(id=f'nls-row:{source_row}:target{target_year}',token=token,role=role,steps=steps,target=None if wage is None else wage/1000,targetSource=source_row,weight=Q(1),scale=Q(1000)))
 sales={(r['product'],int(r['fiscalYear'])):r for r in sales_rows}
 for product in ['iPhone','Mac','iPad','Wearables, Home and Accessories','Services']:
  for target_year in range(2020,2025):
   steps=[dict(x=[value(sales[(product,year)]['valueUSDMillions'])/100000],time=year,source=f'{product}:FY{year}')for year in range(max(2019,target_year-4),target_year)]
   samples['company'].append(dict(id=f'{product}:FY{target_year}',token=product,role='train'if target_year<=2022 else'validation'if target_year==2023 else'test',steps=steps,target=value(sales[(product,target_year)]['valueUSDMillions'])/100000,targetSource=f'{product}:FY{target_year}',weight=Q(1),scale=Q(100000)))
 return samples
def forward(model,sample,vocab):
 h=vector(2);history=[];idx=vocab.index(sample['token'])if sample['token']in vocab else 0;e=model['E'][idx]
 for step in sample['steps']:
  x=[Q(0)if v is None else v for v in step['x']];missing=[Q(v is None)for v in step['x']];old=h
  h=[dot(model['A'][j],old)+dot(model['B'][j],x)+dot(model['M'][j],missing)+dot(model['U'][j],e)+model['b'][j]for j in range(2)]
  history.append(dict(previous=old,x=x,missing=missing,embedding=e,h=h,tokenIndex=idx,time=step['time']))
 return dot(model['C'],h)+model['d'],h,history
def reverse(model,sample,vocab):
 pred,h,history=forward(model,sample,vocab);g={k:zeros(v)for k,v in model.items()};residual=pred-sample['target'];g['C']=[residual*v for v in h];g['d']=residual;adj=[residual*v for v in model['C']]
 for step in reversed(history):
  for i in range(2):
   for j in range(2):g['A'][i][j]+=adj[i]*step['previous'][j];g['U'][i][j]+=adj[i]*step['embedding'][j]
   for j in range(len(step['x'])):g['B'][i][j]+=adj[i]*step['x'][j];g['M'][i][j]+=adj[i]*step['missing'][j]
   g['b'][i]+=adj[i]
  for j in range(2):g['E'][step['tokenIndex']][j]+=sum((model['U'][i][j]*adj[i]for i in range(2)),Q(0))
  adj=[sum((model['A'][i][j]*adj[i]for i in range(2)),Q(0))for j in range(2)]
 return g
def criterion(model,samples,vocab,role):
 rows=[s for s in samples if s['role']==role];eligible=[s for s in rows if s['target']is not None and s['weight']>0];weight=sum((s['weight']for s in eligible),Q(0))
 loss=sum((s['weight']*(forward(model,s,vocab)[0]-s['target'])**2/2 for s in eligible),Q(0))/weight if weight else None
 return dict(windows=len(rows),observedTargets=sum(s['target']is not None for s in rows),eligibleWeight=weight,meanHalfSquaredLoss=loss)
def fit(samples):
 vocab=['<UNK>']+sorted({s['token']for s in samples if s['role']=='train'});initial=initialize(len(samples[0]['steps'][0]['x']),vocab);g={k:zeros(v)for k,v in initial.items()};train=[s for s in samples if s['role']=='train'and s['target']is not None and s['weight']>0];den=sum((s['weight']for s in train),Q(0))
 for s in train:
  one=reverse(initial,s,vocab)
  for k in g:
   for index,v in leaves(one[k]):g[k]=update_leaf(g[k],index,get(g[k],index)+s['weight']*v/den)
 norm=max((abs(v)for a in g.values()for _,v in leaves(a)),default=Q(0));factor=min(Q(1),1/norm)if norm else Q(1);new=copy.deepcopy(initial)
 for k in new:
  for index,v in leaves(initial[k]):new[k]=update_leaf(new[k],index,v-Q(1,100)*factor*get(g[k],index))
 criteria=[{role:criterion(model,samples,vocab,role)for role in ['train','validation','test']}for model in [initial,new]];v0,v1=[c['validation']['meanHalfSquaredLoss']for c in criteria];selected=1 if v0 is not None and v1 is not None and v1<v0 else 0;model=[initial,new][selected]
 records=[];summaries={}
 for s in samples:
  pred,h,hist=forward(model,s,vocab);target=s['target'];baseline=s['steps'][-1]['x'][0];common=target is not None and baseline is not None and s['weight']>0
  records.append(dict(sample=s,prediction=pred,hidden=h,history=hist,baseline=baseline,common=common,halfLoss=None if target is None else(pred-target)**2/2,baselineHalfLoss=None if target is None or baseline is None else(baseline-target)**2/2))
 for role in ['train','validation','test']:
  rr=[r for r in records if r['sample']['role']==role];common=[r for r in rr if r['common']];weight=sum((r['sample']['weight']for r in common),Q(0));rnn=sum((r['sample']['weight']*r['halfLoss']for r in common),Q(0))/weight if weight else None;base=sum((r['sample']['weight']*r['baselineHalfLoss']for r in common),Q(0))/weight if weight else None
  summaries[role]=dict(**criteria[selected][role],commonBaselineWindows=len(common),commonWeight=weight,rnnCommonHalfLoss=rnn,persistenceCommonHalfLoss=base,unknownTokenWindows=sum(r['sample']['token']not in vocab for r in rr))
 return dict(vocabulary=vocab,initial=initial,gradient=g,afterOne=new,gradientLinf=norm,clipFactor=factor,selectedStep=selected,selectedModel=model,criteria=criteria,records=records,summary=summaries)
def write_csv(p,heads,rows):
 with p.open('w',encoding='utf8',newline='')as f:
  w=csv.writer(f,lineterminator='\n');w.writerow(heads);w.writerows(rows)
 return dict(file=p.name,rows=len(rows),columns=len(heads),bodyFields=len(rows)*len(heads),SHA256=hashlib.sha256(p.read_bytes()).hexdigest())
def export(data_dir,out):
 out.mkdir(parents=True,exist_ok=True);samples=reconstruct(data_dir);results={k:fit(v)for k,v in samples.items()};sequence=[];vocabulary=[];parameters=[];checkpoints=[];predictions=[];states=[];metrics=[]
 def metric(key,v,definition):metrics.append([key,'true'if v is not None else'false',exact(v),definition])
 for kind,res in results.items():
  vocab=res['vocabulary'];metric(kind+'.selectedStep',Q(res['selectedStep']),'Earliest strict validation minimum, checkpoints0/1');metric(kind+'.gradientLinf',res['gradientLinf'],'Maximum absolute normalized training gradient entry');metric(kind+'.clipFactor',res['clipFactor'],'One common Linfinity clipping factor, cap1')
  for j,t in enumerate(vocab):vocabulary.append([kind,j,t,sum(s['token']==t and s['role']=='train'for s in samples[kind]),sum(len(s['steps'])for s in samples[kind]if s['token']==t and s['role']=='train')])
  for k,v in res['initial'].items():
   for index,old in leaves(v):
    g=get(res['gradient'][k],index);parameters.append([kind,k,json.dumps(index),exact(old),exact(g),exact(res['clipFactor']),exact(g*res['clipFactor']),exact(get(res['afterOne'][k],index)),exact(get(res['selectedModel'][k],index))])
  for cp,criteria in enumerate(res['criteria']):
   for role,c in criteria.items():checkpoints.append([kind,cp,role,c['windows'],c['observedTargets'],exact(c['eligibleWeight']),exact(c['meanHalfSquaredLoss']),'true'if cp==res['selectedStep']else'false'])
  for role,c in res['summary'].items():
   for key,v in c.items():metric(kind+'.'+role+'.'+key,None if v is None else Q(v),'Same selected model and role; baseline scores use common eligible windows')
  for record in res['records']:
   s=record['sample'];idx=vocab.index(s['token'])if s['token']in vocab else 0;unknown=s['token']not in vocab
   predictions.append([kind,s['id'],s['role'],s['token'],idx,'true'if unknown else'false',len(s['steps']),s['steps'][-1]['time'],str(s['targetSource']),exact(s['target']),exact(record['prediction']),exact(record['halfLoss']),exact(record['baseline']),exact(record['baselineHalfLoss']),'true'if record['common']else'false',exact(s['scale']),exact(s['weight'])])
   for j,(step,h)in enumerate(zip(s['steps'],record['history']),1):
    sequence.append([kind,s['id'],s['role'],s['token'],idx,'true'if unknown else'false',j,step['time'],json.dumps(step['source'],ensure_ascii=False),json.dumps([None if v is None else str(v)for v in step['x']]),exact(s['target']),str(s['targetSource']),exact(s['weight'])])
    states.append([kind,s['id'],s['role'],j,step['time'],exact(h['h'][0]),exact(h['h'][1]),exact(step['x'][0]),exact(step['x'][1])if len(step['x'])>1 else'','true'if step['x'][0]is None else'false','true'if len(step['x'])>1 and step['x'][1]is None else'false'])
 files=[]
 for filename,heads,rows in [
  ('derived-ai10-public-sequence-rows.csv',['case','id','role','sourceToken','vocabularyIndex','unknownToken','step','time','sourceJSON','xExactJSON','targetExact','targetSource','weightExact'],sequence),
  ('derived-ai10-public-vocabulary.csv',['case','index','token','trainingWindows','trainingActiveSteps'],vocabulary),
  ('derived-ai10-public-parameter-updates.csv',['case','parameter','indexJSON','initialExact','meanGradientExact','clipFactorExact','clippedGradientExact','afterOneUpdateExact','selectedExact'],parameters),
  ('derived-ai10-public-checkpoints.csv',['case','checkpoint','role','windows','observedTargets','eligibleWeightExact','meanHalfSquaredLossExact','selected'],checkpoints),
  ('derived-ai10-public-predictions-and-baselines.csv',['case','id','role','sourceToken','vocabularyIndex','unknownToken','activeSteps','lastInputTime','targetSource','targetExact','selectedPredictionExact','selectedHalfLossExact','persistenceExact','persistenceHalfLossExact','commonBaseline','nativeScale','weightExact'],predictions),
  ('derived-ai10-public-state-trajectories.csv',['case','id','role','step','time','h1Exact','h2Exact','x1Exact','x2Exact','missing1','missing2'],states),
  ('derived-ai10-public-summary-metrics.csv',['metric','defined','exactValue','definition'],metrics)]:files.append(write_csv(out/filename,heads,rows))
 summary={kind:{key:val for key,val in res.items()if key not in ['records']}for kind,res in results.items()}
 def serial(v):
  if isinstance(v,Q):return str(v)
  if isinstance(v,list):return[serial(x)for x in v]
  if isinstance(v,dict):return{k:serial(x)for k,x in v.items()}
  return v
 (out/'ai10-reproduction-summary.json').write_text(json.dumps(serial(summary),ensure_ascii=False,indent=2)+'\n',encoding='utf8')
 manifest=dict(method='Standalone standard-library Fraction source reconstruction + full reverse BPTT + one full-batch SGD update; exact Linfinity common-factor clipping; earliest strict validation selection',inputs=[dict(file=n,SHA256=hashlib.sha256((data_dir/n).read_bytes()).hexdigest())for n in NATIVE_FILES],outputs=files,counts=dict(samples=sum(map(len,samples.values())),lagSteps=len(sequence),metrics=len(metrics)),boundaries=['Actual linear recurrent model only, not fitted LSTM/GRU','Country retained revised vintage, retrospective one-step windows; no real-time vintage reconstruction','Native wage missingness remains missing, not diagnosed as nonemployment; original survey weights not applied','Nominal company fiscal-year product sales, not real output, unit shipments or profit','Persistence is undefined when latest lag is missing; comparison uses common target coverage','Exact arithmetic does not certify causal identification, inference or useful prediction'])
 (out/'ai10-reproduction-manifest.json').write_text(json.dumps(manifest,ensure_ascii=False,indent=2)+'\n',encoding='utf8')
 print(json.dumps(dict(status='completed exact standalone reproduction',counts=manifest['counts'],selected={k:v['selectedStep']for k,v in results.items()},outputDir=str(out)),ensure_ascii=False))
if __name__=='__main__':
 p=argparse.ArgumentParser(description=__doc__);p.add_argument('--data-dir',type=Path,default=Path(__file__).resolve().parent/'ai10-sources');p.add_argument('--output-dir',type=Path,default=Path(__file__).resolve().parent/'ai10-reproduced');a=p.parse_args();export(a.data_dir,a.output_dir)
