# Run from any location with Rscript "/path/to/TRUMP CARE/R/run.R".
args <- commandArgs(FALSE)
script <- sub("^--file=", "", grep("^--file=", args, value = TRUE)[1L])
if (!file.exists(script)) script <- gsub("~+~", " ", script, fixed = TRUE)
setwd(dirname(dirname(normalizePath(script))))
source("R/drugs.R")
source("R/charts.R")
read_input <- function(file, ...) read.csv(file.path("Sources", "Inputs", paste0(file, ".csv")), ...)
save_table <- function(data, folder, title) {
  write.csv(data, file.path(folder, paste0(title, ".csv")), row.names = FALSE, na = "")
}
f <- c("01 Healthcare Spending", "02 Health Outcomes", "03 Insurance Coverage",
       "04 Prescription Drugs", "05 European Spending Scenario", "06 Insurance Market")
navy <- "#132E48"
red <- "#AE3035"
teal <- "#176C72"
muted <- "#516479"
grid <- "#DEE5EC"
paper <- "#F8FAFC"
money <- function(x, digits = 0) paste0("$", formatC(x, format = "f", digits = digits, big.mark = ","))
pct <- function(x, digits = 0) paste0(formatC(x, format = "f", digits = digits), "%")

save_chart <- function(folder, name, draw, height = 7, width = 10.5) {
  path <- file.path(folder, name)
  for (format in c("png", "pdf", "portrait")) {
    mobile <- format == "portrait"
    if (mobile) {
      png(file.path("App", "Charts", paste0(name, ".png")), width = 5.4,
          height = max(6.2, height + .45), units = "in", res = 176, type = "cairo", pointsize = 10)
    } else if (format == "png") {
      png(paste0(path, ".png"), width = width, height = height, units = "in", res = 175, type = "cairo")
    } else {
      cairo_pdf(paste0(path, ".pdf"), width = width, height = height)
    }
    par(family = "sans", bg = paper, fg = navy, col = navy, col.axis = muted,
        col.lab = muted, col.main = navy, las = 1,
        oma = if (mobile) c(3.8, 1, 7.3, 1) else c(2, 1.35, 4.7, 1.35),
        mar = c(3.7, 5, .4, 1), xaxs = "i")
    draw()
    invisible(dev.off())
  }
}

europe_color <- "#667D92"
comparison_colors <- function(labels) {
  ifelse(labels == "United States", red,
    ifelse(startsWith(labels, "European average"), europe_color, teal))
}

world_spend <- read_input("world_health_spending_2023")
world_spend <- world_spend[order(world_spend$ppp_international_dollars_per_person, decreasing = TRUE), ]
world_spend$rank <- rank(-world_spend$ppp_international_dollars_per_person, ties.method = "min")
stopifnot(world_spend$iso3[1L] == "USA", nrow(world_spend) == 192L)
save_table(world_spend, f[1], "Worldwide spending comparison 2023")

spend <- read_input("oecd_spending")
us <- spend$ppp_usd[spend$country == "United States"]
europe <- subset(spend, europe == 1)
eu_spend <- mean(spend$ppp_usd[spend$eu == 1])
europe_spend <- mean(europe$ppp_usd)
population <- read_input("us_population")$population[[1L]]
stopifnot(length(us) == 1L, nrow(europe) == 29L, population == 340110988)
spend$us_minus_country_ppp_usd <- us - spend$ppp_usd
spend$us_to_country_ratio <- us / spend$ppp_usd
save_table(spend, f[1], "Spending per person by country")
peers <- c("Germany", "France", "United Kingdom", "Italy", "Spain",
           "Sweden", "Switzerland", "Netherlands", "Poland")
shown <- subset(spend, country %in% c("United States", peers))
save_chart(f[1], "Spending per person", function() {
  labels <- c(shown$country, "European average")
  row_chart(c(shown$ppp_usd, europe_spend), labels,
    "The U.S. spends 2.5 times the European average",
    "Current health expenditure per person | 2024 or closest available year",
    "Source: OECD Health at a Glance 2025, Fig. 7.4. European average gives equal weight to 29 countries.",
    "Purchasing-power-adjusted U.S. dollars", money, colors = comparison_colors(labels))
}, height = 6.7)

outcomes <- read_input("oecd_outcomes")
save_table(outcomes, f[2], "Comparable health outcomes")
europe_outcomes <- subset(outcomes, country %in% europe$country)
outcome_metrics <- data.frame(
  column = c("life_years", "avoidable_deaths_per_100k", "diabetes_pct", "avoidable_admissions_per_100k", "bad_health_pct"),
  title = c("Life expectancy at birth", "Avoidable deaths before age 75", "Diabetes prevalence among adults",
            "Avoidable hospital admissions", "People reporting poor health"),
  subtitle = c("Years | 2023 or closest available year", "Age-standardized rate | 2023 or closest available year",
               "Age-standardized prevalence | 2022", "Age- and sex-standardized rate | 2023 or closest available year",
               "Age 15 and older reporting bad or very bad health | 2024 or closest available year"),
  units = c("Years", "Deaths per 100,000", "Adults with diabetes", "Admissions per 100,000", "Share of population age 15+"),
  file = c("Life expectancy", "Avoidable mortality", "Diabetes morbidity", "Avoidable admissions", "Self-rated health"))
selected_peers <- c("France", "Germany", "Italy", "Spain", "Sweden", "United Kingdom")
outcome_comparison <- do.call(rbind, lapply(outcome_metrics$column, function(metric) {
  european <- subset(europe_outcomes, is.finite(europe_outcomes[[metric]]))
  data.frame(indicator = metric, european_countries = nrow(european),
    european_mean = mean(european[[metric]]),
    us_value = outcomes[[metric]][outcomes$country == "United States"],
    included_countries = paste(sort(european$country), collapse = " | "))
}))
save_table(outcome_comparison, f[2], "US and European outcome benchmarks")
selected <- subset(outcomes, country %in% c("United States", selected_peers))
for (i in seq_len(nrow(outcome_metrics))) {
  m <- outcome_metrics[i, ]
  summary <- outcome_comparison[i, ]
  formatter <- if (grepl("pct", m$column)) function(x) pct(x, 1) else
    function(x) formatC(x, format = "f", digits = if (m$column == "life_years") 1 else 0, big.mark = ",")
  labels <- c(selected$country, "European average")
  values <- c(selected[[m$column]], summary$european_mean)
  save_chart(f[2], m$file, function() {
    row_chart(values, labels, m$title, m$subtitle,
      sprintf("Source: OECD Health at a Glance 2025, Tables 1.2 and 1.5. European mean: %d countries with data.", summary$european_countries),
      if (m$column == "life_years") "Years (axis starts at 75)" else m$units,
      formatter,
      tick_format = if (grepl("pct", m$column)) pct else function(x) format(x, big.mark = ","),
      colors = comparison_colors(labels), min_value = if (m$column == "life_years") 75 else 0,
      kind = "dot")
  }, height = 5.45)
}

coverage <- outcomes[c("country", "core_coverage_pct", "unmet_need_pct")]
coverage$share_ineligible_for_core_services_pct <- 100 - coverage$core_coverage_pct
save_table(coverage, f[3], "OECD core coverage and unmet need")
states <- read_input("census_acs_2025")
save_table(states, f[3], "State uninsured rates and margins of error")
national <- data.frame(year = c(2024, 2025, 2025), survey = c("CPS ASEC", "CPS ASEC", "ACS"),
  definition = c("Uninsured the entire year", "Uninsured the entire year", "Uninsured at interview"),
  uninsured_pct = c(8.0, 7.9, 8.4), uninsured_millions = c(27.1, 26.7, NA))
save_table(national, f[3], "National uninsured rates")
state_only <- subset(states, !state %in% c("United States", "Puerto Rico"))
state_subset <- state_only[order(state_only$uninsured_pct, decreasing = TRUE), ]
state_subset <- rbind(head(state_subset, 10), tail(state_subset, 10))
save_chart(f[3], "Uninsured rates by state", function() {
  row_chart(state_subset$uninsured_pct, state_subset$state, "Where uninsured rates are highest and lowest",
    "Uninsured at interview | ten highest and ten lowest state and D.C. estimates, 2025",
    "Source: U.S. Census Bureau, 2025 ACS Table HI-12. Whiskers show 90% margins of error.",
    "Percent of civilian noninstitutionalized residents", function(x) pct(x, 1), pct,
    colors = ifelse(state_subset$uninsured_pct > 8.4, red, teal),
    errors = state_subset$moe_90_pct, kind = "dot")
}, height = 8.6)

coverage_europe <- subset(coverage, country %in% europe$country & is.finite(core_coverage_pct))
coverage_full <- sum(coverage_europe$core_coverage_pct == 100)
coverage_mean <- mean(coverage_europe$share_ineligible_for_core_services_pct)
coverage_us <- coverage$share_ineligible_for_core_services_pct[coverage$country == "United States"]
covered <- subset(coverage_europe, share_ineligible_for_core_services_pct > 0)
save_chart(f[3], "Eligibility for core health services", function() {
  labels <- c("United States", "European average", covered$country)
  values <- c(coverage_us, coverage_mean, covered$share_ineligible_for_core_services_pct)
  row_chart(values, labels, "Fewer people lack eligibility in Europe",
    sprintf("Core health services | 2024 or closest year | %d of %d European countries reported full eligibility",
            coverage_full, nrow(coverage_europe)),
    "Source: OECD Health at a Glance 2025, Table 1.4. European mean includes countries reporting full eligibility.",
    "Share of population ineligible for core services",
    function(x) pct(x, 1), pct, colors = comparison_colors(labels))
}, height = 5.8)

targets <- c("29 European countries" = europe_spend, "25 EU members with data" = eu_spend,
             "30 European comparators including Türkiye" = mean(c(europe$ppp_usd, spend$ppp_usd[spend$country == "Türkiye"])))
scenario <- expand.grid(year = 1:10, benchmark = names(targets),
                        transition = c("Immediate match", "Five-year phase-in"), stringsAsFactors = FALSE)
scenario$benchmark_ppp_usd_per_person <- unname(targets[scenario$benchmark])
scenario$us_ppp_usd_per_person <- us
scenario$us_population_fixed <- population
scenario$share_of_gap_closed <- ifelse(scenario$transition == "Immediate match", 1, pmin(scenario$year / 5, 1))
scenario$annual_gap_closed_trillions <- (us - scenario$benchmark_ppp_usd_per_person) * population *
  scenario$share_of_gap_closed / 1e12
scenario$cumulative_gap_closed_trillions <- ave(scenario$annual_gap_closed_trillions,
  scenario$benchmark, scenario$transition, FUN = cumsum)
save_table(scenario, f[5], "One to ten year scenarios")
save_table(subset(scenario, year %in% c(1, 10)), f[5], "Year one and year ten")
save_table(europe, f[5], "European benchmark membership")
base <- subset(scenario, benchmark == names(targets)[1L])
instant <- subset(base, transition == "Immediate match")
phase <- subset(base, transition == "Five-year phase-in")
save_chart(f[5], "Cumulative US spending gap", function() {
  plot(0:10, c(0, instant$cumulative_gap_closed_trillions), type = "n",
    xlim = c(0, 10.5), ylim = c(0, 34), axes = FALSE,
    xlab = "", ylab = "", bty = "n")
  abline(h = seq(0, 30, 5), col = grid)
  axis(1, at = 0:10, col = grid)
  axis(2, at = seq(0, 30, 5), labels = paste0("$", seq(0, 30, 5), "T"), col = grid)
  lines(0:10, c(0, instant$cumulative_gap_closed_trillions), lwd = 3.2, col = red)
  lines(0:10, c(0, phase$cumulative_gap_closed_trillions), lwd = 3.2, col = teal)
  legend("topleft", c("Immediate match", "Five-year phase-in"),
    col = c(red, teal), lwd = 3.2, bty = "n", inset = .035)
  mtext("Years after transition begins", 1, 2.3, adj = 0, cex = .9, col = muted)
  chart_heading("What if U.S. spending matched European levels?",
    "Cumulative difference | fixed 2024 U.S. population and purchasing power | 29-country benchmark",
    "Sources: OECD Health at a Glance 2025, Fig. 7.4 and U.S. Census Bureau Vintage 2024 population estimates.")
})

drugs <- drug_analysis(read_input("drug_specifications", colClasses = c(strength = "character")))
quotes <- read_input("cash_price_examples")
q <- match(drugs$drug, quotes$drug)
drugs$cash_quote_quantity <- quotes$quote_quantity[q]
drugs$cash_quote_unit <- quotes$quote_unit[q]
drugs$retail_quote_pack <- quotes$retail_quote[q]
drugs$discount_cash_quote_pack <- quotes$discount_cash_quote[q]
drugs$cash_quote_source <- quotes$source[q]
drugs$cash_quote_notes <- quotes$quote_notes[q]
drugs$retail_quote_30d <- drugs$retail_quote_pack / drugs$cash_quote_quantity * drugs$units_per_30d
drugs$cash_quote_30d <- drugs$discount_cash_quote_pack / drugs$cash_quote_quantity * drugs$units_per_30d
drugs$retail_quote_12x30d <- drugs$retail_quote_30d * 12
drugs$cash_quote_12x30d <- drugs$cash_quote_30d * 12
complete_drugs <- subset(drugs, !is.na(insured_total_30d) & (!is.na(uninsured_patient_30d) | !is.na(cash_quote_30d)))
stopifnot(nrow(complete_drugs) >= 20L)
save_table(drugs, f[4], "US drug payments and production")
drug_gap <- head(drugs[order(drugs$insured_total_to_upper_production_ratio, decreasing = TRUE, na.last = NA), ], 13)
save_chart(f[4], "Payment compared with production cost", function() {
  row_chart(drug_gap$insured_total_to_upper_production_ratio, drug_gap$drug,
    "Pharmacy payments compared with modeled production cost",
    "Top ratios among selected medicines | weighted payments from all sources per 30 supplied days",
    "Sources: AHRQ MEPS 2021-2024, Barber et al. 2024 eTable 7, and Hill et al. 2018 Appendix Table 2.",
    "Payment divided by high estimate of modeled production cost", function(x) paste0(round(x), "x"),
    colors = ifelse(grepl("^Insulin", drug_gap$drug), red, teal))
}, height = 6.9)
oop <- subset(drugs, !is.na(uninsured_patient_30d) & !is.na(insured_patient_30d))
oop <- head(oop[order(oop$uninsured_patient_30d, decreasing = TRUE), ], 12)
save_chart(f[4], "What patients paid with and without insurance", function() {
  values <- rbind(oop$insured_patient_30d, oop$uninsured_patient_30d)
  row_chart(values, oop$drug, "What patients paid at the pharmacy",
    "Blue: insured at some point in the year | Red: uninsured all year | 2021-2024",
    "Source: AHRQ MEPS. Comparisons describe survey groups and plan types.",
    "Weighted patient payments per 30 supplied days", function(x) money(x, 2), money,
    colors = matrix(rep(c(europe_color, red), ncol(values)), nrow = 2),
    sort_rows = FALSE)
}, height = 7.8)

ftc <- read_input("ftc_specialty_generics")
ftc$commercial_2021_affiliated_markup_usd_30d <- ftc$commercial_affiliated_reimb_30d_2021 - ftc$commercial_affiliated_nadac_30d_2021
ftc$commercial_2021_affiliated_markup_pct <- 100 * ftc$commercial_2021_affiliated_markup_usd_30d / ftc$commercial_affiliated_nadac_30d_2021
ftc$commercial_2021_affiliated_vs_unaffiliated_30d <- ftc$commercial_affiliated_reimb_30d_2021 - ftc$commercial_unaffiliated_reimb_30d_2021
for (name in grep("_30d_2021$", names(ftc), value = TRUE)) {
  ftc[[sub("_30d_2021$", "_12x30d_2021", name)]] <- 12 * ftc[[name]]
}
save_table(ftc, f[4], "FTC specialty generic reimbursement and markups")
specialty <- head(ftc[order(ftc$commercial_2021_affiliated_markup_usd_30d, decreasing = TRUE, na.last = NA), ], 12)
save_chart(f[4], "Specialty generic markups at affiliated pharmacies", function() {
  row_chart(specialty$commercial_2021_affiliated_markup_usd_30d, specialty$drug,
    "Specialty drug payments above acquisition cost",
    "Commercial claims at pharmacies affiliated with the three largest PBMs | 2021",
    "Source: FTC 2025 second interim staff report, Appendix A2.A and A7.A. Acquisition benchmark: NADAC.",
    "Reimbursement less pharmacy acquisition cost per 30 days", money)
}, height = 6.7)

market <- read_input("market_concentration")
vertical <- read_input("vertical_integration")
save_table(market, f[6], "Metro market concentration")
save_table(vertical, f[6], "Insurer and PBM ownership")
save_chart(f[6], "Insurer concentration in metropolitan areas", function() {
  values <- t(as.matrix(market[c("commercial_pct", "medicare_advantage_pct")]))
  row_chart(values, market$indicator, "Most local insurance markets are highly concentrated",
    "Blue: commercial | Red: Medicare Advantage | 2025",
    "Source: AMA Competition in Health Insurance, 2026 Update. Highly concentrated means HHI above 1,800.",
    "Share of 385 metropolitan markets", pct,
    colors = matrix(rep(c(europe_color, red), ncol(values)), nrow = 2),
    sort_rows = FALSE)
}, height = 4.9)
save_chart(f[6], "National PBM market shares", function() {
  row_chart(vertical$pbm_2024_pct, vertical$pbm,
    "Four insurer-affiliated firms held 75% of this PBM market",
    "Rebate negotiation | commercial and Medicare Part D members | 2024",
    "Source: AMA Competition in Pharmacy Benefit Manager Markets, 2026 Update. Shares are rounded.",
    "Market share", pct)
}, height = 4.85)

integration <- read_input("pbm_integration_rates")
save_table(integration, f[6], "Share of drug plan members with integrated insurers")
save_chart(f[6], "Vertical integration of insurers and PBMs", function() {
  row_chart(integration$vertically_integrated_pct, integration$market,
    "Most drug plan members had integrated coverage",
    "Members whose insurer was vertically integrated with a PBM | AMA study, 2024",
    "Source: AMA PBM Market Competition and Vertical Integration, 2026 Update, Exhibit 5.",
    "Share of drug plan members", pct,
    colors = ifelse(integration$market == "Combined commercial and Medicare Part D", red, teal))
}, height = 5.15)

source("R/household.R")
source("R/report.R")
