suppressPackageStartupMessages({library(metafor); library(dplyr)})
source("meta_analysis_v2.R")   # reuses LAB / lab_of

## Subgroup analysis in the structure used by Fabrizio et al. (Cochrane 2020):
## individualised fortification split by HOW the target is set --
##   Adjustable : fortification driven by the infant's metabolic response (BUN / urea)
##   Targeted   : fortification driven by measured human-milk composition (milk analysis)
##   Both       : protocol combining milk analysis with metabolic feedback (reported, not
##                entered in the two-group test for subgroup differences)
## Each subgroup is pooled against its own standard-fortification control, then the
## between-subgroup difference is tested with the Cochrane Q_between statistic
## (fixed-effect moderator test, 1 df), with the random-effects moderator test alongside.

sg_of <- function(d, g) d[d$subgroup == g, , drop = FALSE]

## Pooling follows the main analysis exactly (meta_analysis_v2.R):
##   continuous  -> inverse-variance mean difference, random effects with
##                  Hartung-Knapp-Sidik-Jonkman (fixed effect when k = 1 or primary = "FE")
##   dichotomous -> Mantel-Haenszel fixed-effect risk ratio.
## The MH estimator is used for dichotomous outcomes because every morbidity outcome here
## is sparse (several trials with zero events in one or both arms). Inverse-variance
## pooling of log RR with a Hartung-Knapp variance is anti-conservative under those
## conditions: the large within-trial variances make the observed dispersion look small,
## and the HK interval collapses far below the inverse-variance interval.
fit_one <- function(d, cont, primary = "HKSJ") {
  if (nrow(d) == 0) return(NULL)
  if (!cont) {
    d <- d[is.finite(d$e1) & is.finite(d$e2) & is.finite(d$n1) & is.finite(d$n2), , drop = FALSE]
    if (nrow(d) == 0 || sum(d$e1, na.rm = TRUE) + sum(d$e2, na.rm = TRUE) == 0) return(NULL)
    m <- tryCatch(rma.mh(measure = "RR", ai = e1, n1i = n1, ci = e2, n2i = n2,
                         data = d, drop00 = TRUE),
                  error = function(e) NULL)
    ## a subgroup with no events at all in the intervention arm gives MH RR = 0 with an
    ## undefined interval; report it as not estimable rather than as a point estimate
    if (!is.null(m) && !(length(m$ci.lb) == 1 && all(is.finite(c(as.numeric(m$beta)[1], m$ci.lb, m$ci.ub)))))
      m <- NULL
    return(m)
  }
  es <- escalc("MD", m1i = m1, sd1i = sd1, n1i = n1,
               m2i = m2, sd2i = sd2, n2i = n2, data = d)
  es <- es[is.finite(es$yi) & is.finite(es$vi) & es$vi > 0, , drop = FALSE]
  if (nrow(es) == 0) return(NULL)
  if (nrow(es) == 1 || primary == "FE")
    tryCatch(rma(yi, vi, data = es, method = "FE"), error = function(e) NULL)
  else
    tryCatch(rma(yi, vi, data = es, method = "REML", test = "knha"),
             error = function(e) tryCatch(rma(yi, vi, data = es, method = "DL"),
                                          error = function(e) NULL))
}

## RevMan-style test for subgroup differences: Q_between built from the two subgroup
## summary estimates and their standard errors under the review's primary model
## (Cochrane Handbook 10.11.3.1), 1 degree of freedom.
q_between <- function(ms) {
  ms <- ms[!vapply(ms, is.null, logical(1))]
  ms <- ms[vapply(ms, function(m) is.finite(as.numeric(m$beta)[1]) && is.finite(m$se[1]) && m$se[1] > 0,
                  logical(1))]
  if (length(ms) < 2) return(c(Q = NA, df = NA, p = NA))
  th <- vapply(ms, function(m) as.numeric(m$beta)[1], numeric(1))
  w  <- vapply(ms, function(m) 1 / m$se[1]^2, numeric(1))
  Q  <- sum(w * (th - sum(w * th) / sum(w))^2)
  c(Q = Q, df = length(ms) - 1, p = pchisq(Q, length(ms) - 1, lower.tail = FALSE))
}

run_subgroups <- function(infile = "outputs/subgroup_dataset.csv",
                          primary = "HKSJ", outdir = "outputs_subgroup") {
  ad <- read.csv(infile, stringsAsFactors = FALSE)
  ad <- ad[ad$analysable == "True" | ad$analysable == TRUE, ]
  dir.create(file.path(outdir, "figs"), showWarnings = FALSE, recursive = TRUE)

  rows <- list(); inter <- list()
  for (oc in unique(ad$outcome)) {
    d <- ad[ad$outcome == oc, ]
    cont <- d$type[1] == "continuous"
    scale <- if (cont) "MD" else "RR"

    ## --- per-subgroup pooled estimate
    fits <- list()
    for (g in c("Adjustable", "Targeted", "Both")) {
      dg <- sg_of(d, g)
      m <- fit_one(dg, cont, primary)
      fits[[g]] <- m
      if (is.null(m)) {
        if (nrow(dg) > 0)
          rows[[length(rows) + 1]] <- data.frame(
            outcome = oc, label = lab_of(oc), subgroup = g, scale = scale,
            k = nrow(dg), k_contributing = 0,
            n_intervention = sum(dg$n1, na.rm = TRUE), n_control = sum(dg$n2, na.rm = TRUE),
            estimate = NA, ci_lb = NA, ci_ub = NA, pval = NA, I2 = NA, tau2 = NA,
            studies = paste(sort(dg$study), collapse = "; "), stringsAsFactors = FALSE)
        next
      }
      est <- as.numeric(m$beta); lb <- m$ci.lb; ub <- m$ci.ub
      if (!cont) { est <- exp(est); lb <- exp(lb); ub <- exp(ub) }
      rows[[length(rows) + 1]] <- data.frame(
        outcome = oc, label = lab_of(oc), subgroup = g, scale = scale,
        ## same rule as the main analysis: for risk ratios a trial contributes only if it
        ## reported at least one event across the two arms
        k = nrow(dg),
        k_contributing = if (cont) m$k else sum((dg$e1 + dg$e2) > 0, na.rm = TRUE),
        n_intervention = sum(dg$n1, na.rm = TRUE), n_control = sum(dg$n2, na.rm = TRUE),
        estimate = est, ci_lb = lb, ci_ub = ub, pval = m$pval,
        I2 = ifelse(is.null(m$I2), NA, m$I2), tau2 = ifelse(is.null(m$tau2), NA, m$tau2),
        studies = paste(sort(dg$study), collapse = "; "), stringsAsFactors = FALSE)
    }

    ## --- test for subgroup differences: Targeted vs Adjustable
    d2 <- d[d$subgroup %in% c("Adjustable", "Targeted"), ]
    es <- if (cont) escalc("MD", m1i = m1, sd1i = sd1, n1i = n1,
                           m2i = m2, sd2i = sd2, n2i = n2, data = d2)
          else      escalc("RR", ai = e1, n1i = n1, ci = e2, n2i = n2, data = d2)
    es <- es[is.finite(es$yi) & is.finite(es$vi) & es$vi > 0, , drop = FALSE]
    es$subgroup <- factor(es$subgroup, levels = c("Adjustable", "Targeted"))
    ok <- length(unique(es$subgroup[!is.na(es$yi)])) == 2 && nrow(es) >= 3
    if (ok) {
      qb  <- q_between(list(fits[["Adjustable"]], fits[["Targeted"]]))
      mfe <- tryCatch(rma(yi, vi, mods = ~ subgroup, data = es, method = "FE"),
                      error = function(e) NULL)
      mre <- tryCatch(rma(yi, vi, mods = ~ subgroup, data = es, method = "REML"),
                      error = function(e) NULL)
      inter[[length(inter) + 1]] <- data.frame(
        outcome = oc, label = lab_of(oc), scale = scale,
        k_adjustable = sum(es$subgroup == "Adjustable"),
        k_targeted   = sum(es$subgroup == "Targeted"),
        Q_between = qb[["Q"]], df = qb[["df"]], p_subgroup_diff = qb[["p"]],
        p_subgroup_diff_FE = if (is.null(mfe)) NA else mfe$QMp,
        p_subgroup_diff_RE = if (is.null(mre)) NA else mre$QMp,
        stringsAsFactors = FALSE)
    } else {
      inter[[length(inter) + 1]] <- data.frame(
        outcome = oc, label = lab_of(oc), scale = scale,
        k_adjustable = sum(es$subgroup == "Adjustable", na.rm = TRUE),
        k_targeted   = sum(es$subgroup == "Targeted", na.rm = TRUE),
        Q_between = NA, df = NA, p_subgroup_diff = NA,
        p_subgroup_diff_FE = NA, p_subgroup_diff_RE = NA,
        stringsAsFactors = FALSE)
    }
  }

  summ <- bind_rows(rows); it <- bind_rows(inter)
  write.csv(summ, file.path(outdir, "subgroup_results.csv"), row.names = FALSE)
  write.csv(it,   file.path(outdir, "subgroup_difference_tests.csv"), row.names = FALSE)
  list(summ = summ, tests = it, ad = ad)
}

## ---- subgroup forest plot for one outcome (metafor, subgroup-ordered)
plot_subgroup <- function(ad, oc, outdir = "outputs_subgroup", primary = "HKSJ") {
  d <- ad[ad$outcome == oc, ]
  cont <- d$type[1] == "continuous"
  d$subgroup <- factor(d$subgroup, levels = c("Adjustable", "Both", "Targeted"))
  d <- d[order(d$subgroup, d$study), ]
  es <- if (cont) escalc("MD", m1i = m1, sd1i = sd1, n1i = n1,
                         m2i = m2, sd2i = sd2, n2i = n2, data = d)
        else      escalc("RR", ai = e1, n1i = n1, ci = e2, n2i = n2, data = d)
  es <- es[is.finite(es$yi) & is.finite(es$vi) & es$vi > 0, , drop = FALSE]
  if (nrow(es) < 2) return(invisible(NULL))
  gs <- levels(droplevels(es$subgroup))
  ## row layout: leave 2 blank rows between subgroups for the subtotal + header
  rowpos <- c(); cur <- nrow(es) + 3 * length(gs)
  for (g in gs) { for (i in seq_len(sum(es$subgroup == g))) { rowpos <- c(rowpos, cur); cur <- cur - 1 }; cur <- cur - 3 }
  png(file.path(outdir, "figs", paste0("sgforest_", oc, ".png")), width = 2000, height = 180 + 105 * (nrow(es) + 3 * length(gs)), res = 200)
  op <- par(mar = c(4, 4, 2, 2), font = 1)
  forest(es$yi, es$vi, slab = es$study, rows = rowpos,
         ylim = c(-1.5, max(rowpos) + 3),
         atransf = if (cont) I else exp, at = if (cont) NULL else log(c(0.05, 0.25, 1, 4, 20)),
         refline = if (cont) 0 else 0,
         xlab = paste0(lab_of(oc), if (cont) " - mean difference" else " - risk ratio"),
         header = c("Trial", paste0(if (cont) "MD" else "RR", " [95% CI]")),
         cex = 0.85)
  for (g in gs) {
    sel <- es$subgroup == g
    m <- fit_one(es[sel, , drop = FALSE], cont, primary)
    top <- max(rowpos[sel]) + 1.2
    text(par("usr")[1], top, pos = 4, font = 2, cex = 0.85,
         labels = paste0(g, " fortification (k = ", sum(sel), ")"))
    if (!is.null(m)) {
      addpoly(m, row = min(rowpos[sel]) - 1.3, cex = 0.8, font = 2,
              atransf = if (cont) I else exp,
              mlab = paste0("Subtotal: ", g))
    } else {
      text(par("usr")[1], min(rowpos[sel]) - 1.3, pos = 4, font = 2, cex = 0.8,
           labels = paste0("Subtotal: ", g, " - not estimable"))
    }
  }
  ## Overall across subgroups. Where a three-arm trial contributes to two subgroups its
  ## control arm is entered twice, so the overall diamond is labelled as indicative only;
  ## the review's pooled estimate for such outcomes comes from the main analysis set,
  ## where the shared control is combined.
  dup <- any(duplicated(es$study))
  mov <- fit_one(es, cont, primary)
  if (!is.null(mov)) addpoly(mov, row = -1, cex = 0.85, font = 2,
                             atransf = if (cont) I else exp,
                             mlab = if (dup) "Overall (indicative: shared control entered twice)" else "Overall")
  par(op); dev.off()
  invisible(file.path(outdir, "figs", paste0("sgforest_", oc, ".png")))
}
