suppressPackageStartupMessages({library(metafor); library(dplyr)})

## Parametrised re-implementation of meta_analysis.R.
##   exclude : study labels removed from the analysis set
##   primary : "FE" (fixed-effect inverse-variance, Cochrane Neonatal convention)
##             or "HKSJ" (random-effects REML with Hartung-Knapp-Sidik-Jonkman)
## Dichotomous outcomes use Mantel-Haenszel fixed-effect RR/RD in both arms of the
## comparison, which is already the Cochrane convention, plus Peto OR for sparse events.

LAB <- c(
  weight_gain_velocity_g_kg_d = "Weight gain velocity (g/kg/day)",
  weight_gain_g_d             = "Weight gain (g/day)",
  weight_z_change             = "Change in weight z-score",
  length_z_change             = "Change in length z-score",
  hc_z_change                 = "Change in head circumference z-score",
  fat_mass_g                  = "Fat mass (g)",
  fat_free_mass_g             = "Fat-free mass (g)",
  percent_body_fat            = "Body fat (%)",
  fat_free_mass_z             = "Fat-free mass z-score",
  fat_mass_z                  = "Fat mass z-score",
  percent_body_fat_z          = "Body fat percentage z-score",
  bayley_cognitive            = "Bayley-III cognitive composite",
  bayley_language             = "Bayley-III language composite",
  bayley_motor                = "Bayley-III motor composite",
  total_brain_volume_ml       = "Total brain volume (mL)",
  cerebellar_volume_ml        = "Cerebellar volume (mL)",
  protein_intake_g_kg_d       = "Protein intake (g/kg/day)",
  energy_intake_kcal_kg_d     = "Energy intake (kcal/kg/day)",
  mortality                   = "All-cause mortality before discharge",
  nec                         = "Necrotising enterocolitis",
  late_onset_sepsis           = "Late-onset sepsis",
  bpd                         = "Bronchopulmonary dysplasia",
  feeding_intolerance         = "Feeding intolerance",
  rop                         = "Retinopathy of prematurity",
  ivh_severe                  = "Intraventricular haemorrhage grade 3-4",
  length_of_stay              = "Length of hospital stay (days)"
)
lab_of <- function(oc) if (!is.null(LAB[[oc]])) LAB[[oc]] else gsub("_", " ", oc)

row_of <- function(oc, measure, m, k, n_int, n_ctrl) {
  if (is.null(m)) return(NULL)
  data.frame(outcome = oc, label = lab_of(oc), measure = measure, k = k,
             n_intervention = n_int, n_control = n_ctrl,
             estimate = as.numeric(m$beta), ci_lb = m$ci.lb, ci_ub = m$ci.ub,
             se = m$se, pval = m$pval,
             tau2 = ifelse(is.null(m$tau2), NA, m$tau2),
             I2 = ifelse(is.null(m$I2), NA, m$I2),
             Q = ifelse(is.null(m$QE), NA, m$QE),
             Q_p = ifelse(is.null(m$QEp), NA, m$QEp),
             stringsAsFactors = FALSE)
}

run_review <- function(exclude = character(0), primary = "HKSJ", outdir = "outputs") {
  ad <- read.csv("outputs/analysis_dataset.csv", stringsAsFactors = FALSE)
  ad <- ad[ad$analysable == "True" | ad$analysable == TRUE, ]
  ad <- ad[!(ad$study %in% exclude), ]
  dir.create(file.path(outdir, "figs"), showWarnings = FALSE, recursive = TRUE)

  out_rows <- list()
  for (oc in unique(ad$outcome)) {
    d <- ad[ad$outcome == oc, ]; d <- d[order(d$study), ]; k <- nrow(d)
    if (d$type[1] == "continuous") {
      es <- escalc(measure = "MD", m1i = m1, sd1i = sd1, n1i = n1,
                   m2i = m2, sd2i = sd2, n2i = n2, data = d, slab = study)
      m_hk <- tryCatch(rma(yi, vi, data = es, method = "REML", test = "knha"), error = function(e) NULL)
      m_dl <- tryCatch(rma(yi, vi, data = es, method = "DL"), error = function(e) NULL)
      m_fe <- tryCatch(rma(yi, vi, data = es, method = "FE"), error = function(e) NULL)
      if (k == 1) {
        out_rows[[length(out_rows)+1]] <- row_of(oc, "MD (single study)", m_fe, k, sum(d$n1), sum(d$n2))
        next
      }
      pm <- if (primary == "FE") m_fe else m_hk
      plab <- if (primary == "FE") "MD (fixed effect)" else "MD (random, HKSJ)"
      out_rows[[length(out_rows)+1]] <- row_of(oc, plab, pm, k, sum(d$n1), sum(d$n2))
      for (alt in setdiff(c("MD (fixed effect)","MD (random, HKSJ)","MD (random, DL)"), plab)) {
        am <- switch(alt, "MD (fixed effect)" = m_fe, "MD (random, HKSJ)" = m_hk, "MD (random, DL)" = m_dl)
        out_rows[[length(out_rows)+1]] <- row_of(oc, alt, am, k, sum(d$n1), sum(d$n2))
      }
      if (!is.null(pm)) {
        png(file.path(outdir, "figs", sprintf("forest_%s.png", oc)),
            width = 2000, height = 300 + 160*k, res = 220)
        par(mar = c(5, 4, 2, 2))
        sv <- c(es$yi - 1.96*sqrt(es$vi), es$yi + 1.96*sqrt(es$vi), 0); sv <- sv[is.finite(sv)]
        aat <- pretty(range(sv), n = 5); wid <- diff(range(aat))
        ok <- tryCatch({
          forest(pm, xlab = sprintf("Mean difference \u2014 %s", lab_of(oc)),
                 slab = es$study, header = c("Study", "MD [95% CI]"),
                 ilab = data.frame(n = sprintf("%d/%d", d$n1, d$n2)),
                 at = aat, alim = range(aat),
                 xlim = c(min(aat) - 1.5*wid, max(aat) + 1.0*wid),
                 ilab.xpos = min(aat) - 0.85*wid, ilab.lab = "n (I/C)",
                 refline = 0, digits = 2, addpred = (primary != "FE"), cex = 0.85)
          TRUE }, error = function(e) FALSE)
        if (!ok) try(forest(pm, xlab = lab_of(oc), slab = es$study, refline = 0, cex = 0.85), silent = TRUE)
        dev.off()
      }
    } else {
      ok_rr <- sum(d$e1) + sum(d$e2) > 0
      m_rr <- if (ok_rr) tryCatch(rma.mh(measure = "RR", ai = e1, n1i = n1, ci = e2, n2i = n2,
                                         data = d, slab = study), error = function(e) NULL) else NULL
      m_rd <- tryCatch(rma.mh(measure = "RD", ai = e1, n1i = n1, ci = e2, n2i = n2,
                              data = d, slab = study), error = function(e) NULL)
      m_pt <- if (ok_rr) tryCatch(rma.peto(ai = e1, n1i = n1, ci = e2, n2i = n2,
                                           data = d, slab = study), error = function(e) NULL) else NULL
      if (!is.null(m_rr) && !is.finite(as.numeric(m_rr$beta))) m_rr <- NULL
      if (!is.null(m_pt) && !is.finite(as.numeric(m_pt$beta))) m_pt <- NULL
      if (!is.null(m_rr)) out_rows[[length(out_rows)+1]] <- row_of(oc, "RR (Mantel-Haenszel)", m_rr, k, sum(d$n1), sum(d$n2))
      if (!is.null(m_pt)) out_rows[[length(out_rows)+1]] <- row_of(oc, "Peto OR", m_pt, k, sum(d$n1), sum(d$n2))
      if (!is.null(m_rd)) out_rows[[length(out_rows)+1]] <- row_of(oc, "RD (Mantel-Haenszel)", m_rd, k, sum(d$n1), sum(d$n2))
      ratio <- if (!is.null(m_rr)) m_rr else m_pt
      if (k >= 2 && ok_rr && !is.null(ratio)) {
        png(file.path(outdir, "figs", sprintf("forest_%s.png", oc)),
            width = 2000, height = 300 + 160*k, res = 220)
        par(mar = c(5, 4, 2, 2))
        ilb <- data.frame(i = sprintf("%d/%d", d$e1, d$n1), c = sprintf("%d/%d", d$e2, d$n2))
        rlab <- if (!is.null(m_rr)) c("Risk ratio", "RR [95% CI]") else c("Peto odds ratio", "OR [95% CI]")
        try(forest(ratio, atransf = exp, at = log(c(0.05, 0.25, 1, 4, 20)),
                   alim = log(c(0.05, 20)), xlim = c(-17, 8),
                   xlab = sprintf("%s \u2014 %s", rlab[1], lab_of(oc)),
                   header = c("Study", rlab[2]), ilab = ilb, ilab.xpos = c(-11, -7.5),
                   ilab.lab = c("Indiv. n/N", "Std. n/N"), refline = 0, digits = 2, cex = 0.85),
            silent = TRUE)
        dev.off()
      }
    }
  }
  summ <- bind_rows(out_rows)
  is_ratio <- grepl("^RR |^Peto OR", summ$measure)
  summ$estimate_reported <- ifelse(is_ratio, exp(summ$estimate), summ$estimate)
  summ$ci_lb_reported    <- ifelse(is_ratio, exp(summ$ci_lb),    summ$ci_lb)
  summ$ci_ub_reported    <- ifelse(is_ratio, exp(summ$ci_ub),    summ$ci_ub)
  summ$scale <- ifelse(is_ratio, "ratio (back-transformed)", "absolute")
  summ$k_contributing <- sapply(seq_len(nrow(summ)), function(i) {
    d <- ad[ad$outcome == summ$outcome[i], ]
    if (d$type[1] != "continuous" && is_ratio[i]) sum((d$e1 + d$e2) > 0) else summ$k[i] })
  summ$is_primary <- summ$measure %in% c(if (primary == "FE") "MD (fixed effect)" else "MD (random, HKSJ)",
                                         "MD (single study)", "RR (Mantel-Haenszel)")
  summ$analysis_set <- basename(outdir)
  write.csv(summ, file.path(outdir, "meta_results.csv"), row.names = FALSE)

  loo <- list()
  for (oc in unique(summ$outcome[summ$k >= 3 & grepl("^MD", summ$measure)])) {
    d <- ad[ad$outcome == oc, ]
    es <- escalc(measure = "MD", m1i = m1, sd1i = sd1, n1i = n1, m2i = m2, sd2i = sd2, n2i = n2,
                 data = d, slab = study)
    m <- tryCatch(if (primary == "FE") rma(yi, vi, data = es, method = "FE")
                  else rma(yi, vi, data = es, method = "REML", test = "knha"), error = function(e) NULL)
    if (is.null(m)) next
    l <- leave1out(m)
    loo[[length(loo)+1]] <- data.frame(outcome = oc, omitted = es$study, estimate = l$estimate,
                                       ci_lb = l$ci.lb, ci_ub = l$ci.ub, I2 = l$I2, stringsAsFactors = FALSE)
  }
  if (length(loo)) write.csv(bind_rows(loo), file.path(outdir, "leave_one_out.csv"), row.names = FALSE)
  list(summ = summ, ad = ad)
}
