# Rebuild the international comparison charts from their cited inputs.
# From dist, run: Rscript R/comparisons.R
out <- "comparisons"
reported <- read.csv(file.path(out, "reported-values.csv"), check.names = FALSE)
spending <- read.csv(file.path("01 Healthcare Spending", "Spending per person by country.csv"))
peers <- subset(spending, europe == 1 & is.finite(ppp_usd))
stopifnot(nrow(peers) == 29L)
benchmarks <- rbind(spending[spending$country %in% c(
  "United States", "Switzerland", "Germany", "Netherlands", "France",
  "United Kingdom", "Sweden", "Canada", "Australia", "Japan"
), c("country", "ppp_usd")], data.frame(country = "European average (29)", ppp_usd = mean(peers$ppp_usd)))

monthly <- data.frame(
  chart = "monthly-spending", place = benchmarks$country,
  reported_value = benchmarks$ppp_usd, divisor = 12, conversion = 1,
  unit = "PPP USD per person per month", input_unit = "PPP USD per person per year",
  period = "2024 or nearest year",
  source = "https://doi.org/10.1787/8f9e3f98-en"
)
data <- rbind(reported, monthly)
data$value <- data$reported_value / data$divisor * data$conversion
write.csv(data, file.path(out, "comparison-data.csv"), row.names = FALSE, na = "")

axis_label <- function(x, unit) {
  number <- trimws(formatC(x, format = "f", digits = if (unit == "Percent" || unit == "USD per visit") 1 else 0, big.mark = ","))
  if (unit == "Percent") return(paste0(number, "%"))
  if (grepl("USD", unit, fixed = TRUE)) return(paste0("$", number))
  number
}

chart_titles <- c(
  "insurance-payment-denials" = "Insurance denied payment or paid less than expected",
  "emergency-stroke-treatment" = "Wait for emergency stroke treatment"
)

draw <- function(rows, mobile = FALSE, print_title = NULL) {
  values <- rev(rows$value)
  labels <- rev(rows$place)
  us <- grepl("^United States", labels)
  headline_chart <- rows$chart[1] == "skipped-care"
  labels[labels == "European average (29)"] <- "Europe avg. (29)"
  labels[labels == "England (UK)"] <- "England"
  unit <- rows$unit[1]
  par(mar = c(if (is.null(print_title)) 3 else 4.5, if (mobile) 10.6 else 11,
               if (is.null(print_title)) 1 else 3.6, 1.7), bg = "#ffffff", fg = "#211e16", family = "sans",
      cex = 1.13, las = 1, xaxs = "i")
  full_percent_axis <- unit == "Percent" && rows$chart[1] != "insurance-payment-denials"
  limit <- if (full_percent_axis) 100 else max(values) * 1.22
  marks <- pretty(c(0, limit), n = if (mobile) 4 else 5)
  marks <- marks[marks <= limit]
  locations <- barplot(values, horiz = TRUE, xlim = c(0, limit), axes = FALSE, border = NA,
                       col = ifelse(us, "#9e3328", "#126670"))
  axis(2, at = locations, labels = labels, tick = FALSE, line = 0, cex.axis = .94)
  if (headline_chart) marks <- seq(0, 100, by = 25)
  mark_labels <- if (headline_chart) paste0(marks, "%") else axis_label(marks, unit)
  axis(1, at = marks, labels = mark_labels, cex.axis = .82, col = "#7c776b")
  if (unit == "Minutes") mtext("Minutes", side = 1, line = 2, cex = .82)
  shown <- axis_label(values, unit)
  inside <- values + strwidth(shown, units = "user", cex = .95, font = 2) + limit * .055 > limit
  text(values + ifelse(inside,-1,1) * limit * .018, locations, shown,
       pos = ifelse(inside,2,4), offset = .25, cex = .95, font = 2, col = ifelse(inside,"white","#211e16"))
  if (!is.null(print_title)) {
    period <- if (rows$chart[1] == "emergency-stroke-treatment") {
      "Europe 2023; U.S. benchmark cited 2024"
    } else {
      rows$period[1]
    }
    mtext(print_title, side = 3, line = 1.7, adj = 0, font = 2)
    mtext(paste(period, unit, sep = " | "), side = 3, line = .4, adj = 0, cex = .8)
    mtext("Source URLs and data: usatrumpcare.com/comparisons/comparison-data.csv",
          side = 1, line = 3, adj = 0, cex = .75)
  }
}

args <- commandArgs(trailingOnly = TRUE)
for (key in if (length(args)) args else unique(data$chart)) {
  rows <- subset(data, chart == key)
  rows <- rows[order(rows$value, decreasing = rows$unit[1] != "Minutes"), ]
  h <- 1.5 + .38 * nrow(rows)
  phone_h <- 1.35 + .46 * nrow(rows)
  png(file.path(out,paste0(key,".png")), width = 10, height = h, units = "in", res = 160, type = "cairo")
  draw(rows)
  dev.off()
  png(file.path(out,paste0(key,"-phone.png")), width = 6.3, height = phone_h,
      units = "in", res = 160, type = "cairo", pointsize = 13)
  draw(rows, mobile = TRUE)
  dev.off()
  cairo_pdf(file.path(out,paste0(key,".pdf")), width = 10, height = h + 1)
  title <- if (key %in% names(chart_titles)) chart_titles[[key]] else tools::toTitleCase(gsub("-", " ", key))
  draw(rows, print_title = title)
  dev.off()
}
