if(.Platform$OS.type=="windows") invisible(Sys.setlocale("LC_CTYPE","English_United States.utf8"))
options(digits=17); here<-getwd(); data<-file.path(here,"econ10-sources"); arch<-file.path(here,"..","..","work","textbook-rewrite-2026","source-audit-econ10")
M<-numeric(); add<-function(k,v){M[k]<<-as.numeric(v)}
read<-function(n)read.csv(file.path(data,n),check.names=FALSE,colClasses="character",fileEncoding="UTF-8-BOM",na.strings=NULL)
frac<-function(s){if(grepl("/",s,fixed=TRUE)){a<-strsplit(s,"/",fixed=TRUE)[[1]];as.numeric(a[1])/as.numeric(a[2])}else as.numeric(s)}
extract<-function(pattern,s)regmatches(s,gregexpr(pattern,s,perl=TRUE))[[1]]
clean<-function(s){s<-gsub("(?is)<[^>]+>"," ",s,perl=TRUE);s<-gsub("&nbsp;|&#160;"," ",s);s<-gsub("\\x{00A0}"," ",s,perl=TRUE);s<-gsub("&amp;","&",s,fixed=TRUE);trimws(gsub("[[:space:]]+"," ",s))}
cells<-function(s)lapply(extract("(?is)<tr\\b[^>]*>.*?</tr>",s),function(r)vapply(extract("(?is)<t[dh]\\b[^>]*>.*?</t[dh]>",r),clean,""))
bp<-file.path(arch,"BTS-domestic-market-share-snapshot.html"); sr<-read("actual-BTS-carrier-RPM-share-labels-and-raw-tokens.csv")
if(file.exists(bp)){
 h<-paste(readLines(bp,warn=FALSE,encoding="UTF-8"),collapse="\n"); pos<-regexpr("Airline Domestic Market Share August 2025 - July 2026",h,fixed=TRUE);stopifnot(pos>0)
 h<-substring(h,pos);h<-substring(h,1,regexpr("</TABLE>",h,fixed=TRUE)+7);rs<-Filter(function(r)length(r)==2&&grepl("%$",r[2]),cells(h));stopifnot(length(rs)==11)
 for(i in seq_along(rs))stopifnot(rs[[i]][1]==sr$carrier_label[i],sub("%$","",rs[[i]][2])==sr$source_share_percent_token[i])
 original<-paste(readLines(bp,warn=FALSE,encoding="UTF-8"),collapse="\n");tok<-extract('var sData = "[^"]+"',original)[1];tok<-sub('var sData = "','',tok,fixed=TRUE);tok<-sub('"$','',tok);rpm<-strsplit(tok,",",fixed=TRUE)[[1]];rpm<-rpm[nzchar(rpm)];stopifnot(identical(rpm,sr$source_RPM_billions_display_token[1:10]))
}
s<-round(as.numeric(sr$source_share_percent_token),1);stopifnot(abs(sum(s)-100)<1e-12)
for(i in seq_along(s)){add(paste0("country_share",i-1),s[i]);if(nzchar(sr$source_RPM_billions_display_token[i]))add(paste0("country_RPMbillions",i-1),frac(sr$source_RPM_billions_display_token[i]))}
cr4<-sum(s[1:4]);known<-sum(s[1:10]^2);other<-s[11]
for(k in c("CR4_percent","known10_squared","Other_display_percent","grouped11_HHI"))add(paste0("country_",k),switch(k,CR4_percent=cr4,known10_squared=known,Other_display_percent=other,grouped11_HHI=known+other^2))
for(m in c(1,2,5,10))add(paste0("country_assumed_m",m,"_HHI"),known+other^2/m)
# Portable actual source rows preserve all eight original XLSX fields. Python
# independently reopens the archived XLSX and checks every selected source cell.
rr<-read("actual17-same-day-same-stock-positive-lines.csv");stopifnot(nrow(rr)==17,all(rr$StockCode=="85123A"),all(substr(rr$source_minute_label,1,10)=="2010-12-01"))
for(i in seq_len(nrow(rr))){v<-c(row=as.numeric(rr$source_row_id[i]),quantity=as.numeric(rr$Quantity[i]),price=as.numeric(rr$UnitPrice[i]),amount=as.numeric(rr$Quantity[i])*as.numeric(rr$UnitPrice[i]));for(k in names(v))add(paste0("person_line",i-1,"_",k),v[k])}
six<-rr[as.numeric(rr$Quantity)==6,,drop=FALSE];add("person_selected_rows",nrow(rr));add("person_missing_account_rows",sum(!nzchar(rr$CustomerID)));add("person_quantity6_rows",nrow(six));add("person_quantity6_available_distinct_accounts",length(unique(six$CustomerID[nzchar(six$CustomerID)])))
prices<-sort(unique(as.numeric(rr$UnitPrice)))
for(i in seq_along(prices)){g<-rr[as.numeric(rr$UnitPrice)==prices[i],,drop=FALSE];v<-c(source_lines=nrow(g),available_account_lines=sum(nzchar(g$CustomerID)),distinct_available_account_codes=length(unique(g$CustomerID[nzchar(g$CustomerID)])),quantity6_lines=sum(as.numeric(g$Quantity)==6));for(k in names(v))add(paste0("person_pricegroup",i-1,"_",k),v[k])}
gap<-2.95-as.numeric("2.5499999999999998");add("person_equal6_pricegap",gap);add("person_equal6_amountgap",6*gap)
ar<-read("actual-Southwest2024-10K-financial-and-traffic-records.csv");cp<-file.path(arch,"Southwest-2024-official10K.html")
if(file.exists(cp)){
 h<-paste(readLines(cp,warn=FALSE,encoding="UTF-8"),collapse="\n");rs<-cells(h)
 for(i in seq_len(nrow(ar))){wanted<-ar$source_row_label[i];group<-ar$metric[i];vv<-ar$source_value_token[ar$metric==group];ok<-FALSE
  for(row in rs){row<-row[nzchar(row)&!(row%in%c("$","%"))];if(length(row)&&tolower(row[1])==tolower(wanted)){x<-gsub(",","",row[-1],fixed=TRUE);x<-x[grepl("^[0-9]+(\\.[0-9]+)?$",x)];if(length(x)==3&&length(vv)<=3&&all(x[seq_along(vv)]==vv))ok<-TRUE}}
  if(!ok)stop(paste("Original row mismatch:",wanted,paste(vv,collapse=",")))
 }
}
lookup<-function(year,key)as.numeric(ar$source_value_token[ar$fiscal_year==as.character(year)&ar$metric==key])
for(i in seq_len(nrow(ar)))add(paste0("company_",ar$fiscal_year[i],"_",ar$metric[i]),as.numeric(ar$source_value_token[i]))
for(year in c(2023,2024)){
 R<-lookup(year,"operating_revenue_million_USD");C<-lookup(year,"operating_expense_million_USD");I<-lookup(year,"operating_income_million_USD");PR<-lookup(year,"passenger_revenue_million_USD");Q<-lookup(year,"revenue_passengers_thousands");RM<-lookup(year,"RPM_millions");AS<-lookup(year,"ASM_millions");stopifnot(R-C==I)
 v<-c(actual_operating_margin_fraction_exact=I/R,derived_passenger_revenue_per_revenue_passenger_USD_exact=1000*PR/Q,reported_average_passenger_fare_USD_exact=lookup(year,"average_passenger_fare_USD"),derived_operating_cost_per_revenue_passenger_USD_exact=1000*C/Q,derived_load_factor_exact=RM/AS)
 for(k in names(v))add(paste0("company_",year,"_",k),v[k])
}
Q0<-lookup(2024,"revenue_passengers_thousands")/1000;P0<-lookup(2024,"passenger_revenue_million_USD")/Q0
for(n in c(1,2,3,5,10)){
 q<-3*n/(2*(n+1));p<-2*P0-P0*q;cost<-P0/2;profit<-Q0*q*(p-cost);cs<-Q0*P0*q*q/2;best<-Q0*P0*9/8
 v<-c(borrowed_quantity_scale_million_passengers_exact=Q0,borrowed_price_scale_USD_per_passenger_exact=P0,assumed_total_quantity_index_exact=q,assumed_total_quantity_million_exact=q*Q0,assumed_price_USD_exact=p,assumed_constant_MC_USD_exact=cost,assumed_industry_operating_profit_million_USD_exact=profit,assumed_consumer_surplus_million_USD_exact=cs,assumed_total_surplus_million_USD_exact=profit+cs,assumed_DWL_million_USD_exact=best-profit-cs)
 for(k in names(v))add(paste0("model_n",n,"_",k),v[k])
}
for(regime in c("uniform","segmented")){
 total<-c(profit=0,CS=0,TS=0)
 for(group in c("A","B")){a<-if(group=="A")200 else 120;p<-if(regime=="uniform")100 else (a+40)/2;q<-a-p;profit<-(p-40)*q;cs<-q*q/2;v<-c(chosen_price_exact=p,assumed_quantity_exact=q,assumed_profit_money_units_exact=profit,assumed_CS_money_units_exact=cs,assumed_total_surplus_money_units_exact=profit+cs);for(k in names(v))add(paste0("pricing_",regime,"_",group,"_",k),v[k]);total<-total+c(profit,cs,profit+cs)}
 for(k in names(total))add(paste0("pricing_",regime,"_total_",k),total[k])
}
write.csv(data.frame(metric=names(M),value=unname(M)),file.path(here,"econ10-r-results.csv"),row.names=FALSE,fileEncoding="UTF-8")
cat("ECON10 R:",length(M),"independent actual/scenario metrics\n")
