# Read only the fields needed from the original AHRQ public-use archives.
read_meps_file <- function(code) {
  connection <- unz(file.path("Sources", "Original files", paste0(code, "dat.zip")),
                    paste0(code, ".dat"), open = "r", encoding = "latin1")
  on.exit(close(connection))
  readLines(connection, warn = FALSE)
}

read_meps_year <- function(year, rx_code, person_code, coverage_pos, payment_fields) {
  person <- read_meps_file(person_code)
  person_id <- substr(person, 11, 20)
  stopifnot(!anyDuplicated(person_id))
  rx <- read_meps_file(rx_code)
  field <- function(start, end) trimws(substr(rx, start, end))
  paid <- function(i) as.numeric(field(payment_fields[i], payment_fields[i + 1L]))
  coverage <- substr(person, coverage_pos, coverage_pos)[match(field(11, 20), person_id)]
  data.frame(year, id = field(11, 20), insurance = coverage,
    ingredient = toupper(field(129, 188)), form = field(208, 257),
    quantity_unit = field(258, 307), strength = field(308, 357),
    unit = field(358, 407), quantity = as.numeric(field(200, 207)),
    days = as.numeric(field(408, 410)),
    self = paid(1L), total = paid(3L), weight = paid(5L))
}

drug_analysis <- function(specs) {
  fills <- rbind(
    read_meps_year(2021, "h229a", "h233", 2408, c(487, 494, 564, 572, 573, 584)),
    read_meps_year(2022, "h239a", "h243", 2235, c(485, 491, 561, 569, 570, 582)),
    read_meps_year(2023, "h248a", "h251", 2090, c(474, 481, 551, 558, 559, 571)),
    read_meps_year(2024, "h254a", "h256", 2805, c(483, 490, 561, 569, 570, 581))
  )
  fills <- subset(fills, insurance %in% 1:3 & weight > 0 & days > 0 &
                  quantity > 0 & self >= 0 & total >= self)
  fills <- split(fills, fills$ingredient)

  # This ratio estimates dollars or product units per 30 supplied days.
  rate <- function(group, values) 30 * sum(group$weight * values) / sum(group$weight * group$days)
  result <- lapply(seq_len(nrow(specs)), function(i) {
    spec <- specs[i, ]
    drug <- fills[[spec$ingredient]]
    if (is.null(drug)) drug <- fills[[1L]][FALSE, ]
    form_codes <- strsplit(spec$forms, "|", fixed = TRUE)[[1L]]
    match_product <- drug$strength == spec$strength & drug$unit == spec$unit & drug$form %in% form_codes
    is_pen <- spec$forms == "SOPN"
    if (is_pen) match_product <- match_product & grepl("^ML$|MILLILITER", drug$quantity_unit, ignore.case = TRUE)
    drug <- drug[match_product, ]
    insured <- subset(drug, insurance %in% c("1", "2"))
    uninsured <- subset(drug, insurance == "3")
    n_in <- length(unique(insured$id))
    n_out <- length(unique(uninsured$id))

    # Hill's historical API estimates inform our simplified production model.
    # Assume excipients weigh as much as active ingredient and use finished-product
    # excipient rate on twice the active mass. Ingredient salt differences are unmodeled.
    model_unit <- 0.01 + (spec$api_usd_per_kg + 2 * 2.63) * spec$active_mg / 1e6
    cost_low <- if (spec$source == "Hill") model_unit else spec$production_low_per_unit
    cost_high <- if (spec$source == "Hill") model_unit else spec$production_high_per_unit
    volume <- if (n_in >= 5L) rate(insured, insured$quantity) else NA_real_
    units <- if (is_pen) volume * spec$units_per_ml else volume

    data.frame(drug = spec$drug, example_use = spec$use,
      strength_and_unit = paste(spec$strength, spec$unit),
      form = if (is_pen) "Prefilled pen" else if (grepl("CAP", spec$forms)) "Solid oral" else "Standard tablet",
      units_per_30d = units, production_low_30d = units * cost_low,
      production_high_30d = units * cost_high,
      insured_total_30d = if (n_in >= 5L) rate(insured, insured$total) else NA_real_,
      insured_patient_30d = if (n_in >= 5L) rate(insured, insured$self) else NA_real_,
      uninsured_total_30d = if (n_out >= 5L) rate(uninsured, uninsured$total) else NA_real_,
      uninsured_patient_30d = if (n_out >= 5L) rate(uninsured, uninsured$self) else NA_real_,
      insured_fills = nrow(insured), uninsured_fills = nrow(uninsured),
      insured_people = n_in, uninsured_people = n_out,
      annual_weighted_30_day_fills = sum(drug$weight * drug$days / 30) / 4,
      cost_source = spec$source)
  })
  result <- do.call(rbind, result)
  monthly <- grep("^(production|insured_total|insured_patient|uninsured_total|uninsured_patient).*_30d$", names(result), value = TRUE)
  for (name in monthly) result[[sub("_30d$", "_12x30d", name)]] <- result[[name]] * 12
  result$insured_total_to_upper_production_ratio <- result$insured_total_30d / result$production_high_30d
  result$uninsured_patient_minus_insured_patient_30d <- result$uninsured_patient_30d - result$insured_patient_30d
  result[order(result$annual_weighted_30_day_fills, decreasing = TRUE), ]
}
