#!/usr/bin/env python3
"""AI12 factual byte language models. Python standard library only.
Usage: python ai12-reproduce.py [source-directory] [output-directory]
Inputs: two published source CSVs; no JavaScript engine, fitted model or expected results.
Original text/roles/counts/probabilities are exact; natural logarithms are approximate.
UCI Online Retail, Daqing Chen (2015), CC BY4.0, doi:10.24432/C5BW33.
"""
import csv,hashlib,json,math,pathlib,sys
from collections import Counter
from fractions import Fraction
HERE=pathlib.Path(__file__).resolve().parent
S=pathlib.Path(sys.argv[1]) if len(sys.argv)>1 else HERE/'ai12-sources'
OUT=pathlib.Path(sys.argv[2]) if len(sys.argv)>2 else HERE/'ai12-reproduced-python'
OUT.mkdir(parents=True,exist_ok=True)
def read(name):
 with (S/name).open(encoding='utf-8-sig',newline='') as f:return list(csv.DictReader(f))
raw=read('actual1000-first-retail-worksheet-records.csv');declared=read('actual128-selected-retail-text-documents.csv')
assert len(raw)==1000 and len(declared)==128
docs=[]
def select(case,group,rows,limit=None):
 seen=set()
 for r in rows:
  text=r['Description']
  if not text.strip() or text in seen:continue
  seen.add(text);h=hashlib.sha256(text.encode('utf8')).hexdigest();remainder=int(h[:8],16)%6
  docs.append(dict(case=case,id=case+':row'+r['worksheetRow'],group=group,worksheetRow=r['worksheetRow'],InvoiceNo=r['InvoiceNo'],StockCode=r['StockCode'],CustomerID=r['CustomerID'],Country=r['Country'],sourceText=text,textSHA256=h,UTF8Bytes=len(text.encode('utf8')),unicodeCodePoints=len(text),role='train' if remainder<4 else 'validation' if remainder==4 else 'test'))
  if limit is not None and len(seen)==limit:break
 if limit is not None:assert len(seen)==limit
for country in ['United Kingdom','France','Australia']:select('country',country,[r for r in raw if r['Country']==country],12)
account=next(r['CustomerID'] for r in raw if r['CustomerID'] and r['Description'].strip());select('account',account,[r for r in raw if r['CustomerID']==account]);select('company','retained-online-retailer',raw,72)
for d,r in zip(docs,declared):
 for key,value in d.items():assert str(value)==r[key],(d['id'],key)
V=257;EOS=256;BOS=257
lineage=[list(d.values())+[d['UTF8Bytes']+1] for d in docs];count_rows=[];prediction_rows=[];metric_rows=[];token_rows=[];selected={}
fmt=lambda x:('-Infinity' if x<0 else 'Infinity') if math.isinf(x) else format(x,'.15g')
def logp(q):
 if not q:return -math.inf
 n,d=q.numerator,q.denominator
 return math.log1p((n-d)/d) if 2*n>d else math.log(n)-math.log(d)
for case in ['country','account','company']:
 dd=[d for d in docs if d['case']==case];train=[list(d['sourceText'].encode()) for d in dd if d['role']=='train'];uni=Counter();bi=Counter();ct=Counter()
 for tokens in train:
  for context,target in zip([BOS]+tokens,tokens+[EOS]):uni[target]+=1;bi[context,target]+=1;ct[context]+=1
 total=sum(uni.values())
 for y in range(V):count_rows.append([case,'unigram','',y,uni[y],total])
 for c in range(V+1):count_rows.append([case,'context',c,'',ct[c],ct[c]])
 for (c,y),n in sorted(bi.items()):count_rows.append([case,'transition',c,y,n,ct[c]])
 candidates=[]
 for order in [1,2]:
  for al in ['0','1/100','1/2']:
   index=len(candidates);alpha=Fraction(al)
   def probability(c,y):
    n=total if order==1 else ct[c];k=uni[y] if order==1 else bi[c,y]
    q=Fraction(1,V) if n==0 and alpha==0 else (k+alpha)/(n+V*alpha)
    state='unidentified-zero-count-context-uniform-MLE-completion' if n==0 and alpha==0 else 'prior-only-additive-smoothing' if n==0 else 'observed-context-unsmoothed-MLE' if alpha==0 else 'observed-context-additive-smoothing'
    return q,k,n,state
   predictions=[];details=[]
   for doc in dd:
    bs=list(doc['sourceText'].encode());qs=[];logs=[];rows=[]
    for j,(c,y) in enumerate(zip([BOS]+bs,bs+[EOS])):
     q,k,n,state=probability(c,y);qs.append(q);lp=logp(q);logs.append(-lp)
     rows.append([case,index,doc['id'],doc['role'],j,c,y,k,n,al,V,q.numerator,q.denominator,state,fmt(lp),doc['worksheetRow']])
    path=math.prod(qs);loss=math.inf if any(q==0 for q in qs) else sum(logs);mean=loss/len(qs);ppl=math.exp(mean) if math.isfinite(mean) else math.inf
    predictions.append(dict(doc=doc,n=len(qs),loss=loss,mean=mean,ppl=ppl,path=path));details.extend(rows)
    prediction_rows.append([case,index,order,al,doc['id'],doc['role'],len(qs),path.numerator,path.denominator,fmt(loss),fmt(mean),fmt(ppl),'positiveInfinity' if math.isinf(loss) else 'finite',doc['worksheetRow'],doc['textSHA256'],doc['sourceText']])
   metrics={}
   for role in ['train','validation','test']:
    pp=[p for p in predictions if p['doc']['role']==role];N=sum(p['n'] for p in pp);loss=sum(p['loss'] for p in pp);mean=loss/N;metrics[role]=(len(pp),N,loss,mean,math.exp(mean) if math.isfinite(mean) else math.inf)
   candidates.append(dict(index=index,order=order,alpha=al,metrics=metrics,details=details))
 best=min(range(6),key=lambda i:candidates[i]['metrics']['validation'][3]);selected[case]=best;token_rows.extend(candidates[best]['details'])
 for c in candidates:
  for role,mm in c['metrics'].items():
   D,N,totalLoss,mean,ppl=mm;metric_rows.append([case,c['index'],c['order'],c['alpha'],role,D,N,fmt(totalLoss),fmt(mean),fmt(ppl),'positiveInfinity' if math.isinf(mean) else 'finite','true' if c['index']==best else 'false',V])
tables={
 'computed-document-lineage.csv':(list(docs[0])+['predictedTokensWithEOS'],lineage),
 'computed-training-counts.csv':(['case','type','contextToken','targetToken','count','contextTotal'],count_rows),
 'computed-all-candidate-documents.csv':(['case','candidate','order','alpha','document','role','predictedTokens','pathNumerator','pathDenominator','sumNLL','meanNLL','perplexity','lossState','worksheetRow','textSHA256','originalText'],prediction_rows),
 'computed-candidate-metrics.csv':(['case','candidate','order','alpha','role','documents','predictedTokens','sumNLL','meanNLL','perplexity','lossState','selected','uniformBaselinePPL'],metric_rows),
 'computed-selected-conditionals.csv':(['case','candidate','document','role','position','contextToken','targetToken','targetCount','contextTotal','alpha','V','probNumerator','probDenominator','conditionalState','logProbability','worksheetRow'],token_rows)
}
for name,(headers,rows) in tables.items():
 with (OUT/name).open('w',encoding='utf8',newline='') as f:w=csv.writer(f,quoting=csv.QUOTE_ALL,lineterminator='\n');w.writerow(headers);w.writerows(rows)
summary=dict(chapter='AI-12',runtime='Python standard library',selectedCandidates=selected,documents=len(docs),originalUTF8Bytes=sum(d['UTF8Bytes'] for d in docs),predictionTokensWithEOS=sum(d['UTF8Bytes']+1 for d in docs),outputs={name:dict(rows=len(rows),columns=len(headers),bodyFields=len(rows)*len(headers)) for name,(headers,rows) in tables.items()},scope='Exact source/roles/counts/conditional fractions/path products; approximate natural logs/exp. Country residence/account-not-person/single-retailer overlapping views. No trained BPE or neural model here.')
(OUT/'summary.json').write_text(json.dumps(summary,indent=2)+'\n',encoding='utf8');print(json.dumps(summary))
