# AI-11 factual attention pooling, using only base R.
# Run beside ai11-sources/, or pass --source-dir and --output-dir.
# This is a fixed scoring rule plus a fitted scalar ridge readout, not
# end-to-end Transformer training. exp(), pooling and ridge are approximate.
options(digits=17)
args <- commandArgs(trailingOnly=TRUE)
script <- sub('^--file=', '', grep('^--file=', commandArgs(), value=TRUE)[1])
home <- dirname(script)
option <- function(key, default) {
  pos <- match(key,args)
  if (is.na(pos)) default else {
    if (pos==length(args)) stop('Missing argument after ',key)
    args[pos+1]
  }
}
source_dir <- option('--source-dir',file.path(home,'ai11-sources'))
output_dir <- option('--output-dir',file.path(home,'ai11-reproduced-R'))
read_source <- function(name) read.csv(file.path(source_dir,name),colClasses='character',check.names=FALSE,na.strings=character(),stringsAsFactors=FALSE)
number <- function(token,divisor) {
  result <- rep(NA_real_,length(token));good <- !(token %in% c('','.'))
  result[good] <- as.numeric(token[good])/divisor
  result
}
wb <- read_source('actual360-four-country-growth-CPI-1980-2024.csv')
nl <- read_source('actual3613-NLS-original52-fields.csv')
ap <- read_source('actual30-Apple-product-sales-FY2019-2024.csv')
wb_value <- function(iso,year,indicator) {
  row <- wb$countryISO3==iso & wb$year==as.character(year) & wb$indicatorID==indicator
  stopifnot(sum(row)==1);wb$valueToken[row]
}
sales <- function(product,year) {
  row <- ap$product==product & ap$fiscalYear==as.character(year)
  stopifnot(sum(row)==1);number(ap$valueUSDMillions[row],100000)
}
samples <- list(country=list(),person=list(),company=list())
add <- function(kind,id,entity,year,role,times,step,features,values,target,multiplier) {
  stopifnot(length(times)>0,all(times<year))
  samples[[kind]][[length(samples[[kind]])+1]] <<- list(id=id,entity=entity,targetTime=year,role=role,times=times,stepYears=step,features=features,values=values,keyObserved=!is.na(values),query=features[nrow(features),],target=target,baseline=tail(values,1),nativeMultiplier=multiplier)
}
for (iso in c('KOR','USA','DEU','JPN')) for (year in 1981:2024) {
  times <- seq(max(1980,year-4),year-1)
  features <- t(vapply(times,function(t)c(number(wb_value(iso,t,'NY.GDP.MKTP.KD.ZG'),20),number(wb_value(iso,t,'FP.CPI.TOTL.ZG'),10)),numeric(2)))
  stopifnot(!anyNA(features))
  role <- if(year<=2014)'train' else if(year<=2019)'validation' else 'test'
  add('country',paste0(iso,':',year),iso,year,role,times,1,features,features[,1],number(wb_value(iso,year,'NY.GDP.MKTP.KD.ZG'),20),20)
}
for (j in 0:47) {
  pos <- 1+floor(j*3612/47);r <- nl[pos,,drop=FALSE]
  role <- if(j%%6<4)'train' else if(j%%6==4)'validation' else 'test'
  for (year in c(1978,1980)) {
    times <- c(1976,1978);times <- times[times<year]
    values <- vapply(times,function(t)number(r[[paste0('wage',substr(t,3,4))]],1000),numeric(1))
    features <- cbind(ifelse(is.na(values),0,values),as.numeric(!is.na(values)))
    add('person',paste0('nls-row:',pos,':target',year),r$id,year,role,times,2,features,values,number(r[[paste0('wage',substr(year,3,4))]],1000),10)
  }
}
for (product in unique(ap$product)) for (year in 2020:2024) {
  times <- seq(max(2019,year-4),year-1)
  values <- vapply(times,function(t)sales(product,t),numeric(1))
  role <- if(year<=2022)'train' else if(year==2023)'validation' else 'test'
  add('company',paste0(product,':FY',year),product,year,role,times,1,cbind(values,1),values,sales(product,year),100000)
}
stopifnot(identical(as.integer(lengths(samples)),c(176L,96L,25L)))
stopifnot(sum(vapply(unlist(samples,recursive=FALSE),function(s)length(s$times),integer(1)))==894)
tables <- list(candidates=list(),predictions=list(),weights=list(),metrics=list())
append_row <- function(key,row) tables[[key]][[length(tables[[key]])+1]] <<- as.data.frame(row,stringsAsFactors=FALSE,check.names=FALSE)
selected_all <- list()
results <- list()
for (kind in names(samples)) {
  ss <- samples[[kind]]
  train_y <- vapply(Filter(function(s)s$role=='train'&&!is.na(s$target),ss),function(s)s$target,numeric(1))
  fallback_mean <- mean(train_y);candidates <- list()
  for (temperature in c(0.5,1,2)) for (recency in c(0,0.25,1)) {
    records <- lapply(ss,function(s) {
      score <- as.vector(s$features %*% s$query)/(sqrt(2)*temperature)-recency*(s$targetTime-s$times)/s$stepYears
      if(any(s$keyObserved)) {
        ex <- rep(0,length(score));ex[s$keyObserved] <- exp(score[s$keyObserved]-max(score[s$keyObserved]))
        weight <- ex/sum(ex);pool <- sum(weight[s$keyObserved]*s$values[s$keyObserved])
      } else {weight <- rep(NA_real_,length(score));pool <- NA_real_}
      c(s,list(scores=score,weights=weight,pooled=pool))
    })
    fit <- Filter(function(r)r$role=='train'&&!is.na(r$target)&&!is.na(r$pooled),records)
    n <- length(fit);x <- vapply(fit,function(r)r$pooled,numeric(1));y <- vapply(fit,function(r)r$target,numeric(1))
    mx <- mean(x);my <- mean(y);denominator <- sum((x-mx)^2)+n*0.01
    slope <- sum((x-mx)*(y-my))/denominator;intercept <- my-slope*mx
    records <- lapply(records,function(r) {
      r$fallbackToTrainingMean <- is.na(r$pooled)
      r$prediction <- if(r$fallbackToTrainingMean)fallback_mean else intercept+slope*r$pooled
      r$squaredError <- if(is.na(r$target))NA_real_ else(r$prediction-r$target)^2
      r$baselineSquaredError <- if(is.na(r$target)||is.na(r$baseline))NA_real_ else(r$baseline-r$target)^2
      r
    })
    metrics <- list()
    for (role in c('train','validation','test')) {
      rr <- Filter(function(r)r$role==role,records);obs <- Filter(function(r)!is.na(r$target),rr);common <- Filter(function(r)!is.na(r$baseline),obs)
      avg <- function(rr,key) if(length(rr))mean(vapply(rr,function(r)r[[key]],numeric(1))) else NA_real_
      metrics[[role]] <- list(samples=length(rr),observedTargets=length(obs),MSE=avg(obs,'squaredError'),fallbackTargets=sum(vapply(obs,function(r)r$fallbackToTrainingMean,logical(1))),commonPersistenceRows=length(common),attentionMSEOnPersistenceFrame=avg(common,'squaredError'),persistenceMSE=avg(common,'baselineSquaredError'),meanOnlyMSE=if(length(obs))mean(vapply(obs,function(r)(r$target-fallback_mean)^2,numeric(1))) else NA_real_)
    }
    candidates[[length(candidates)+1]] <- list(index=length(candidates),temperature=temperature,recencyWeight=recency,ridgePenalty=0.01,trainingMean=fallback_mean,readoutTrainingRows=n,readout=list(intercept=intercept,slope=slope,denominator=denominator,meanPooled=mx,meanTarget=my),predictions=records,metrics=metrics)
  }
  losses <- vapply(candidates,function(c)c$metrics$validation$MSE,numeric(1));selected <- which.min(losses)-1L
  selected_all[[kind]] <- selected;results[[kind]] <- candidates
  for (candidate in candidates) {
    base <- list(case=kind,candidate=candidate$index,temperature=candidate$temperature,recencyWeight=candidate$recencyWeight,selected=candidate$index==selected)
    append_row('candidates',c(base,list(ridgePenalty=candidate$ridgePenalty,trainingMean=candidate$trainingMean,readoutTrainingRows=candidate$readoutTrainingRows),candidate$readout))
    for(role in names(candidate$metrics))append_row('metrics',c(base,list(role=role),candidate$metrics[[role]]))
    for(r in candidate$predictions) {
      append_row('predictions',c(base,list(id=r$id,entity=r$entity,targetTime=r$targetTime,role=r$role,target=r$target,targetObserved=!is.na(r$target),pooled=r$pooled,fallbackToTrainingMean=r$fallbackToTrainingMean,prediction=r$prediction,baseline=r$baseline,squaredError=r$squaredError,baselineSquaredError=r$baselineSquaredError,nativeMultiplier=r$nativeMultiplier,targetNative=r$target*r$nativeMultiplier,predictionNative=r$prediction*r$nativeMultiplier)))
      for(j in seq_along(r$times))append_row('weights',c(base,list(id=r$id,role=r$role,targetTime=r$targetTime,historyIndex=j-1L,historyTime=r$times[j],elapsedStepUnits=(r$targetTime-r$times[j])/r$stepYears,feature0=r$features[j,1],feature1=r$features[j,2],query0=r$query[1],query1=r$query[2],value=r$values[j],keyObserved=r$keyObserved[j],score=r$scores[j],weight=r$weights[j])))
    }
  }
}
dir.create(output_dir,recursive=TRUE,showWarnings=FALSE)
for(key in names(tables)) {
  table <- do.call(rbind,tables[[key]])
  write.csv(table,file.path(output_dir,paste0('derived-ai11-public-',key,'.csv')),row.names=FALSE,na='',fileEncoding='UTF-8')
}
manifest <- paste0('{"chapter":"AI-11","arithmetic":"Base R approximate floating-point attention pooling and train-only ridge","samples":297,"historyRecords":894,"selection":{"country":',selected_all$country,',"person":',selected_all$person,',"company":',selected_all$company,'},"scope":"No full Transformer training, real-time vintage or causal certification"}')
writeLines(manifest,file.path(output_dir,'ai11-public-R-manifest.json'),useBytes=TRUE)
cat(manifest,'\n')
