# AI12 byte language models; base R only, no engine or expected-model outputs.
# Rscript ai12-reproduce.R [source-directory] [output-directory]
# Exact counts/small fractions and integer-prime path products; approximate logs.
# Python recomputes SHA256. Base R reads published source hash fields, checks
# selection against original1000rows, and reconstructs roles from those hashes.
# Source: Daqing Chen(2015), UCI Online Retail, CC BY4.0, doi10.24432/C5BW33.
args <- commandArgs(trailingOnly=TRUE)
script <- sub('^--file=','',commandArgs()[grep('^--file=',commandArgs())][1])
home <- dirname(script) # keep script-relative path; no Unicode normalizePath conversion
src <- if(length(args)>=1) args[1] else file.path(home,'ai12-sources')
out <- if(length(args)>=2) args[2] else file.path(home,'ai12-reproduced-R')
dir.create(out,recursive=TRUE,showWarnings=FALSE)
readsrc <- function(name) read.csv(file.path(src,name),colClasses='character',check.names=FALSE,na.strings=character(),fileEncoding='UTF-8-BOM',strip.white=FALSE)
raw <- readsrc('actual1000-first-retail-worksheet-records.csv')
declared <- readsrc('actual128-selected-retail-text-documents.csv')
stopifnot(nrow(raw)==1000,nrow(declared)==128)
selected <- list()
pick <- function(case,group,indices,limit=NULL){
 seen <- character();local <- list()
 for(i in indices){text <- raw$Description[i];if(!nzchar(trimws(text))||text%in%seen) next
  seen <- c(seen,text);local[[length(local)+1]] <- list(case=case,group=group,i=i)
  if(!is.null(limit)&&length(seen)==limit) break
 }
 if(!is.null(limit)) stopifnot(length(seen)==limit)
 selected <<- c(selected,local)
}
for(country in c('United Kingdom','France','Australia')) pick('country',country,which(raw$Country==country),12)
account <- raw$CustomerID[which(nzchar(raw$CustomerID)&nzchar(trimws(raw$Description)))[1]]
pick('account',account,which(raw$CustomerID==account));pick('company','retained-online-retailer',seq_len(nrow(raw)),72)
stopifnot(length(selected)==128)
docs <- vector('list',128)
for(i in seq_along(selected)){
 s <- selected[[i]];r <- raw[s$i,,drop=FALSE];d <- declared[i,,drop=FALSE];text <- r$Description
 stopifnot(grepl('^[0-9a-f]{64}$',d$textSHA256))
 # First7hex*16+last is exact within binary64 and avoids signed32-bit strtoi overflow.
 rem <- (strtoi(substr(d$textSHA256,1,7),16L)*16+strtoi(substr(d$textSHA256,8,8),16L))%%6
 role <- if(rem<4) 'train' else if(rem==4) 'validation' else 'test'
 dd <- list(case=s$case,id=paste0(s$case,':row',r$worksheetRow),group=s$group,worksheetRow=r$worksheetRow,InvoiceNo=r$InvoiceNo,StockCode=r$StockCode,CustomerID=r$CustomerID,Country=r$Country,sourceText=text,textSHA256=d$textSHA256,UTF8Bytes=length(charToRaw(enc2utf8(text))),unicodeCodePoints=nchar(text,type='chars'),role=role)
 for(k in names(dd)) stopifnot(as.character(dd[[k]])==d[[k]])
 docs[[i]] <- dd
}
V <- 257;EOS <- 256;BOS <- 257
gcd <- function(a,b){while(b!=0){r<-a%%b;a<-b;b<-r};a}
fmt <- function(x) if(is.infinite(x)) if(x<0) '-Infinity' else 'Infinity' else sprintf('%.15g',x)
qlog <- function(n,d) if(n==0) -Inf else if(2*n>d) log1p((n-d)/d) else log(n)-log(d)
factors <- new.env(parent=emptyenv())
factorize <- function(n){
 key <- as.character(n);if(exists(key,factors,inherits=FALSE)) return(get(key,factors))
 original <- n;pp <- numeric();d <- 2
 while(d*d<=n){while(n%%d==0){k<-as.character(d);if(is.na(pp[k])) pp[k]<-0;pp[k]<-pp[k]+1;n<-n/d};d<-if(d==2)3 else d+2}
 if(n>1){k<-as.character(n);if(is.na(pp[k])) pp[k]<-0;pp[k]<-pp[k]+1}
 assign(key,pp,factors);pp
}
decimalProduct <- function(powers,positive=TRUE){
 limbs <- 1
 for(k in names(powers)){
  exponent <- powers[k];if((positive&&exponent<=0)||(!positive&&exponent>=0)) next
  prime <- as.numeric(k)
  for(rep in seq_len(abs(exponent))){carry<-0
   for(j in seq_along(limbs)){value<-limbs[j]*prime+carry;limbs[j]<-value%%10000;carry<-floor(value/10000)}
   while(carry>0){limbs<-c(limbs,carry%%10000);carry<-floor(carry/10000)}
  }
 }
 if(length(limbs)==1) return(as.character(limbs[1]))
 paste0(as.character(limbs[length(limbs)]),paste(sprintf('%04d',as.integer(rev(limbs[-length(limbs)]))),collapse=''))
}
exactPath <- function(nn,dd){
 if(any(nn==0)) return(c('0','1'))
 powers <- numeric()
 for(i in seq_along(nn)) for(sign in c(1,-1)){
  ff <- factorize(if(sign==1)nn[i] else dd[i])
  for(k in names(ff)){if(is.na(powers[k])) powers[k]<-0;powers[k]<-powers[k]+sign*ff[k]}
 }
 c(decimalProduct(powers,TRUE),decimalProduct(powers,FALSE))
}
lineage <- lapply(docs,function(d)c(unlist(d),predictedTokensWithEOS=d$UTF8Bytes+1))
counts <- list();predictionsOut <- list();metricsOut <- list();tokensOut <- list();chosen <- list()
for(case in c('country','account','company')){
 dd <- Filter(function(d)d$case==case,docs);train <- Filter(function(d)d$role=='train',dd)
 bi <- matrix(0,nrow=V+1,ncol=V)
 for(doc in train){bs<-as.integer(charToRaw(enc2utf8(doc$sourceText)));contexts<-c(BOS,bs);targets<-c(bs,EOS)
  for(j in seq_along(targets)) bi[contexts[j]+1,targets[j]+1]<-bi[contexts[j]+1,targets[j]+1]+1
 }
 uni <- colSums(bi);ct <- rowSums(bi);total <- sum(uni)
 for(y in 0:(V-1)) counts[[length(counts)+1]]<-c(case,'unigram','',y,uni[y+1],total)
 for(c0 in 0:V) counts[[length(counts)+1]]<-c(case,'context',c0,'',ct[c0+1],ct[c0+1])
 nonzero<-which(bi>0,arr.ind=TRUE);nonzero<-nonzero[order(nonzero[,1],nonzero[,2]),,drop=FALSE]
 for(j in seq_len(nrow(nonzero))){c0<-nonzero[j,1]-1;y<-nonzero[j,2]-1;counts[[length(counts)+1]]<-c(case,'transition',c0,y,bi[c0+1,y+1],ct[c0+1])}
 candidates <- list()
 for(order in c(1,2)) for(alpha in c('0','1/100','1/2')){
  index<-length(candidates);ab<-switch(alpha,'0'=c(0,1),'1/100'=c(1,100),'1/2'=c(1,2));localPred<-list();details<-list()
  for(doc in dd){
   bs<-as.integer(charToRaw(enc2utf8(doc$sourceText)));contexts<-c(BOS,bs);targets<-c(bs,EOS);nn<-numeric(length(targets));den<-nn;losses<-nn
   for(j in seq_along(targets)){
    c0<-contexts[j];y<-targets[j];n<-if(order==1)total else ct[c0+1];k<-if(order==1)uni[y+1] else bi[c0+1,y+1]
    if(n==0&&ab[1]==0){num<-1;dm<-V;state<-'unidentified-zero-count-context-uniform-MLE-completion'}else{
     num<-k*ab[2]+ab[1];dm<-n*ab[2]+V*ab[1];gg<-gcd(num,dm);num<-num/gg;dm<-dm/gg
     state<-if(n==0)'prior-only-additive-smoothing' else if(ab[1]==0)'observed-context-unsmoothed-MLE' else 'observed-context-additive-smoothing'
    }
    nn[j]<-num;den[j]<-dm;lp<-qlog(num,dm);losses[j]<- -lp
    details[[length(details)+1]]<-c(case,index,doc$id,doc$role,j-1,c0,y,k,n,alpha,V,num,dm,state,fmt(lp),doc$worksheetRow)
   }
   path<-exactPath(nn,den);loss<-sum(losses);mean<-loss/length(targets);ppl<-exp(mean)
   localPred[[length(localPred)+1]]<-list(role=doc$role,n=length(targets),loss=loss)
   predictionsOut[[length(predictionsOut)+1]]<-c(case,index,order,alpha,doc$id,doc$role,length(targets),path,fmt(loss),fmt(mean),fmt(ppl),if(is.infinite(loss))'positiveInfinity' else 'finite',doc$worksheetRow,doc$textSHA256,doc$sourceText)
  }
  mm<-list()
  for(role in c('train','validation','test')){pp<-Filter(function(p)p$role==role,localPred);N<-sum(vapply(pp,function(p)p$n,0));loss<-sum(vapply(pp,function(p)p$loss,0));mean<-loss/N;mm[[role]]<-c(length(pp),N,loss,mean,exp(mean))}
  candidates[[length(candidates)+1]]<-list(index=index,order=order,alpha=alpha,metrics=mm,details=details)
 }
 val<-vapply(candidates,function(c)c$metrics$validation[4],0);best<-which.min(val);chosen[[case]]<-best-1;tokensOut<-c(tokensOut,candidates[[best]]$details)
 for(cand in candidates) for(role in c('train','validation','test')){
  mm<-cand$metrics[[role]];metricsOut[[length(metricsOut)+1]]<-c(case,cand$index,cand$order,cand$alpha,role,mm[1],mm[2],fmt(mm[3]),fmt(mm[4]),fmt(mm[5]),if(is.infinite(mm[4]))'positiveInfinity' else 'finite',if(cand$index==best-1)'true' else 'false',V)
 }
}
headers<-list(
 'computed-document-lineage.csv'=c(names(docs[[1]]),'predictedTokensWithEOS'),
 'computed-training-counts.csv'=c('case','type','contextToken','targetToken','count','contextTotal'),
 'computed-all-candidate-documents.csv'=c('case','candidate','order','alpha','document','role','predictedTokens','pathNumerator','pathDenominator','sumNLL','meanNLL','perplexity','lossState','worksheetRow','textSHA256','originalText'),
 'computed-candidate-metrics.csv'=c('case','candidate','order','alpha','role','documents','predictedTokens','sumNLL','meanNLL','perplexity','lossState','selected','uniformBaselinePPL'),
 'computed-selected-conditionals.csv'=c('case','candidate','document','role','position','contextToken','targetToken','targetCount','contextTotal','alpha','V','probNumerator','probDenominator','conditionalState','logProbability','worksheetRow'))
tables<-list(lineage,counts,predictionsOut,metricsOut,tokensOut);names(tables)<-names(headers)
quoted<-function(x)paste0('"',gsub('"','""',as.character(x),fixed=TRUE),'"')
for(name in names(tables)){
 con<-file(file.path(out,name),open='wt',encoding='UTF-8');writeLines(paste(quoted(headers[[name]]),collapse=','),con,useBytes=TRUE)
 for(row in tables[[name]]){stopifnot(length(row)==length(headers[[name]]));writeLines(paste(quoted(row),collapse=','),con,useBytes=TRUE)}
 close(con)
}
summary<-c('AI12 base R standalone PASS',paste('selected',paste(names(chosen),unlist(chosen),sep='=',collapse='; ')),paste('documents',length(docs),'bytes',sum(vapply(docs,function(d)d$UTF8Bytes,0)),'targets',length(tokensOut)),paste('rows',paste(names(tables),vapply(tables,length,0),sep='=',collapse='; ')),'Exact original selection/counts/conditional fractions and prime-factor integer path products; approximate natural logs. SHA role grouping uses published source hash field; Python independently recomputes SHA256.')
writeLines(summary,file.path(out,'summary.txt'),useBytes=TRUE);cat(paste(summary,collapse='\n'),'\n')
