#!/usr/bin/env python3
"""AI17 retained-data workflow experiment, Python standard library only.
Usage: python actual-source-study.py [native_source_directory] [output_directory]
Defaults are relative to this code file. Scientific inputs: three native CSVs.
The original MovieLens README is a required redistribution companion, copied to
the output. No JS engine, source-model JSON or prepared answer table is read.
Tasks, roles, controller policies, injected faults and rewards are declared
teaching choices, not observed incidents/LLM performance. Native tokens survive.
MovieLens credit: Harper and Konstan (2015), doi:10.1145/2827872. Original use
conditions/no warranty/no endorsement/prior commercial permission still apply.
"""
from pathlib import Path
from fractions import Fraction as Q
import csv,json,hashlib,sys,re,collections,shutil
HERE=Path(__file__).resolve().parent
SRC=Path(sys.argv[1]).resolve() if len(sys.argv)>1 else HERE.parent/'ai17-sources'
OUT=Path(sys.argv[2]).resolve() if len(sys.argv)>2 else HERE/'reproduced-python'
OUT.mkdir(parents=True,exist_ok=True)
NAMES={'country':'actual32-country-observations-2024.csv','person':'movielens-original-movies.csv','company':'actual30-Apple-product-sales-FY2019-2024.csv'}
HASH={'country':'4a544884181b228f4539c859abb874f92ddd77f09b956d1ba9c96d37b6f8587b','person':'5a5f32dd9bb3797b8e728a1b98958789d2b13f294a69fdfbc5727f8a9611aa07','company':'b163b104c02e0362e0d61fdb3bb220350a97e6e25f6eb6098b742bfac2aa5598'}
READMEHASH='63d22ac138e80fae37021797ed8e1b9424b5239dc576a137422adf783ae3f404'
H=lambda p:hashlib.sha256(p.read_bytes()).hexdigest()
key=lambda p,s:hashlib.sha256((p+'|'+s).encode('utf-8')).hexdigest()
J=lambda x:json.dumps(x,ensure_ascii=False,separators=(',',':'))
B=lambda x:'true' if x else 'false'
raw={}
for kind,name in NAMES.items():
 p=SRC/name
 if H(p)!=HASH[kind]:raise ValueError('Native SHA mismatch: '+name)
 with p.open(encoding='utf-8-sig',newline='') as f:raw[kind]=list(csv.DictReader(f))
readme=SRC/'MovieLens-README-original.txt'
if H(readme)!=READMEHASH:raise ValueError('Original MovieLens README missing or changed')
shutil.copyfile(readme,OUT/readme.name)
records={k:[] for k in NAMES};tasks={k:[] for k in NAMES};ledgers=[]
def rec(kind,id,row,native,unit,year,extra,value=None,upstream=None):
 r=dict(recordID=id,kind={'country':'annualRate','person':'movieCatalog','company':'nominalProductSales'}[kind],unit=unit,year=str(year),**extra)
 if value is not None:r['valueToken']=value
 r['provenance']=dict(file=NAMES[kind],sourceRow=str(row),nativeSHA256=HASH[kind])
 if upstream is not None:r['provenance']['upstreamSourceRowToken']=upstream
 item=dict(id=id,response=r,nativeFields=dict(native),sourceRow=str(row));records[kind].append(item);return item
def meta(r):return{k:r[k] for k in ['recordID','kind','unit','year']}
def task(kind,id,role,group,operation,refs,answer):
 tasks[kind].append(dict(id=id,role=role,group=group,operation=operation,lookups=[dict(recordID=r['id'],expectedMetadata=meta(r['response'])) for r in refs],expectedAnswer=answer))
country_order=sorted({r['countryISO3'] for r in raw['country']},key=lambda c:(key('AI17-country-role',c),c));country_roles={c:'train' if i<8 else 'validation' if i<12 else 'test' for i,c in enumerate(country_order)};by_country={}
for row,r in enumerate(raw['country'],1):
 id=f"WB:{r['countryISO3']}:{r['indicatorID']}:{r['date']}";by_country[r['countryISO3'],r['indicatorID']]=rec('country',id,row,r,'annual-percent',r['date'],dict(countryISO3=r['countryISO3'],indicatorID=r['indicatorID']),r['originalValueToken'],r['sourceRow'])
for c in sorted(country_order):
 refs=[by_country[c,i] for i in ['NY.GDP.MKTP.KD.ZG','FP.CPI.TOTL.ZG']];task('country','country:'+c,country_roles[c],c,'country-pair',refs,dict(gdpGrowthToken=refs[0]['response']['valueToken'],cpiInflationToken=refs[1]['response']['valueToken'],evidence=[meta(r['response']) for r in refs]))
ranked=sorted(enumerate(raw['person'],1),key=lambda z:(key('AI16-person-corpus',z[1]['movieId']),z[1]['movieId']));frame=ranked[:240];chosenids={r['movieId'] for row,r in frame};query=sorted(frame,key=lambda z:(key('AI17-person-task',z[1]['movieId']),z[1]['movieId']))[:40];movie_roles={r['movieId']:'train' if i<20 else 'validation' if i<30 else 'test' for i,(row,r) in enumerate(query)};by_movie={}
for row,r in enumerate(raw['person'],1):
 selected=r['movieId'] in chosenids;ledgers.append(dict(sourceRow=row,movieId=r['movieId'],title=r['title'],genres=r['genres'],frameSHA=key('AI16-person-corpus',r['movieId']),in240Frame=B(selected),taskSHA=key('AI17-person-task',r['movieId']) if selected else '',taskRole=movie_roles.get(r['movieId'],'')))
 if selected:
  y=re.search(r'\((\d{4})\)\s*$',r['title']);by_movie[r['movieId']]=rec('person','MovieLens:movie:'+r['movieId'],row,r,'year-in-title',y[1] if y else 'not-present',dict(movieID=r['movieId'],title=r['title'],genres=r['genres'].split('|')))
for row,r in query:
 v=by_movie[r['movieId']];task('person','movie:'+r['movieId'],movie_roles[r['movieId']],r['movieId'],'movie-facts',[v],dict(movieID=r['movieId'],title=r['title'],genres=r['genres'].split('|'),evidence=[meta(v['response'])]))
sales={}
for row,r in enumerate(raw['company'],1):
 assert r['originalUSDMillionsToken'].replace(',','')==r['valueUSDMillions']
 sales[r['product'],int(r['fiscalYear'])]=rec('company',f"Apple:{r['product']}:{r['fiscalYear']}",row,r,'nominal-USD-million',r['fiscalYear'],dict(product=r['product'],sourceOriginalValueToken=r['originalUSDMillionsToken']),r['valueUSDMillions'])
growth=[]
for product in sorted({r['product'] for r in raw['company']}):
 for year in range(2020,2025):
  refs=[sales[product,year],sales[product,year-1]];x,b=[Q(r['response']['valueToken']) for r in refs]
  if b<=0:raise ValueError('This declared retained growth frame needs positive bases')
  g=100*(x-b)/b;task('company',f'growth:{product}:{year}','train' if year<=2022 else 'validation' if year==2023 else 'test',str(year),'sales-growth',refs,dict(growthPercentFraction=str(g),evidence=[meta(r['response']) for r in refs]));growth.append(dict(product=product,fiscalYear=year,currentOriginalToken=refs[0]['nativeFields']['originalUSDMillionsToken'],priorOriginalToken=refs[1]['nativeFields']['originalUSDMillionsToken'],currentValueToken=str(x),priorValueToken=str(b),growthPercentFraction=str(g),namedCSVRows=J([r['sourceRow'] for r in refs])))
POLICIES=['single','retry-transient','checked-single','checked-retry-transient'];SCENARIOS=['clean','first-attempt-transient-timeout','persistent-stale-metadata','persistent-wrong-kind-or-unit','persistent-valid-typed-corruption','persistent-missing-result']
runrows=[];traces=[];means=[];scenario_means=[];selections=[]
def execute(kind,t,policy,scenario):
 checked=policy.startswith('checked-');retry=policy.endswith('retry-transient');by={r['id']:r for r in records[kind]};accepted_responses=[];attempted=0;reason=None
 for step,lookup in enumerate(t['lookups'],1):
  response=None
  for attempt in range(1,4 if retry else 2):
   attempted+=1;status='ok';issues=[];response=None
   if step==1 and scenario=='first-attempt-transient-timeout' and attempt==1:status='transient-error'
   elif step==1 and scenario=='persistent-missing-result':status='missing'
   else:
    response=json.loads(J(by[lookup['recordID']]['response']))
    if step==1 and scenario=='persistent-stale-metadata':response['year']=str(int(response['year'])-1) if re.fullmatch(r'\d{4}',response['year']) else 'unrelated-year'
    if step==1 and scenario=='persistent-wrong-kind-or-unit':response['unit']='unrelated-unit'
    if step==1 and scenario=='persistent-valid-typed-corruption':
     if 'valueToken' in response:response['valueToken']=str(Q(response['valueToken'])+1)
     else:response['title']+=' [corrupted]'
    if checked:issues=['metadata-mismatch:'+k for k,v in lookup['expectedMetadata'].items() if response[k]!=v]
   traces.append(dict(kind=kind,taskID=t['id'],policy=policy,scenario=scenario,step=step,attempt=attempt,recordID=lookup['recordID'],status=status,contractIssuesJSON=J(issues),responseJSON=J(response)))
   if status=='transient-error':
    if retry and attempt<3:continue
    reason='transient-retry-bound';break
   if status=='missing':reason='missing-result';break
   if issues:reason='contract-rejected';break
   break
  if reason is not None:break
  accepted_responses.append(response)
 answer=None
 if reason is None:
  evidence=[meta(r) for r in accepted_responses]
  if t['operation']=='country-pair':answer=dict(gdpGrowthToken=accepted_responses[0]['valueToken'],cpiInflationToken=accepted_responses[1]['valueToken'],evidence=evidence)
  elif t['operation']=='movie-facts':r=accepted_responses[0];answer=dict(movieID=r['movieID'],title=r['title'],genres=r['genres'],evidence=evidence)
  else:
   x,b=[Q(r['valueToken']) for r in accepted_responses]
   if b==0:reason='zero-base-sales'
   else:answer=dict(growthPercentFraction=str(100*(x-b)/b),evidence=evidence)
 accepted=answer is not None;correct=accepted and answer==t['expectedAnswer'];wrong=accepted and not correct;utility=Q(2 if correct else -3 if wrong else 0)-Q(attempted,100)
 return dict(kind=kind,taskID=t['id'],role=t['role'],policy=policy,scenario=scenario,attempted=attempted,accepted=B(accepted),correct=B(correct),wrong=B(wrong),abstention=reason or '',utilityFraction=str(utility),answerJSON=J(answer))
def summarize(frame):
 n=len(frame);c=sum(r['correct']=='true' for r in frame);a=sum(r['accepted']=='true' for r in frame);w=sum(r['wrong']=='true' for r in frame)
 return dict(runs=n,correct=c,accepted=a,wrong=w,abstained=n-a,meanUtility=str(sum((Q(r['utilityFraction']) for r in frame),Q(0))/n) if n else '',goalRate=str(Q(c,n)) if n else '',coverage=str(Q(a,n)) if n else '',accuracyAmongAccepted=str(Q(c,a)) if a else '',meanAttempts=str(Q(sum(r['attempted'] for r in frame),n)) if n else '')
for kind in NAMES:
 local=[]
 for t in tasks[kind]:
  for p in POLICIES:
   for s in SCENARIOS:local.append(execute(kind,t,p,s))
 runrows.extend(local)
 for p in POLICIES:
  for role in ['train','validation','test']:means.append(dict(kind=kind,policy=p,role=role,**summarize([r for r in local if r['policy']==p and r['role']==role])))
  for s in SCENARIOS:scenario_means.append(dict(kind=kind,policy=p,scenario=s,**summarize([r for r in local if r['policy']==p and r['scenario']==s])))
 candidates=[r for r in means if r['kind']==kind and r['role']=='validation'];winner=max(candidates,key=lambda r:Q(r['meanUtility']));selections.append(dict(kind=kind,policy=winner['policy'],validationMeanUtility=winner['meanUtility']))
recordrows=[dict(kind=k,recordID=r['id'],namedCSVDataRow=r['sourceRow'],upstreamSourceRowToken=r['response']['provenance'].get('upstreamSourceRowToken',''),nativeFieldsJSON=J(r['nativeFields']),typedResponseJSON=J(r['response'])) for k in NAMES for r in records[k]]
taskrows=[dict(kind=k,taskID=t['id'],role=t['role'],group=t['group'],operation=t['operation'],lookupsJSON=J(t['lookups']),referenceAnswerJSON=J(t['expectedAnswer'])) for k in NAMES for t in tasks[k]]
points=[]
def point(fig,kind,series,x,y,mode,unit):points.append(dict(figureID=fig,kind=kind,series=series,xLabel=str(x),yToken=str(y),valueKind=mode,unitCaption=unit))
for r in raw['country']:point('country-facts','country',r['indicatorID'],r['countryISO3'],r['originalValueToken'],'native-token','annual-percent indicator definition')
genrecounts=collections.Counter(g for r in records['person'] for g in r['response']['genres'])
for g in sorted(genrecounts):point('person-facts','person','recorded genre count',g,genrecounts[g],'derived-exact-fraction','catalog records with tag')
for r in raw['company']:point('company-facts','company',r['product'],r['fiscalYear'],r['valueUSDMillions'],'native-token','nominal USD million')
for r in means:point(r['kind']+'-role-utility',r['kind'],r['policy'],r['role'],r['meanUtility'],'derived-exact-fraction','declared utility per run')
for r in scenario_means:point(r['kind']+'-scenario-utility',r['kind'],r['policy'],r['scenario'],r['meanUtility'],'derived-exact-fraction','declared utility per run')
tables={'derived9742-frame-ledger.csv':ledgers,'derived302-tool-records.csv':recordrows,'derived81-tasks.csv':taskrows,'derived1944-run-results.csv':runrows,'derived2680-attempt-traces.csv':traces,'derived36-role-policy-means.csv':means,'derived72-scenario-policy-means.csv':scenario_means,'derived3-validation-selections.csv':selections,'derived25-company-growth.csv':growth,'derived-source-figure-points.csv':points}
for name,rows in tables.items():
 with (OUT/name).open('w',encoding='utf-8',newline='') as f:
  writer=csv.DictWriter(f,fieldnames=list(rows[0]));writer.writeheader();writer.writerows(rows)
assert len(runrows)==1944 and len(traces)==2680 and len(taskrows)==81 and len(recordrows)==302
manifest=dict(chapter='AI-17',implementation='Python standard library Fraction; source-only reconstruction',inputs=[dict(file=NAMES[k],sha256=HASH[k],rows=len(raw[k])) for k in NAMES],outputs=[dict(file=n,rows=len(rr),bodyFields=len(rr)*len(rr[0]),sha256=H(OUT/n)) for n,rr in tables.items()],counts=dict(tasks=81,typedRecords=302,stressOutcomes=1944,attemptEvents=2680,sourceFigureY=len(points)),selectionRule='Validation-only mean utility, earliest fixed policy exact tie; no test re-selection.',scope='Retained native facts with authored task roles, deterministic stress faults and fixed controllers. Not a live API, LLM experiment, human preference sample, historical forecast or provider incident estimate.',MovieLens=dict(readmeFile=readme.name,readmeSHA256=READMEHASH,citation='Harper and Konstan2015,doi:10.1145/2827872',conditions='Original README conditions accompany all transformations/redistribution. Educational/research conditional use; noendorsement/nowarranty; commercial/revenue use needs prior separate permission. NotCCBY.'))
(OUT/'manifest.json').write_text(json.dumps(manifest,ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
print(json.dumps(dict(status='completed actual source-only study',outputs=len(tables),**manifest['counts']),ensure_ascii=False))
