if(.Platform$OS.type=="windows")invisible(Sys.setlocale("LC_CTYPE","English_United States.utf8"))
# ECON-05: base R actual anchors and explicitly assumed production and costs.
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<-"econ05-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}




fraction<-function(s)vapply(as.character(s),function(v){if(is.na(v)||v=="")return(NA_real_);a<-strsplit(v,"/",fixed=TRUE)[[1]];as.numeric(a[1])/if(length(a)==2)as.numeric(a[2]) else 1},numeric(1),USE.NAMES=FALSE)
rawdir<-file.path(workspace,"work/textbooks-2026/raw");W<-read_actual(file.path(common,"worldbank.csv"));row<-W[W$country=="KOR"&W$year==2024,];stopifnot(nrow(row)==1);GDP<-row$gdp_pc
# Base R has no JSON dependency: independently match the original API record object.
text<-paste(readLines(file.path(rawdir,"worldbank-panel.json"),warn=FALSE),collapse=" ");objects<-regmatches(text,gregexpr('\\{\\s*"indicator".*?"decimal"\\s*:\\s*[0-9]+\\s*\\}',text,perl=TRUE))[[1]];hits<-which(grepl('"countryiso3code"\\s*:\\s*"KOR"',objects,perl=TRUE)&grepl('"date"\\s*:\\s*"2024"',objects,perl=TRUE)&grepl('"id"\\s*:\\s*"NY.GDP.PCAP.KD"',objects,perl=TRUE));stopifnot(length(hits)==1);value<-as.numeric(sub('.*"value"\\s*:\\s*([0-9.eE+-]+).*',"\\1",objects[hits],perl=TRUE));near(value,GDP);S<-read_actual(file.path(data_dir,"actual-Korea2024-GDPpc-level-anchor-and-absent-inputs.csv"));stopifnot(nrow(S)==1,S$country=="KOR",S$indicator=="NY.GDP.PCAP.KD",S$labor_or_capital_input_observed_here=="False",S$total_GDP_or_TFP_observed_here=="False");near(S$source_API_row,hits);near(S$source_year,2024);near(S$actual_GDPpc_constant2015USD_source_decimal,GDP);add("source_country_APIrow",hits);add("source_country_GDPpc2024",GDP)
S<-read_actual(file.path(data_dir,"explicit-eight-two-production-proxy-curves-and-slopes.csv"));stopifnot(nrow(S)==8,all(S$actual_output_observed_at_this_input=="False"),all(S$assumed_input_is_actual_labor_hours=="False"),all(S$model_is_empirical_national_production_function=="False"));for(i in 1:8){s<-i/4;z<-s^2;v<-c(assumed_input_index_exact=z,chosen_exact_square_root_of_index=s,linear_model_output_unit_exact=GDP*z,root_model_output_unit_exact=GDP*sqrt(z),linear_model_marginal_output_per_index_exact=GDP,root_model_marginal_output_per_index_exact=GDP/(2*sqrt(z)));for(k in names(v)){near(fraction(S[[k]][i]),v[[k]]);add(paste0("country_query",i-1,"_",k),v[[k]])}}
con<-unz(file.path(rawdir,"proximity.zip"),"nls.dat");lines<-readLines(con,warn=FALSE);close(con);part<-function(a,b){s<-trimws(substr(lines,a,b));s[s=="."]<-NA_character_;as.numeric(s)};code<-part(1,5);raw<-part(128,132);logs<-part(86,97);S<-read_actual(file.path(data_dir,"actual3613-Card-raw-wages-and-distinct-trimmed-logs.csv"));stopifnot(nrow(S)==3613,length(lines)==3613,identical(is.na(raw),is.na(S$actual1976_raw_hourly_wage_cents)),identical(is.na(logs),is.na(S$actual1976_source_trimmed_log_hourly_wage_cents)),all(S$raw_wage_available==ifelse(is.na(raw),"False","True")),all(S$source_trimmed_log_available==ifelse(is.na(logs),"False","True")));near(S$source_row_id,1:3613);near(S$source_person_code,code);near(S$actual1976_raw_hourly_wage_cents[!is.na(raw)],raw[!is.na(raw)]);near(S$actual1976_source_trimmed_log_hourly_wage_cents[!is.na(logs)],logs[!is.na(logs)]);wage<-raw[1]/100;v<-c(rows=length(lines),rawAvailable=sum(!is.na(raw)),logAvailable=sum(!is.na(logs)),rawWithoutLog=sum(!is.na(raw)&is.na(logs)),firstCode=code[1],firstRawCents=raw[1],firstHourlyUSD=wage);for(k in names(v))add(paste0("source_person_",k),v[[k]])

markup<-paste(readLines(file.path(workspace,"work/textbook-rewrite-2026/source-audit-math08/apple-2024.html"),warn=FALSE,encoding="UTF-8"),collapse=" ");clean<-function(s){s<-gsub("<[^>]+>"," ",s);s<-gsub("&nbsp;|&#160;|&amp;"," ",s);trimws(gsub("[[:space:]]+"," ",s))};plain<-clean(markup);stopifnot(grepl("2024 and 2022 spanned 52 weeks each",plain,fixed=TRUE),grepl("2023 spanned 53 weeks",plain,fixed=TRUE));tables<-regmatches(markup,gregexpr("(?is)<table\\b[^>]*>.*?</table>",markup,perl=TRUE))[[1]];labels<-c("Total net sales","Total cost of sales","Total operating expenses","Operating income");sel<-vapply(tables,function(t)all(vapply(labels,function(l)grepl(l,clean(t),fixed=TRUE),logical(1))),logical(1));stopifnot(sum(sel)==1);rows<-regmatches(tables[sel],gregexpr("(?is)<tr\\b[^>]*>.*?</tr>",tables[sel],perl=TRUE))[[1]];financial<-function(label){hits<-list();for(row in rows){t<-clean(row);if(startsWith(t,label)){t<-gsub("[0-9]+(?:\\.[0-9]+)?[[:space:]]*%"," ",t,perl=TRUE);v<-regmatches(t,gregexpr("\\b[0-9][0-9,]*\\b",t,perl=TRUE))[[1]];if(length(v)==3)hits[[length(hits)+1]]<-as.numeric(gsub(",","",v,fixed=TRUE))}};stopifnot(length(hits)==1);hits[[1]]};ACC<-lapply(labels,financial);names(ACC)<-labels;S<-read_actual(file.path(data_dir,"actual-two-Apple-consolidated-operating-income-identities.csv"));stopifnot(nrow(S)==2,all(S$accounting_identity_holds=="True"),all(S$physical_output_quantity_observed=="False"),all(S$fixed_variable_or_marginal_cost_identified=="False"));for(j in 1:2){i<-c(2,1)[j];y<-c(2023,2024)[j];v<-c(source_fiscal_weeks=c(53,52)[j],actual_revenue_million_USD=ACC[[1]][i],actual_cost_of_sales_million_USD=ACC[[2]][i],actual_operating_expenses_million_USD=ACC[[3]][i],actual_operating_income_million_USD=ACC[[4]][i]);near(ACC[[1]][i]-ACC[[2]][i]-ACC[[3]][i],ACC[[4]][i]);near(S$source_fiscal_year[j],y);for(k in names(v)){near(fraction(S[[k]][j]),v[[k]]);add(paste0("source_company_",y,"_",k),v[[k]])}};revenue<-ACC[[1]][1];C0<-ACC[[2]][1]+ACC[[3]][1]
S<-read_actual(file.path(data_dir,"explicit27-inverse-production-labor-and-cost-profiles.csv"));stopifnot(nrow(S)==27,all(S$production_or_output_observed=="False"),all(S$additional_paid_labor_available_verified=="False"),all(S$source_person_actual_productivity_identified=="False"));j<-0;for(A in c(1,2,4))for(q in 0:8){j<-j+1;L<-(q/A)^2;VC<-wage*L;TC<-10+VC;MC<-2*wage*q/A^2;v<-c(assumed_productivity_output_per_sqrt_hour_exact=A,assumed_output_units_exact=q,conditional_required_labor_hours_exact=L,actual_wage_anchor_1976USD_per_hour_exact=wage,assumed_fixed_cost_1976USD_exact=10,conditional_variable_cost_1976USD_exact=VC,conditional_total_cost_1976USD_exact=TC);if(q>0)v<-c(v,conditional_average_total_cost_1976USD_per_output_exact=TC/q);v<-c(v,conditional_marginal_cost_1976USD_per_output_exact=MC);for(k in names(v)){near(fraction(S[[k]][j]),v[[k]]);add(paste0("person_query",j-1,"_",k),v[[k]])};stopifnot(S$average_cost_defined[j]==if(q>0)"True" else "False");if(q==0)stopifnot(is.na(S$conditional_average_total_cost_1976USD_per_output_exact[j]))}
S<-read_actual(file.path(data_dir,"explicit-six-cost-family-revenue-and-profit-profiles.csv"));T<-read_actual(file.path(data_dir,"explicit-two-constrained-profit-model-maxima.csv"));stopifnot(nrow(S)==6,nrow(T)==2,all(S$curve_matches_disclosed_anchor_at_index1=="True"),all(S$activity_index_is_observed_product_quantity=="False"),all(S$cost_curve_or_profit_counterfactual_identified=="False"),all(T$model_optimum_is_actual_company_recommendation=="False"));b<-100000;lo<-.5;hi<-1.5;j<-0;oi<-0;for(a in c(200000,400000)){for(q in c(lo,1,hi)){j<-j+1;cost<-C0+a*(q-1)+b*(q-1)^2;R<-revenue*q;pi<-R-cost;MC<-a+2*b*(q-1);stopifnot(cost>0);v<-c(assumed_cost_slope_at_anchor_million_USD_per_index_exact=a,assumed_curvature_coefficient_million_USD_per_index_squared_exact=b,assumed_activity_index_exact=q,assumed_revenue_million_USD_exact=R,assumed_total_operating_cost_million_USD_exact=cost,assumed_operating_profit_million_USD_exact=pi,assumed_marginal_cost_million_USD_per_index_exact=MC);for(k in names(v)){near(fraction(S[[k]][j]),v[[k]]);add(paste0("company_query",j-1,"_",k),v[[k]])}};oi<-oi+1;un<-1+(revenue-a)/(2*b);q<-max(lo,min(hi,un));profit<-function(z)revenue*z-C0-a*(z-1)-b*(z-1)^2;derivative<-revenue-a-2*b*(q-1);stopifnot(profit(q)>=profit(lo),profit(q)>=profit(hi));for(t in c(lo,1,hi)){near(profit(t)-profit(q),derivative*(t-q)-b*(t-q)^2);stopifnot(profit(t)<=profit(q)+1e-8)};v<-c(assumed_anchor_cost_slope_exact=a,assumed_lower_activity_bound_exact=lo,assumed_upper_activity_bound_exact=hi,unconstrained_profit_maximizer_exact=un,constrained_profit_maximizer_exact=q,assumed_maximum_profit_million_USD_exact=profit(q),profit_derivative_at_constrained_maximum_exact=derivative);for(k in names(v)){near(fraction(T[[k]][oi]),v[[k]]);add(paste0("company_optimum",oi-1,"_",k),v[[k]])};stopifnot(T$upper_bound_binds[oi]==if(q==hi)"True" else "False")}
write.csv(data.frame(metric=names(results),value=unname(results)),"econ05-r-results.csv",row.names=FALSE);cat("ECON-05:",length(results),"original-source anchors and assumed production/cost metrics independently checked.\n")
