#!/usr/bin/env Rscript
# Parametric bootstrap for the displayed six-trait intercept-only 2/2 fit.
# Run from the repository root. Use a private output directory, then copy
# the aggregate CSVs (never the reference fit) when preparing the tutorial.
#   Rscript --vanilla tutorial/downloads/extensions/bootstrap-red-knots-intercept.R init OUT
#   Rscript --vanilla tutorial/downloads/extensions/bootstrap-red-knots-intercept.R run OUT FIRST LAST
#   Rscript --vanilla tutorial/downloads/extensions/bootstrap-red-knots-intercept.R summarise OUT FIRST LAST
# Start with a pilot in a different output directory from the main campaign.
# Shards can run independently so long as they cover disjoint replicate IDs.

args <- commandArgs(trailingOnly = TRUE)
if (!length(args) || !args[1L] %in% c("init", "run", "summarise") ||
    length(args) != if (args[1L] == "init") 2L else 4L)
  stop("Expected init OUT, run OUT FIRST LAST, or summarise OUT FIRST LAST.")
mode <- args[1L]
root <- normalizePath(getwd(), mustWork = TRUE)
dir.create(args[2L], recursive = TRUE, showWarnings = FALSE)
out <- normalizePath(args[2L], mustWork = TRUE)
dir.create(file.path(out, "draws"), showWarnings = FALSE)
for (pkg in c("digest", "gllvmTMB"))
  if (!requireNamespace(pkg, quietly = TRUE)) stop("Install ", pkg, ".")
if (mode != "init") {
  lim <- suppressWarnings(as.integer(args[3:4]))
  if (anyNA(lim) || lim[1L] < 1L || lim[2L] < lim[1L] ||
      any(as.character(lim) != args[3:4])) stop("Invalid replicate range.")
  replicates <- seq.int(lim[1L], lim[2L])
}

hash_file <- function(path) digest::digest(file = path, algo = "sha256")
write_csv <- function(x, name) {
  target <- file.path(out, name)
  temporary <- tempfile(tmpdir = out)
  utils::write.csv(x, temporary, row.names = FALSE, na = "")
  if (!file.rename(temporary, target)) stop("Cannot write ", target)
}
write_rds <- function(x, target) {
  temporary <- tempfile(tmpdir = dirname(target))
  saveRDS(x, temporary, version = 3)
  if (!file.rename(temporary, target)) stop("Cannot write ", target)
}

traits <- c("mass", "gizzard", "BMR_W", "exploration", "activity", "feeding")
source_path <- file.path(root, "tutorial/data/red-knots-original.csv")
prep_script <- file.path(root, "tutorial/data/prepare-red-knots.R")
point_script <- file.path(root, "tutorial/downloads/extensions/fit_red_knots_intercept_only.R")
this_script <- file.path(root, "tutorial/downloads/extensions/bootstrap-red-knots-intercept.R")
private_reference_path <- file.path(out, "reference-fit.private.rds")
source_hash <- hash_file(source_path)
prep_hash <- hash_file(prep_script)
point_recipe_hash <- hash_file(point_script)
script_hash <- hash_file(this_script)
engine_version <- as.character(utils::packageVersion("gllvmTMB"))
r_version <- as.character(getRversion())

# The same response, formula, likelihood and point-fit recipe as the figure.
form <- value ~ 0 + trait +
  latent(0 + trait | individual, d = 2, unique = TRUE) +
  latent(0 + trait | occasion, d = 2, unique = TRUE)

fit_model <- function(data, optimizer = "nlminb", start_from = NULL) {
  settings <- if (optimizer == "nlminb") {
    list(control = list(iter.max = 1500L, eval.max = 2000L))
  } else {
    list(method = "BFGS", control = list(maxit = 1500L, reltol = 1e-10))
  }
  control <- gllvmTMB::gllvmTMBcontrol(
    optimizer = optimizer, optArgs = settings, n_init = 1L, init_jitter = 0,
    start_method = if (is.null(start_from)) list(method = "indep") else list(),
    start_from = start_from
  )
  gllvmTMB::gllvmTMB(
    form, data = data, trait = "trait", unit = "individual",
    unit_obs = "occasion", family = stats::gaussian(), REML = FALSE,
    control = control
  )
}

matrices <- function(fit) {
  for_level <- function(level) {
    extract <- function(part) {
      m <- as.matrix(gllvmTMB::extract_Sigma(
        fit, level = level, part = part, link_residual = "none"
      )$Sigma)
      if (!setequal(rownames(m), traits) || !setequal(colnames(m), traits))
        stop("Unexpected covariance labels")
      m[traits, traits, drop = FALSE]
    }
    shared <- extract("shared")
    total <- extract("total")
    unique <- total - shared
    for (m in list(shared, total)) {
      if (any(!is.finite(m)) || max(abs(m - t(m))) > 1e-8 ||
          min(eigen(m, symmetric = TRUE, only.values = TRUE)$values) < -1e-8)
        stop("Invalid covariance matrix")
    }
    if (any(diag(total) <= 0) || any(diag(unique) < -1e-8) ||
        max(abs(unique - diag(diag(unique)))) > 1e-8)
      stop("Invalid unique variance")
    list(shared = shared, total = total)
  }
  list(B = for_level("unit"), W = for_level("unit_obs"))
}

targets <- function(m) {
  pairs <- utils::combn(traits, 2L)
  b_cor <- stats::cov2cor(m$B$total)[cbind(pairs[1L, ], pairs[2L, ])]
  w_cor <- stats::cov2cor(m$W$total)[cbind(pairs[1L, ], pairs[2L, ])]
  b_var <- diag(m$B$total)
  w_var <- diag(m$W$total)
  b_comm <- diag(m$B$shared) / b_var
  w_comm <- diag(m$W$shared) / w_var
  rows <- function(quantity, level, trait_1, trait_2, value) {
    data.frame(quantity, level, trait_1, trait_2, value = as.numeric(value))
  }
  z <- rbind(
    rows("correlation", "B", pairs[1L, ], pairs[2L, ], b_cor),
    rows("correlation", "W", pairs[1L, ], pairs[2L, ], w_cor),
    rows("correlation_contrast", "B_minus_W", pairs[1L, ], pairs[2L, ], b_cor - w_cor),
    rows("communality", "B", traits, traits, b_comm),
    rows("communality", "W", traits, traits, w_comm),
    rows("communality_contrast", "B_minus_W", traits, traits, b_comm - w_comm),
    rows("repeatability", "B_over_total", traits, traits, b_var / (b_var + w_var))
  )
  if (any(!is.finite(z$value))) stop("Nonfinite bootstrap target")
  z
}

diagnose <- function(fit) {
  h <- fit$fit_health
  ll <- as.numeric(stats::logLik(fit))
  gradient <- h$max_gradient
  convergence <- h$convergence
  pd <- isTRUE(h$pd_hessian)
  if (length(ll) != 1L || length(gradient) != 1L || length(convergence) != 1L)
    stop("Optimizer diagnostic missing")
  finite <- is.finite(ll) && all(is.finite(fit$opt$par))
  data.frame(logLik = ll, convergence = convergence, pd_hessian = pd,
             max_gradient = gradient, finite = finite,
             qualified = finite && isTRUE(convergence == 0L) && pd &&
               isTRUE(is.finite(gradient) && gradient <= .01))
}

if (mode == "init") {
  if (file.exists(private_reference_path)) stop("Reference already exists. Use a new output directory.")
  # Run the public preparation script in a scratch tree to avoid rewriting
  # existing tutorial artefacts. Its observed cell mask is the bootstrap mask.
  scratch <- tempfile("red-knots-bootstrap-prep-")
  dir.create(file.path(scratch, "tutorial/data"), recursive = TRUE)
  dir.create(file.path(scratch, "tutorial/downloads"))
  stopifnot(file.copy(source_path, file.path(scratch, "tutorial/data")))
  setwd(scratch)
  sys.source(prep_script, envir = new.env(parent = globalenv()))
  prepared <- readRDS("analysis/cache/tutorial-data/red-knots-six-intercept.rds")
  setwd(root)
  unlink(scratch, recursive = TRUE)
  data <- prepared$long
  stopifnot(identical(prepared$traits, traits), !anyNA(data),
            nrow(data) == 2101L, nlevels(data$individual) == 58L,
            nlevels(data$occasion) == 464L)
  set.seed(20261130L, kind = "Mersenne-Twister", normal.kind = "Inversion",
           sample.kind = "Rejection")
  fit <- fit_model(data)
  diag <- diagnose(fit)
  if (!diag$qualified) stop("Generating fit failed the numerical screen")
  m <- matrices(fit)
  point <- targets(m)
  published <- utils::read.csv(file.path(root, "tutorial/downloads/extensions",
                                         "red-knots-intercept-fit-diagnostics.csv"))
  published <- published[published$engine == "gllvmTMB", ]
  if (nrow(published) != 1L || abs(published$logLik - diag$logLik) > 1e-4)
    stop("Generating fit differs from the displayed point fit")
  display_summary <- utils::read.csv(file.path(root, "tutorial/downloads/extensions",
                                               "red-knots-intercept-summary.csv"))
  display_summary <- display_summary[display_summary$engine == "gllvmTMB", ]
  display_cor <- utils::read.csv(file.path(root, "tutorial/downloads/extensions",
                                           "red-knots-intercept-correlations.csv"))
  display_cor <- display_cor[display_cor$engine == "gllvmTMB", ]
  check <- point[point$quantity %in% c("correlation", "communality", "repeatability"), ]
  key <- function(a, b, c) paste(a, b, c, sep = ":")
  for (i in seq_len(nrow(check))) {
    r <- check[i, ]
    expected <- if (r$quantity == "correlation") {
      display_cor$correlation[match(key(r$level, r$trait_1, r$trait_2),
        key(display_cor$level, display_cor$trait_1, display_cor$trait_2))]
    } else {
      field <- if (r$quantity == "repeatability") "repeatability" else paste0("communality_", r$level)
      display_summary[[field]][match(r$trait_1, display_summary$trait)]
    }
    if (!is.finite(expected) || abs(expected - r$value) > 1e-4)
      stop("Generating fit targets differ from display: ", r$quantity, " ", r$trait_1)
  }
  fixed <- summary(fit)$fixef
  mu <- fixed$Estimate[match(paste0("trait", traits), fixed$term)]
  residual_sd <- as.numeric(fit$report$sigma_eps)
  stopifnot(length(mu) == length(traits), all(is.finite(mu)),
            length(residual_sd) == 1L, is.finite(residual_sd), residual_sd >= 0)
  mask <- with(data, data.frame(bird = as.integer(individual),
                               period = as.integer(occasion), response = as.integer(trait)))
  identity <- data.frame(
    engine = "gllvmTMB", engine_version, r_version, rank_B = 2L, rank_W = 2L,
    n_birds = 58L, n_periods = 464L, n_observed = nrow(data),
    source_sha256 = source_hash, preparation_sha256 = prep_hash,
    point_recipe_sha256 = point_recipe_hash, bootstrap_sha256 = script_hash,
    observed_mask_sha256 = digest::digest(mask, algo = "sha256"),
    reference_seed = 20261130L, replicate_seed_base = 202612020L,
    residual_sd = residual_sd, diag
  )
  write_csv(identity, "red-knots-intercept-bootstrap-reference.csv")
  write_rds(list(identity = identity, fit = fit, point = point, data = data,
                 matrices = m, mask = mask, mu = mu, residual_sd = residual_sd),
            private_reference_path)
  cat("PASS red-knot bootstrap reference: matches the displayed 2/2 fit\n")
  quit(save = "no")
}

reference <- readRDS(private_reference_path)
id <- reference$identity
stopifnot(id$source_sha256 == source_hash, id$preparation_sha256 == prep_hash,
          id$point_recipe_sha256 == point_recipe_hash, id$bootstrap_sha256 == script_hash,
          id$engine_version == engine_version, id$r_version == r_version)
reference_hash <- hash_file(private_reference_path)
receipt_path <- function(i) file.path(out, "draws", sprintf("draw-%06d.rds", i))

if (mode == "run") {
  # Simulate fresh bird effects, period effects and independent Gaussian
  # observation noise on the scaled response. Use only the original observed
  # cells. The display's level-specific summaries omit the tiny numeric floor.
  covariance_root <- function(m) {
    e <- eigen(m, symmetric = TRUE)
    stopifnot(min(e$values) >= -1e-8)
    e$vectors %*% diag(sqrt(pmax(e$values, 0)), length(traits))
  }
  r_B <- covariance_root(reference$matrices$B$total)
  r_W <- covariance_root(reference$matrices$W$total)
  mask <- reference$mask
  try_fit <- function(data, optimizer, start_from = NULL) {
    begin <- proc.time()[["elapsed"]]
    warn <- character()
    withCallingHandlers(tryCatch({
      f <- fit_model(data, optimizer, start_from)
      d <- diagnose(f)
      z <- tryCatch(targets(matrices(f)), error = identity)
      error <- if (inherits(z, "error")) conditionMessage(z) else ""
      d$qualified <- d$qualified && !inherits(z, "error")
      list(fit = f, diagnostics = d, targets = z, error = error)
    }, error = function(e) list(
      fit = NULL, diagnostics = data.frame(logLik = NA_real_, convergence = NA_integer_,
        pd_hessian = FALSE, max_gradient = NA_real_, finite = FALSE, qualified = FALSE),
      targets = NULL, error = conditionMessage(e)
    )), warning = function(w) {
      warn <<- c(warn, conditionMessage(w))
      invokeRestart("muffleWarning")
    }) -> result
    result$diagnostics$optimizer <- optimizer
    result$diagnostics$start <- if (is.null(start_from)) "independent" else "previous_refit"
    result$diagnostics$elapsed_seconds <- proc.time()[["elapsed"]] - begin
    result$diagnostics$warning_count <- length(warn)
    result$diagnostics$error <- nzchar(result$error)
    result
  }
  for (i in replicates) {
    destination <- receipt_path(i)
    if (file.exists(destination)) {
      saved <- readRDS(destination)
      stopifnot(identical(saved$replicate, i), saved$reference_sha256 == reference_hash)
      next
    }
    seed <- as.integer(id$replicate_seed_base + i)
    set.seed(seed, kind = "Mersenne-Twister", normal.kind = "Inversion",
             sample.kind = "Rejection")
    B <- matrix(rnorm(id$n_birds * length(traits)), nrow = id$n_birds) %*% t(r_B)
    W <- matrix(rnorm(id$n_periods * length(traits)), nrow = id$n_periods) %*% t(r_W)
    data <- reference$data
    data$value <- reference$mu[mask$response] + B[cbind(mask$bird, mask$response)] +
      W[cbind(mask$period, mask$response)] + rnorm(nrow(data), sd = reference$residual_sd)

    first <- try_fit(data, "nlminb")
    attempts <- list(first)
    if (!first$diagnostics$qualified) {
      attempts[[2L]] <- try_fit(data, "optim", first$fit)
    }
    diagnostics <- do.call(rbind, lapply(attempts, "[[", "diagnostics"))
    eligible <- which(diagnostics$qualified)
    selected <- if (length(eligible)) eligible[which.max(diagnostics$logLik[eligible])] else NA_integer_
    if (!is.na(selected) &&
        any(diagnostics$logLik > diagnostics$logLik[selected] + 1e-4, na.rm = TRUE))
      selected <- NA_integer_
    diagnostics$selected <- seq_len(nrow(diagnostics)) %in% selected
    z <- if (is.na(selected)) NULL else attempts[[selected]]$targets
    write_rds(list(replicate = i, seed = seed, reference_sha256 = reference_hash,
                   diagnostics = diagnostics, targets = z), destination)
    cat("replicate", i, if (is.null(z)) "excluded" else "retained", "\n")
  }
  quit(save = "no")
}

paths <- vapply(replicates, receipt_path, character(1))
if (!all(file.exists(paths))) stop("At least one requested replicate receipt is missing")
draws <- lapply(paths, readRDS)
stopifnot(identical(vapply(draws, "[[", integer(1), "replicate"), replicates),
          all(vapply(draws, "[[", character(1), "reference_sha256") == reference_hash))
attempts <- do.call(rbind, lapply(draws, function(x) {
  data.frame(replicate = x$replicate, seed = x$seed,
             attempt = seq_len(nrow(x$diagnostics)), x$diagnostics)
}))
write_csv(attempts, "red-knots-intercept-bootstrap-attempts.csv")
retained <- vapply(draws, function(x) !is.null(x$targets), logical(1))
receipt <- data.frame(id, first_replicate = min(replicates), last_replicate = max(replicates),
                      attempted_refits = length(draws), retained_refits = sum(retained),
                      reference_sha256 = reference_hash)
write_csv(receipt, "red-knots-intercept-bootstrap-receipt.csv")
cat("Red-knot bootstrap:", sum(retained), "/", length(draws), "retained\n")
if (!any(retained)) stop("No qualified bootstrap refits; see attempt and campaign CSVs")
values <- vapply(draws[retained], function(x) {
  stopifnot(identical(x$targets[1:4], reference$point[1:4]))
  x$targets$value
}, numeric(nrow(reference$point)))
lower <- apply(values, 1L, stats::quantile, probs = .025, names = FALSE, type = 7)
upper <- apply(values, 1L, stats::quantile, probs = .975, names = FALSE, type = 7)
intervals <- data.frame(reference$point[1:4], estimate = reference$point$value,
                        lower_95 = lower, upper_95 = upper, retained_refits = sum(retained))
write_csv(intervals, "red-knots-intercept-bootstrap-intervals.csv")
long <- do.call(rbind, lapply(draws[retained], function(x) {
  data.frame(replicate = x$replicate, x$targets)
}))
write_csv(long, "red-knots-intercept-bootstrap-target-draws.csv")
