if(.Platform$OS.type=="windows")invisible(Sys.setlocale("LC_CTYPE","English_United States.utf8"))
# STAT-04: base R actual source records, not numeric case JSON inputs.
chapter<-4
args<-commandArgs(FALSE);filearg<-args[grepl("^--file=",args)]
if(length(filearg))setwd(dirname(normalizePath(sub("^--file=","",filearg[1]),winslash="/")))
workspace<-normalizePath("../..",winslash="/");common<-"\uc2e4\uc81c\ub370\uc774\ud130";data_dir<-"stats04-sources"
read_actual<-function(p)read.csv(p,fileEncoding="UTF-8-BOM",na.strings=c("","NA"),check.names=FALSE,stringsAsFactors=FALSE)
results<-numeric(0);add<-function(k,v){results[k]<<-as.numeric(v)}
near<-function(a,b,tol=1e-10)stopifnot(all(abs(a-b)<=tol*pmax(1,abs(a))))
fraction<-function(s){v<-strsplit(as.character(s),"/",fixed=TRUE)[[1]];as.numeric(v[1])/if(length(v)==2)as.numeric(v[2]) else 1}
W<-read_actual(file.path(common,"worldbank.csv"));W<-W[W$year==2024,];W<-W[order(W$country),];country<-cbind(W$gdp_pc>=30000,W$life_expectancy>=80)
archive<-file.path(workspace,"work/textbooks-2026/raw/penguins.csv");P<-read_actual(if(file.exists(archive))archive else file.path(common,"penguins.csv"));V<-P[!is.na(P$flipper_length_mm),];penguins<-cbind(V$species=="Gentoo",V$flipper_length_mm>=210)
stopifnot(nrow(W)==16,nrow(P)==344,nrow(V)==342)
filename<-if(chapter==4)"actual-apple-category-sales-and-two-selection-weights.csv" else "actual-apple-ten-category-year-cells-and-two-laws.csv"
S<-read_actual(file.path(data_dir,filename));categories<-c("iPhone","Mac","iPad","Wearables, Home and Accessories","Services")
sec<-file.path(workspace,"work/textbook-rewrite-2026/source-audit-math08/apple-2024.html");sales<-list()
if(file.exists(sec)){
 text<-paste(readLines(sec,encoding="UTF-8",warn=FALSE),collapse=" ");extract<-function(pattern,s)regmatches(s,gregexpr(pattern,s,perl=TRUE))[[1]];plain<-function(s)trimws(gsub("\\s+"," ",gsub("&#160;|&nbsp;"," ",gsub("<[^>]+>"," ",s),perl=TRUE)));tables<-extract("(?s)<table\\b.*?</table>",text);cand<-tables[vapply(tables,function(t)grepl("iPhone",plain(t),fixed=TRUE)&&grepl("Services",plain(t),fixed=TRUE),logical(1))];stopifnot(length(cand)>=1);rows<-extract("(?s)<tr\\b.*?</tr>",cand[1])
 for(category in categories){found<-FALSE;for(row in rows){cells<-vapply(extract("(?s)<t[dh]\\b.*?</t[dh]>",row),plain,character(1));if(length(cells)&&sub("\\s*\\([0-9]+\\)$","",cells[1])==category){values<-as.numeric(gsub(",","",cells[grepl("^[0-9]{1,3}(,[0-9]{3})+$",cells)],fixed=TRUE));stopifnot(length(values)==3);sales[[category]]<-setNames(values,c("2024","2023","2022"));found<-TRUE;break}};stopifnot(found)}
 x<-vapply(categories,function(c)sales[[c]][["2023"]],numeric(1));y<-vapply(categories,function(c)sales[[c]][["2024"]],numeric(1))
}else if(chapter==4){x<-S$reported_FY2023_net_sales_million_nominalUSD;y<-S$reported_FY2024_net_sales_million_nominalUSD}else{x<-S$reported_net_sales_million_nominalUSD[S$fiscal_year==2023];y<-S$reported_net_sales_million_nominalUSD[S$fiscal_year==2024]}
stopifnot(sum(x)==383285,sum(y)==391035)
cell_order<-rbind(c(TRUE,TRUE),c(TRUE,FALSE),c(FALSE,TRUE),c(FALSE,FALSE))
countcells<-function(A)vapply(seq_len(4),function(i)sum(A[,1]==cell_order[i,1] & A[,2]==cell_order[i,2]),numeric(1))
cc<-countcells(country);pc<-countcells(penguins);stopifnot(identical(unname(cc),c(8,1,0,7)),identical(unname(pc),c(109,14,5,214)))
for(i in 1:4){add(paste0("country_cell",i,"_actual_count"),cc[i]);add(paste0("penguin_cell",i,"_actual_count"),pc[i])}
event_values<-function(A,w){stopifnot(nrow(A)==length(w));near(sum(w),1);pa<-sum(w[A[,1]]);pb<-sum(w[A[,2]]);ab<-sum(w[A[,1]&A[,2]]);c(P_first=pa,P_second=pb,P_intersection=ab,P_union=pa+pb-ab,P_not_first=1-pa,P_not_second=1-pb,P_second_given_first=ab/pa,P_first_given_second=ab/pb,P_first_given_not_second=(pa-ab)/(1-pb),P_second_given_not_first=(pb-ab)/(1-pa))}
expected<-numeric(0);calc<-function(group,key,value){name<-paste0(group,"__",key);expected[name]<<-value;add(name,value)}
if(chapter==4){
 A<-cbind(seq_len(5)<5,y>x);experiments<-list(country_uniform=list(country,rep(1/16,16)),penguin_uniform_valid_flipper=list(penguins,rep(1/342,342)),company_uniform_category=list(A,rep(1/5,5)),company_FY2024_sales_weighted=list(A,y/sum(y)))
 for(group in names(experiments)){e<-experiments[[group]];z<-event_values(e[[1]],e[[2]]);for(key in names(z))calc(group,key,z[[key]])}
 T<-read_actual(file.path(data_dir,"actual-record-contingency-counts-and-assigned-probabilities.csv"));stopifnot(nrow(T)==16)
 for(i in seq_len(nrow(T))){e<-experiments[[T$experiment[i]]];A<-e[[1]];w<-e[[2]];a<-tolower(T$first_event_occurs[i])=="true";b<-tolower(T$second_event_occurs[i])=="true";whichcell<-A[,1]==a&A[,2]==b;stopifnot(sum(whichcell)==T$actual_record_count[i]);near(sum(w[whichcell]),T$assigned_probability_decimal[i])}
 calcfile<-"exact-event-and-conditional-probability-calculations.csv"
}else{
 pa<-9/16;pb<-1/2;ab<-1/2;z<-c(P_A=pa,P_B=pb,P_intersection=ab,marginal_product_under_independence=pa*pb,P_B_given_A=ab/pa,P_A_given_B=ab/pb,independence_gap=ab-pa*pb)
 for(key in names(z))calc("country_uniform_actual_snapshot",key,z[[key]])
 pairs<-expand.grid(i=seq_len(16),j=seq_len(16));distinct<-pairs[pairs$i!=pairs$j,];both<-function(p)mean(country[p$i,2]&country[p$j,2]);second<-function(p)mean(country[p$j,2])
 z<-c(with_replacement_first_B=pb,with_replacement_second_B=second(pairs),with_replacement_both_B=both(pairs),with_replacement_second_B_given_first_B=both(pairs)/pb,without_replacement_first_B=pb,without_replacement_second_B=second(distinct),without_replacement_both_B=both(distinct),without_replacement_second_B_given_first_B=both(distinct)/pb)
 for(key in names(z))calc("country_two_ticket_selection",key,z[[key]])
 prior<-mean(penguins[,1]);a<-sum(penguins[,1]&penguins[,2])/sum(penguins[,1]);b<-sum(!penguins[,1]&penguins[,2])/sum(!penguins[,1]);evidence<-a*prior+b*(1-prior);post<-a*prior/evidence
 z<-c(P_G=prior,P_T_given_G=a,P_T_given_other=b,P_T=evidence,P_G_given_T=post,P_other_given_T=1-post,likelihood_ratio_T=a/b,prior_odds_G=prior/(1-prior),posterior_odds_G_given_T=post/(1-post))
 for(key in names(z))calc("penguin_original_empirical_mixture",key,z[[key]])
 grid<-sort(unique(c(.01,.99,prior,(1:19)/20)));T<-read_actual(file.path(data_dir,"explicit-base-rate-reweighting-scenarios-not-new-observations.csv"));stopifnot(length(grid)==22,nrow(T)==22)
 mapping<-c(prior="prior_G_exact",joint_G_T="joint_G_T_exact",joint_G_notT="joint_G_notT_exact",joint_other_T="joint_other_T_exact",joint_other_notT="joint_other_notT_exact",evidence_T="P_T_exact",posterior_G_given_T="posterior_G_given_T_exact")
 for(i in seq_along(grid)){p<-grid[i];gt<-p*a;gn<-p*(1-a);ot<-(1-p)*b;on<-(1-p)*(1-b);ev<-gt+ot;po<-gt/ev;z<-c(prior=p,joint_G_T=gt,joint_G_notT=gn,joint_other_T=ot,joint_other_notT=on,evidence_T=ev,posterior_G_given_T=po);for(key in names(z)){near(z[[key]],fraction(T[[mapping[[key]]]][i]));add(paste0("penguin_scenario_",sprintf("%02d",i),"_",key),z[[key]])};near(gt+gn+ot+on,1);stopifnot((tolower(T$matches_original_empirical_mixture[i])=="true")==(abs(p-prior)<1e-14))}
 total<-sum(x)+sum(y)
 for(weighted in c(FALSE,TRUE)){label<-if(weighted)"sales_weighted_choice" else "uniform_product_choice";A<-cbind(rep(seq_len(5)==5,2),rep(c(FALSE,TRUE),each=5));w<-if(weighted)c(x,y)/total else rep(1/10,10);v<-event_values(A,w);ps<-v[["P_first"]];py<-v[["P_second"]];joint<-v[["P_intersection"]];z<-c(P_S=ps,P_Y=py,P_S_intersection_Y=joint,P_S_times_P_Y=ps*py,P_S_given_Y=joint/py,P_Y_given_S=joint/ps,P_S_given_notY=(ps-joint)/(1-py),independence_gap=joint-ps*py);for(key in names(z))calc(paste0("company_",label),key,z[[key]])}
 calcfile<-"exact-Bayes-independence-and-repeated-selection-calculations.csv"
}
T<-read_actual(file.path(data_dir,calcfile));stopifnot(nrow(T)==40,length(expected)==40)
for(i in seq_len(nrow(T))){key<-paste0(T$experiment[i],"__",T$calculation[i]);near(expected[[key]],fraction(T$exact_fraction[i]));near(expected[[key]],T$decimal_approximation[i])}
write.csv(data.frame(metric=names(results),value=unname(results)),"stat04-r-results.csv",row.names=FALSE)
cat("STAT-04:",length(results),"numeric metrics independently recomputed with base R.\n")
