suppressPackageStartupMessages({
  library(readxl)
  library(dplyr)
  library(meta)
  library(netmeta)
})

# Reproducible rerun specification for the family-lock-v1.0 dataset.
# Final literature search date: 2026-10-05.
# Target environment used for the archived native run:
# R 4.3.3; meta 8.5-0; netmeta 3.6-1.

args <- commandArgs(trailingOnly = TRUE)
input_xlsx <- if (length(args) >= 1) args[[1]] else "Caesarean_Catheter_15RCT_Locked_Analysis_Data_2026-10-20.xlsx"
output_dir <- if (length(args) >= 2) args[[2]] else "R_output"
dir.create(output_dir, recursive = TRUE, showWarnings = FALSE)

stopifnot(packageVersion("meta") == "8.5.0")
stopifnot(packageVersion("netmeta") == "3.6.1")

read_locked <- function(sheet) {
  x <- read_excel(input_xlsx, sheet = sheet, skip = 4)
  names(x) <- gsub(" ", "_", names(x), fixed = TRUE)
  x
}

nma_bin <- read_locked("NMA Binary Input") %>% filter(main_analysis == "Yes")
nma_con <- read_locked("NMA Continuous Input") %>% filter(main_analysis == "Yes")
nc_bin <- read_locked("NC Binary Input") %>% filter(main_analysis == "Yes")
nc_con <- read_locked("NC Continuous Input") %>% filter(main_analysis == "Yes")

trt_labels <- c(T0 = "Immediate", T1 = ">30 min–6 h", T2 = ">6–12 h", T3 = ">12–24 h")

fit_nma_binary <- function(dat, ref = "T3", sm = "RR") {
  pw <- pairwise(
    treat = node, event = events, n = n, studlab = study,
    data = dat, sm = sm, incr = 0.5, method.incr = "only0",
    allstudies = TRUE
  )
  netmeta(
    TE, seTE, treat1, treat2, studlab, data = pw,
    sm = sm, reference.group = ref, common = FALSE, random = TRUE,
    method.tau = "REML", details.chkmultiarm = TRUE
  )
}

fit_nma_continuous <- function(dat, ref = "T3") {
  pw <- pairwise(
    treat = node, n = n, mean = mean_hours, sd = sd_hours,
    studlab = study, data = dat, sm = "MD"
  )
  netmeta(
    TE, seTE, treat1, treat2, studlab, data = pw,
    sm = "MD", reference.group = ref, common = FALSE, random = TRUE,
    method.tau = "REML", details.chkmultiarm = TRUE
  )
}

extract_nma <- function(x, outcome, scenario = "Primary", ref = "T3") {
  trts <- x$trts
  te <- x$TE.random[trts, ref]
  se <- x$seTE.random[trts, ref]
  lo <- te - qnorm(0.975) * se
  hi <- te + qnorm(0.975) * se
  is_ratio <- x$sm %in% c("RR", "OR", "HR")
  tibble(
    outcome = outcome, scenario = scenario, treatment = trts,
    treatment_label = unname(trt_labels[trts]), reference = ref,
    measure = x$sm, TE = as.numeric(te), seTE = as.numeric(se),
    lower_TE = as.numeric(lo), upper_TE = as.numeric(hi),
    effect = if (is_ratio) exp(te) else te,
    lower = if (is_ratio) exp(lo) else lo,
    upper = if (is_ratio) exp(hi) else hi,
    tau2 = x$tau^2, tau = x$tau, Q = x$Q, df_Q = x$df.Q,
    p_Q = x$pval.Q, I2_percent = 100 * x$I2,
    n_studies = length(unique(x$studlab))
  )
}

extract_rank <- function(x, outcome, scenario = "Primary") {
  r <- netrank(x, small.values = "good")
  p <- r$Pscore.random
  tibble(
    outcome = outcome, scenario = scenario, treatment = names(p),
    treatment_label = unname(trt_labels[names(p)]), P_score = as.numeric(p)
  ) %>% arrange(desc(P_score)) %>% mutate(rank = row_number())
}

extract_league <- function(x, outcome, scenario = "Primary") {
  trts <- x$trts
  te <- x$TE.random[trts, trts, drop = FALSE]
  se <- x$seTE.random[trts, trts, drop = FALSE]
  ratio <- x$sm %in% c("RR", "OR", "HR")
  bind_rows(lapply(trts, function(col) {
    tibble(
      outcome = outcome, scenario = scenario, row = trts, column = col,
      TE = te[trts, col],
      effect = if (ratio) exp(te[trts, col]) else te[trts, col],
      lower = if (ratio) exp(te[trts, col] - qnorm(.975) * se[trts, col]) else te[trts, col] - qnorm(.975) * se[trts, col],
      upper = if (ratio) exp(te[trts, col] + qnorm(.975) * se[trts, col]) else te[trts, col] + qnorm(.975) * se[trts, col]
    )
  }))
}

safe_side <- function(x, outcome, scenario = "Primary") {
  z <- try(netsplit(x), silent = TRUE)
  if (inherits(z, "try-error")) return(tibble(outcome = outcome, scenario = scenario, note = as.character(z)))
  out <- as.data.frame(z)
  out$outcome <- outcome
  out$scenario <- scenario
  out
}

safe_decomp <- function(x, outcome, scenario = "Primary") {
  z <- decomp.design(x)
  capture.output(print(z), file = file.path(output_dir, paste0("decomp_", gsub("[^A-Za-z0-9]+", "_", outcome), "_", gsub("[^A-Za-z0-9]+", "_", scenario), ".txt")))
  tibble(
    outcome = outcome, scenario = scenario,
    Q_total = x$Q, df_total = x$df.Q, p_total = x$pval.Q,
    Q_inconsistency = z$Q.decomp["Between designs"],
    df_inconsistency = z$df.Q.decomp["Between designs"],
    p_inconsistency = z$pval.Q.decomp["Between designs"]
  )
}

fits <- list(
  "Infection" = fit_nma_binary(filter(nma_bin, outcome == "infection")),
  "Urinary retention" = fit_nma_binary(filter(nma_bin, outcome == "retention")),
  "Dysuria" = fit_nma_binary(filter(nma_bin, outcome == "dysuria")),
  "Time to ambulation" = fit_nma_continuous(filter(nma_con, outcome == "ambulation")),
  "Length of stay" = fit_nma_continuous(filter(nma_con, outcome == "los"))
)

nma_results <- bind_rows(Map(extract_nma, fits, names(fits)))
pscores <- bind_rows(Map(extract_rank, fits, names(fits)))
league <- bind_rows(Map(extract_league, fits, names(fits)))
inconsistency <- bind_rows(Map(safe_decomp, fits, names(fits)))
node_split <- bind_rows(Map(safe_side, fits, names(fits)))

# Prespecified NMA sensitivities.
high_risk_ids <- c("S02", "S03", "S11")
sens_fits <- list(
  "Infection|Exclude high RoB" = fit_nma_binary(filter(nma_bin, outcome == "infection", !Family_ID %in% high_risk_ids)),
  "Urinary retention|Exclude high RoB" = fit_nma_binary(filter(nma_bin, outcome == "retention", !Family_ID %in% high_risk_ids)),
  "Dysuria|Exclude high RoB" = fit_nma_binary(filter(nma_bin, outcome == "dysuria", !Family_ID %in% high_risk_ids)),
  "Time to ambulation|Exclude high RoB" = fit_nma_continuous(filter(nma_con, outcome == "ambulation", !Family_ID %in% high_risk_ids)),
  "Length of stay|Exclude high RoB" = fit_nma_continuous(filter(nma_con, outcome == "los", !Family_ID %in% high_risk_ids))
)

ret_strict <- filter(nma_bin, outcome == "retention") %>%
  mutate(events = ifelse(Family_ID == "S06" & node == "T1", 2,
                  ifelse(Family_ID == "S06" & node %in% c("T2", "T3"), 0, events)))
sens_fits[["Urinary retention|Strict recatheterization"]] <- fit_nma_binary(ret_strict)

sensitivity <- bind_rows(lapply(names(sens_fits), function(key) {
  parts <- strsplit(key, "\\|", fixed = FALSE)[[1]]
  extract_nma(sens_fits[[key]], parts[[1]], parts[[2]])
}))

# Pairwise no-catheterization meta-analysis. Study effects are calculated first,
# then pooled with generic inverse variance REML and Hartung-Knapp confidence intervals.
fit_pair_bin <- function(dat) {
  m0 <- metabin(
    event.e = event_nc, n.e = n_nc, event.c = event_catheter, n.c = n_catheter,
    studlab = study, data = dat, sm = "RR", incr = 0.5,
    method.incr = "only0", allstudies = TRUE, common = FALSE, random = FALSE
  )
  metagen(
    TE = m0$TE, seTE = m0$seTE, studlab = m0$studlab, sm = "RR",
    common = FALSE, random = TRUE, method.tau = "REML", method.random.ci = "HK"
  )
}

fit_pair_cont <- function(dat) {
  m0 <- metacont(
    n.e = n_nc, mean.e = mean_nc_hours, sd.e = sd_nc_hours,
    n.c = n_catheter, mean.c = mean_catheter_hours, sd.c = sd_catheter_hours,
    studlab = study, data = dat, sm = "MD", common = FALSE, random = FALSE
  )
  metagen(
    TE = m0$TE, seTE = m0$seTE, studlab = m0$studlab, sm = "MD",
    common = FALSE, random = TRUE, method.tau = "REML", method.random.ci = "HK"
  )
}

extract_pair <- function(x, outcome, scenario) {
  ratio <- x$sm == "RR"
  tibble(
    outcome = outcome, scenario = scenario, measure = ifelse(ratio, "RR", "MD (hours)"),
    k = x$k, effect = if (ratio) exp(x$TE.random) else x$TE.random,
    lower = if (ratio) exp(x$lower.random) else x$lower.random,
    upper = if (ratio) exp(x$upper.random) else x$upper.random,
    TE = x$TE.random, seTE = x$seTE.random,
    tau2 = x$tau^2, tau = x$tau, Q = x$Q, df_Q = x$df.Q,
    p_Q = x$pval.Q, I2_percent = 100 * x$I2,
    studies = paste(x$studlab, collapse = "; ")
  )
}

pair_fits <- list(
  "NC: Infection|Primary" = fit_pair_bin(filter(nc_bin, outcome == "infection")),
  "NC: Infection|Exclude Nasr 2009" = fit_pair_bin(filter(nc_bin, outcome == "infection", Family_ID != "S10")),
  "NC: Urinary retention|Primary including definition sensitivity" = fit_pair_bin(filter(nc_bin, outcome == "retention")),
  "NC: Urinary retention|Exclude Yassin 2024 definition sensitivity" = fit_pair_bin(filter(nc_bin, outcome == "retention", Family_ID != "S15")),
  "NC: Time to ambulation|Primary" = fit_pair_cont(filter(nc_con, outcome == "ambulation")),
  "NC: Time to ambulation|Exclude high RoB" = fit_pair_cont(filter(nc_con, outcome == "ambulation", Family_ID != "S10")),
  "NC: Length of stay|Primary" = fit_pair_cont(filter(nc_con, outcome == "los")),
  "NC: Length of stay|Exclude high RoB" = fit_pair_cont(filter(nc_con, outcome == "los", Family_ID != "S10"))
)
pairwise_results <- bind_rows(lapply(names(pair_fits), function(key) {
  parts <- strsplit(key, "\\|", fixed = FALSE)[[1]]
  extract_pair(pair_fits[[key]], parts[[1]], parts[[2]])
}))

write.csv(nma_results, file.path(output_dir, "nma_results.csv"), row.names = FALSE)
write.csv(pscores, file.path(output_dir, "pscores.csv"), row.names = FALSE)
write.csv(league, file.path(output_dir, "league_detail.csv"), row.names = FALSE)
write.csv(inconsistency, file.path(output_dir, "inconsistency.csv"), row.names = FALSE)
write.csv(node_split, file.path(output_dir, "node_split.csv"), row.names = FALSE)
write.csv(sensitivity, file.path(output_dir, "sensitivity.csv"), row.names = FALSE)
write.csv(pairwise_results, file.path(output_dir, "pairwise_results.csv"), row.names = FALSE)

for (nm in names(fits)) {
  slug <- gsub("[^A-Za-z0-9]+", "_", nm)
  png(file.path(output_dir, paste0("network_", slug, ".png")), 1800, 1400, res = 220)
  netgraph(fits[[nm]], thickness = "number.of.studies", points = TRUE, number.of.studies = TRUE)
  dev.off()
  png(file.path(output_dir, paste0("forest_", slug, ".png")), 1800, 1400, res = 220)
  forest(fits[[nm]], reference.group = "T3", common = FALSE, random = TRUE)
  dev.off()
}

for (key in names(pair_fits)) {
  slug <- gsub("[^A-Za-z0-9]+", "_", key)
  png(file.path(output_dir, paste0("forest_", slug, ".png")), 1800, 1400, res = 220)
  forest(pair_fits[[key]], common = FALSE, random = TRUE)
  dev.off()
}

capture.output(sessionInfo(), file = file.path(output_dir, "sessionInfo.txt"))
message("Completed netmeta/meta rerun: ", normalizePath(output_dir))
