# ECON18 independent base R arithmetic companion: public CSVs only, binary64 results.
options(digits=17,warn=1); Sys.setenv(TZ="UTC"); try(Sys.setlocale("LC_NUMERIC","C"),silent=TRUE)
a <- commandArgs(trailingOnly=TRUE); base <- if(length(a)>=1) a[1] else "econ18-sources"; out <- if(length(a)>=2) a[2] else "econ18-r-results.csv"
rd <- function(n) read.csv(file.path(base,n),fileEncoding="UTF-8-BOM",colClasses="character",check.names=FALSE,stringsAsFactors=FALSE)
n <- function(x) as.numeric(x); vals <- list(); put <- function(k,v) { vals[[k]] <<- v }
# Preserve small published identity residuals before converting the final quotient.
# The retained selected decimal tokens have safe common-scale integer magnitudes.
sourceResidual <- function(asset,debt,networth) {
  tok <- c(asset,debt,networth)
  stopifnot(all(grepl("^-?[0-9]+(\\.[0-9]+)?$",tok)))
  pieces <- strsplit(sub("^-","",tok),".",fixed=TRUE)
  places <- vapply(pieces,function(p) if(length(p)==2) nchar(p[2]) else 0L,integer(1))
  scale <- max(places)
  integers <- vapply(seq_along(tok),function(j) {
    digits <- paste0(pieces[[j]][1],if(length(pieces[[j]])==2) pieces[[j]][2] else "",paste(rep("0",scale-places[j]),collapse=""))
    v <- as.numeric(digits); if(startsWith(tok[j],"-")) -v else v
  },numeric(1))
  stopifnot(all(is.finite(integers)),sum(abs(integers))<2^53,scale<=15)
  (integers[3]-integers[1]+integers[2])/10^scale
}
annual<-rd("actual-Treasury-FY2023-2024-annual.csv"); month<-rd("actual-Treasury-FY2023-2024-monthly.csv")
for(j in seq_len(nrow(annual))){v<-annual[j,]; yr<-v$fiscalYear; R<-n(v$receipts);D<-n(v$outlays);F<-n(v$reportedDeficit);st<-paste0("budget.",yr,"."); z<-c(receipts=R,outlays=D,reportedDeficit=F,deficitDerived=D-R,deficitResidual=F-D+R);for(k in names(z)) put(paste0(st,k),z[k]);for(k in c("receipts","outlays","reportedDeficit")){s<-sum(n(month[month$fiscalYear==yr,k]));put(paste0(st,"monthlySum.",k),s);put(paste0(st,"sumResidual.",k),s-n(v[[k]]))}}
for(j in seq_len(nrow(month)))put(paste0("budget.monthly.",j,".residual"),n(month$reportedDeficit[j])-n(month$outlays[j])+n(month$receipts[j]))
all<-rd("actual-SCF2022-public-summary-selected-fields-all-implicates.csv");selected<-rd("actual-SCF2022-three-family-implicates.csv")
put("SCF.implicateRows",nrow(all));put("SCF.families",length(unique(all$YY1)));put("SCF.zeroDebtRows",sum(n(all$DEBT)==0));put("SCF.negativeNetWorthRows",sum(n(all$NETWORTH)<0));stopifnot(all(n(all$Y1)==10*n(all$YY1)+n(all$implicate)))
for(j in seq_len(nrow(selected))){v<-selected[j,];st<-paste0("SCF.row",v$sourceRow);A<-n(v$ASSET);D<-n(v$DEBT);N<-n(v$NETWORTH);I<-n(v$INCOME);put(paste0(st,".derivedNetWorth"),A-D);put(paste0(st,".publishedResidual"),sourceResidual(v$ASSET,v$DEBT,v$NETWORTH));if(I>0)put(paste0(st,".debtIncomeRatio"),D/I);for(k in 1:3){s<-c(0,.5,1)[k];tag<-c("zero","half","all")[k];put(paste0(st,".repricing.",tag,".minusOnePP"),-D*s/100);put(paste0(st,".repricing.",tag,".plusOnePP"),D*s/100)}}
for(id in unique(selected$YY1))for(field in c("INCOME","ASSET","DEBT","NETWORTH")){x<-n(selected[selected$YY1==id,field]);put(paste0("SCF.family",id,".",field,".min"),min(x));put(paste0("SCF.family",id,".",field,".max"),max(x))}
total<-rd("actual-Toyota-consolidated-revenue.csv")
for(cl in c("customer","sellingEntity")){r<-rd(if(cl=="customer")"actual-Toyota-external-revenue-by-customer-location.csv" else "actual-Toyota-external-revenue-by-selling-entity-location.csv");for(yr in c("2022","2023","2024")){g<-r[r$fiscalYear==yr,];t<-n(total$revenueMillionJPY[total$fiscalYear==yr]);s<-sum(n(g$revenueMillionJPY));J<-n(g$revenueMillionJPY[g$region=="Japan"]);foreign<-sum(n(g$revenueMillionJPY[g$region!="Japan"]));z<-c(reportedTotal=t,regionalSum=s,roundingResidual=s-t,Japan=J,nonJapan=foreign,JapanShare=J/t,nonJapanShare=foreign/t,halfUSDproxy=foreign/260,tenJPYChange=foreign/26);for(k in names(z))put(paste0("Toyota.",cl,".",yr,".",k),z[k])}}
u<-rd("actual-Toyota-customer-location-vehicle-units.csv");for(yr in c("2022","2023","2024"))put(paste0("Toyota.",yr,".customerUnitRegionSum"),sum(n(u$vehicleThousandUnits[u$fiscalYear==yr])))
u<-rd("actual-Toyota-Japan-units-including-exports.csv");for(j in seq_len(nrow(u)))put(paste0("Toyota.",u$fiscalYear[j],".JapanUnitResidual"),n(u$JapanEntityVehicleThousandUnits[j])-n(u$JapanCustomerVehicleThousandUnits[j])-n(u$JapanExportVehicleThousandUnits[j]))
result<-data.frame(metric=names(vals),value=vapply(vals,function(x)sprintf("%.17g",unname(x)),character(1)));write.csv(result,out,row.names=FALSE,quote=TRUE,fileEncoding="UTF-8");cat("ECON18 base R metrics",nrow(result),"\n")
