args <- commandArgs(trailingOnly = TRUE)
root <- if (length(args)) args[[1]] else "."
read <- function(file) read.csv(file.path(root, file), check.names = FALSE, stringsAsFactors = FALSE)
record <- function(analysis, group, label, value, unit, period, source_url) {
  data.frame(analysis, group, label, value, unit, period, source_url)
}

spending <- read("oecd-spending.csv")
outcome <- read("oecd-outcomes.csv")
population <- read("us-population.csv")$population[[1]]
oecd <- "https://www.oecd.org/en/publications/health-at-a-glance-2025_8f9e3f98-en.html"
peer <- spending[spending$europe == 1, ]
us <- spending$ppp_usd[spending$country == "United States"]
gap <- us - mean(peer$ppp_usd)
ill <- outcome[outcome$country %in% peer$country, ]
us_health <- outcome[outcome$country == "United States", ]
stopifnot(nrow(peer) == 29, length(us) == 1)
metrics <- read("recorded-values.csv")
health <- rbind(
  record("health", "Health spending per person", c("United States", "European average"),
         c(us, mean(peer$ppp_usd)), "PPP-adjusted USD", c("2024 or closest year", "29 countries"), oecd),
  record("health", "Life expectancy", c("United States", "European average"),
         c(us_health$life_years, mean(ill$life_years, na.rm = TRUE)), "years",
         c("2023 or closest year", paste(sum(!is.na(ill$life_years)), "countries")), oecd),
  record("health", "Avoidable mortality", c("United States", "European average"),
         c(us_health$avoidable_deaths_per_100k, mean(ill$avoidable_deaths_per_100k, na.rm = TRUE)), "deaths per 100,000",
         c("2023 or closest year", paste(sum(!is.na(ill$avoidable_deaths_per_100k)), "countries")), oecd),
  record("health", "Fixed-benchmark spending gap", c("One year", "Ten years"),
         gap * population / 1e12 * c(1, 10), "PPP-adjusted USD trillions", "Immediate match assumed", oecd)
)
stopifnot(round(gap * population / 1e12, 2) == 3.04)
write.csv(peer[, c("country", "ppp_usd")], file.path(root, "europe-benchmark.csv"), row.names = FALSE)

generics <- read("ftc-generics.csv")
usable <- with(generics, is.finite(commercial_affiliated_nadac_30d_2021) &
  commercial_affiliated_nadac_30d_2021 > 0 & is.finite(commercial_affiliated_reimb_30d_2021))
drugs <- generics[usable, c("drug", "brand_equivalent", "formulation",
                           "commercial_affiliated_nadac_30d_2021", "commercial_affiliated_reimb_30d_2021")]
drugs$markup_percent <- with(drugs, 100 * (commercial_affiliated_reimb_30d_2021 / commercial_affiliated_nadac_30d_2021 - 1))
drugs <- drugs[order(drugs$markup_percent, decreasing = TRUE), ]
ftc <- "https://www.ftc.gov/reports/specialty-generic-drugs-growing-profit-center-vertically-integrated-pharmacy-benefit-managers"
drugs$source_url <- ftc
write.csv(drugs, file.path(root, "ftc-commercial-markups.csv"), row.names = FALSE)
pharmacy <- record("pbm", "Largest markups in available 2021 rows", head(drugs$drug, 6),
                   head(drugs$markup_percent, 6), "% above NADAC", "Commercial affiliated pharmacies", ftc)

dfa <- read("fed-networth-shares.csv")
time <- c("1989:Q3", "2026:Q2")
fed <- "https://www.federalreserve.gov/releases/z1/dataviz/dfa/"
wealth <- do.call(rbind, lapply(time, function(quarter) {
  d <- dfa[dfa$Date == quarter, ]
  record("wealth", quarter, c("Top 1%", "Bottom 50%"),
         c(sum(d[["Net worth"]][d$Category %in% c("TopPt1", "RemainingTop1")]),
           d[["Net worth"]][d$Category == "Bottom50"]), "% of household net worth", quarter, fed)
}))
metrics <- rbind(health, metrics, pharmacy, wealth)
write.csv(metrics, file.path(root, "all-analysis.csv"), row.names = FALSE)
stopifnot(nrow(metrics) > 35)

render <- function(part, id) {
  if (id == "gaza") return(invisible(NULL))
  bands <- split(seq_len(nrow(part)), factor(part$group, levels = unique(part$group)))
  heights <- lengths(bands) * 87 + 100
  height <- sum(heights) + 42
  file <- file.path(root, paste0(id, "-figure.png"))
  png(file, width = 1450, height = height, res = 130, type = "cairo", bg = "#edf3f7")
  par(mar = rep(0, 4), family = "sans", xaxs = "i", yaxs = "i")
  plot.new()
  plot.window(c(0, 1450), c(height, 0))
  heading <- 20
  for (panel in seq_along(bands)) {
    d <- part[bands[[panel]], ]
    maxval <- max(d$value, 1)
    step <- 10 ^ floor(log10(maxval))
    bound <- if (id == "wealth" || d$unit[1] == "years") 100 else ceiling(maxval / step) * step
    rect(20, heading, 1430, heading + heights[panel] - 12, col = "#fffefa", border = "#c4d3dc")
    text(54, heading + 38, d$group[1], adj = c(0, .5), font = 2, cex = 1.42, col = "#172d44")
    text(54, heading + 70, paste0(d$unit[1], "  |  Scale 0 to ", format(bound, big.mark = ",")),
         adj = c(0, .5), cex = 1.04, col = "#40586d")
    for (i in seq_len(nrow(d))) {
      y <- heading + 113 + (i - 1) * 87
      color <- c("#234f75", "#267160")[(i - 1) %% 2 + 1]
      text(54, y, d$label[i], adj = c(0, .5), font = 2, cex = 1.22, col = "#172d44")
      text(1396, y, format(round(d$value[i], 2), big.mark = ",", trim = TRUE),
           adj = c(1, .5), font = 2, cex = 1.22, col = color)
      rect(54, y + 20, 1396, y + 34, col = "#e1edf0", border = NA)
      rect(54, y + 20, 54 + 1342 * d$value[i] / bound, y + 34, col = color, border = NA)
      text(54, y + 53, d$period[i], adj = c(0, .5), cex = .94, col = "#40586d")
    }
    heading <- heading + heights[panel]
  }
  text(54, height - 22, "FARLIGHT NEWS  |  Sources appear in the accompanying CSV.",
       adj = c(0, .5), cex = .94, col = "#40586d")
  invisible(dev.off())
}

for (id in unique(metrics$analysis)) {
  part <- metrics[metrics$analysis == id, ]
  write.csv(part, file.path(root, paste0(id, "-summary.csv")), row.names = FALSE)
  write.table(part, file.path(root, paste0(id, "-display.tsv")), row.names = FALSE, quote = FALSE, sep = "\t")
  render(part, id)
}
