#!/usr/bin/env Rscript

# Refit the six-trait, intercept-only red-knot teaching model with both
# packages. This script writes only aggregate summaries and fit diagnostics.
# Run it from the repository root. The individual-level data and fit objects
# remain in memory and are not exported.

root <- normalizePath(getwd(), mustWork = TRUE)
args <- commandArgs(trailingOnly = TRUE)
out_dir <- if (length(args)) args[[1L]] else
  file.path(root, "tutorial", "downloads", "extensions")
if (!dir.exists(out_dir)) dir.create(out_dir, recursive = TRUE)
figure_dir <- file.path(root, "tutorial", "figures")
if (!dir.exists(figure_dir)) dir.create(figure_dir, recursive = TRUE)

required <- c("glmmTMB", "gllvmTMB", "digest", "ggplot2", "patchwork")
missing <- required[!vapply(required, requireNamespace, logical(1), quietly = TRUE)]
if (length(missing)) stop("Install required packages: ", paste(missing, collapse = ", "))

source(file.path(root, "tutorial", "data", "prepare-red-knots.R"), local = new.env(parent = globalenv()))
prepared_path <- file.path(root, "analysis", "cache", "tutorial-data", "red-knots-six-intercept.rds")
if (!file.exists(prepared_path)) stop("Preparation did not create: ", prepared_path)
prepared <- readRDS(prepared_path)
traits <- prepared$traits
long <- prepared$long
stopifnot(identical(traits, c("mass", "gizzard", "BMR_W", "exploration", "activity", "feeding")),
          nrow(long) == 2101L, nlevels(long$individual) == 58L,
          nlevels(long$occasion) == 464L, !anyNA(long$value))

form_glmm <- value ~ 0 + trait +
  rr(0 + trait | individual, d = 2) + diag(0 + trait | individual) +
  rr(0 + trait | occasion, d = 2)
form_gllvm <- value ~ 0 + trait +
  latent(0 + trait | individual, d = 2, unique = TRUE) +
  latent(0 + trait | occasion, d = 2, unique = TRUE)

set.seed(20261130L)
fit_glmm <- glmmTMB::glmmTMB(
  form_glmm, data = long, family = stats::gaussian(),
  dispformula = ~ 0 + trait, REML = FALSE,
  control = glmmTMB::glmmTMBControl(
    optimizer = optim, optArgs = list(method = "BFGS"),
    optCtrl = list(maxit = 1500L, reltol = 1e-10)
  )
)
# During the campaign build, reuse the exact private generating fit.
# Public replay can refit with the same recipe and verify all plotted targets.
fit_gllvm <- if (length(args) >= 2L) {
  reference <- readRDS(args[[2L]])
  keys <- c("individual", "occasion", "trait")
  stopifnot(all(vapply(keys, function(k) {
    identical(as.character(reference$data[[k]]), as.character(long[[k]]))
  }, logical(1))),
            max(abs(reference$data$value - long$value)) < 1e-12,
            identical(reference$identity$engine, "gllvmTMB"),
            reference$identity$rank_B == 2L, reference$identity$rank_W == 2L)
  reference$fit
} else {
  set.seed(20261130L)
  gllvmTMB::gllvmTMB(
    form_gllvm, data = long, trait = "trait", unit = "individual",
    unit_obs = "occasion", family = stats::gaussian(), REML = FALSE,
    control = gllvmTMB::gllvmTMBcontrol(
      optimizer = "nlminb",
      optArgs = list(control = list(iter.max = 1500L, eval.max = 2000L)),
      n_init = 1L, init_jitter = 0,
      start_method = list(method = "indep")
    )
  )
}

as_trait_matrix <- function(x, traits) {
  x <- as.matrix(x)
  rn <- sub("^trait", "", rownames(x))
  cn <- sub("^trait", "", colnames(x))
  if (is.null(rn) || is.null(cn) || !setequal(rn, traits) || !setequal(cn, traits))
    stop("Covariance labels do not match the frozen trait order")
  x <- x[match(traits, rn), match(traits, cn), drop = FALSE]
  dimnames(x) <- list(traits, traits)
  x
}

glmm_matrices <- function(fit) {
  blocks <- glmmTMB::VarCorr(fit)$cond
  block_type <- function(x) {
    code <- attr(x, "blockCode")
    if (is.null(code)) return(NA_character_)
    names(code)[1L]
  }
  keys <- names(blocks)
  codes <- vapply(blocks, block_type, character(1))
  b_rr <- keys[sub("\\.[0-9]+$", "", keys) == "individual" & codes == "rr"]
  b_diag <- keys[sub("\\.[0-9]+$", "", keys) == "individual" & codes == "diag"]
  w_rr <- keys[sub("\\.[0-9]+$", "", keys) == "occasion" & codes == "rr"]
  if (length(b_rr) != 1L || length(b_diag) != 1L || length(w_rr) != 1L)
    stop("Unexpected glmmTMB covariance blocks")
  B_shared <- as_trait_matrix(blocks[[b_rr]], traits)
  B_unique <- as_trait_matrix(blocks[[b_diag]], traits)
  beta <- glmmTMB::fixef(fit)$disp
  wanted <- paste0("trait", traits)
  if (length(beta) != length(traits) || !setequal(names(beta), wanted))
    stop("Expected one Gaussian dispersion parameter per trait")
  W_unique <- diag(exp(2 * beta[match(wanted, names(beta))]), nrow = length(traits))
  W_shared <- as_trait_matrix(blocks[[w_rr]], traits)
  dimnames(W_unique) <- list(traits, traits)
  list(B_shared = B_shared, B_unique = B_unique,
       B_total = B_shared + B_unique, W_shared = W_shared,
       W_unique = W_unique, W_total = W_shared + W_unique)
}

gllvm_matrices <- function(fit) {
  extract <- function(level, part) as_trait_matrix(
    gllvmTMB::extract_Sigma(fit, level = level, part = part,
                            link_residual = "none")$Sigma, traits
  )
  B_shared <- extract("unit", "shared")
  W_shared <- extract("unit_obs", "shared")
  B_total <- extract("unit", "total")
  W_total <- extract("unit_obs", "total")
  list(B_shared = B_shared, B_unique = B_total - B_shared, B_total = B_total,
       W_shared = W_shared, W_unique = W_total - W_shared, W_total = W_total)
}

fits <- list(glmmTMB = fit_glmm, gllvmTMB = fit_gllvm)
matrices <- list(glmmTMB = glmm_matrices(fit_glmm), gllvmTMB = gllvm_matrices(fit_gllvm))
matrix_error <- function(x) max(abs(x - t(x)))
for (engine in names(matrices)) for (level in c("B", "W")) {
  m <- matrices[[engine]]
  shared <- m[[paste0(level, "_shared")]]
  unique <- m[[paste0(level, "_unique")]]
  total <- m[[paste0(level, "_total")]]
  if (matrix_error(shared) > 1e-8 || matrix_error(unique) > 1e-8 ||
      matrix_error(total) > 1e-8 || max(abs(total - shared - unique)) > 1e-7 ||
      any(diag(unique) < -1e-8) || max(abs(unique - diag(diag(unique)))) > 1e-8)
    stop(engine, " ", level, " covariance reconstruction failed")
}

summary_rows <- list()
correlation_rows <- list()
for (engine in names(matrices)) {
  m <- matrices[[engine]]
  R <- diag(m$B_total) / (diag(m$B_total) + diag(m$W_total))
  summary_rows[[engine]] <- data.frame(
    engine = engine, trait = traits,
    between_variance = diag(m$B_total), within_variance = diag(m$W_total),
    repeatability = as.numeric(R),
    communality_B = diag(m$B_shared) / diag(m$B_total),
    communality_W = diag(m$W_shared) / diag(m$W_total),
    stringsAsFactors = FALSE
  )
  for (level in c("B", "W")) {
    C <- stats::cov2cor(m[[paste0(level, "_total")]])
    cells <- expand.grid(row = seq_along(traits), col = seq_along(traits))
    correlation_rows[[paste(engine, level)]] <- data.frame(
      engine = engine, level = level,
      trait_1 = traits[cells$row], trait_2 = traits[cells$col],
      correlation = C[cbind(cells$row, cells$col)], stringsAsFactors = FALSE
    )
  }
}

diagnostic_row <- function(engine, fit) {
  if (engine == "glmmTMB") {
    convergence <- fit$fit$convergence
    pd_hessian <- isTRUE(fit$sdr$pdHess)
    max_gradient <- max(abs(fit$obj$gr(fit$fit$par)))
  } else {
    convergence <- fit$fit_health$convergence
    pd_hessian <- isTRUE(fit$fit_health$pd_hessian)
    max_gradient <- fit$fit_health$max_gradient
  }
  ll <- stats::logLik(fit)
  data.frame(engine = engine, d_B = 2L, d_W = 2L,
    n_individuals = 58L, n_occasions = 464L, n_observed = nrow(long),
    logLik = as.numeric(ll), npar = as.integer(attr(ll, "df")),
    AIC = stats::AIC(fit), BIC = stats::BIC(fit),
    convergence = as.integer(convergence), pd_hessian = pd_hessian,
    max_gradient = max_gradient,
    stringsAsFactors = FALSE)
}
diagnostics <- do.call(rbind, Map(diagnostic_row, names(fits), fits))
if (any(diagnostics$convergence != 0L) || !all(diagnostics$pd_hessian) ||
    any(!is.finite(diagnostics$max_gradient)) || any(diagnostics$max_gradient > .01))
  stop("At least one refit did not meet the registered numerical rules")

engine_difference <- max(vapply(c("B_shared", "B_unique", "B_total",
                                  "W_shared", "W_unique", "W_total"),
  function(part) max(abs(matrices$glmmTMB[[part]] - matrices$gllvmTMB[[part]])),
  numeric(1)))
if (!is.finite(engine_difference) || engine_difference > 1e-4)
  stop("The selected point fits do not reconstruct matching covariance matrices")
# The primary display uses gllvmTMB's public ordination plot method. The
# correlation, communality, and repeatability panels use reconstructed
# covariance matrices, so they do not depend on loading signs.
gllvm_summary <- subset(do.call(rbind, summary_rows), engine == "gllvmTMB")
gllvm_correlations <- subset(do.call(rbind, correlation_rows), engine == "gllvmTMB")
interval_path <- file.path(out_dir, "red-knots-intercept-bootstrap-intervals.csv")
intervals <- if (file.exists(interval_path)) utils::read.csv(interval_path) else NULL
if (!is.null(intervals)) {
  receipt_path <- file.path(out_dir, "red-knots-intercept-bootstrap-figure-receipt.csv")
  if (!file.exists(receipt_path)) stop("Missing final bootstrap figure receipt")
  receipt <- utils::read.csv(receipt_path)
  if (nrow(receipt) != 1L || receipt$retained_refits < 1000L ||
      !all(intervals$retained_refits == receipt$retained_refits) ||
      !identical(digest::digest(file = interval_path, algo = "sha256"), receipt$interval_sha256))
    stop("Final bootstrap draw count or interval checksum differs from the receipt")
  if (length(args) >= 2L &&
      !identical(digest::digest(file = args[[2L]], algo = "sha256"), receipt$reference_sha256))
    stop("The private generating fit differs from the bootstrap receipt")
}


add_intervals <- function(data, quantity, level, trait_1, trait_2, point) {
  if (is.null(intervals)) return(data)
  source <- intervals[intervals$quantity == quantity, , drop = FALSE]
  key <- function(level, trait_1, trait_2) paste(level, trait_1, trait_2, sep = "/")
  lookup <- key(source$level, source$trait_1, source$trait_2)
  if (anyDuplicated(lookup)) stop("Duplicate bootstrap target")
  index <- match(key(level, trait_1, trait_2), lookup)
  if (anyNA(index)) stop("Missing bootstrap target")
  selected <- source[index, ]
  if (any(!is.finite(selected$lower_95)) || any(!is.finite(selected$upper_95)) ||
      any(selected$lower_95 > selected$upper_95) ||
      any(!is.finite(selected$estimate)) || max(abs(selected$estimate - point)) > 1e-5)
    stop("Bootstrap intervals do not match the plotted fit and targets")
  data$lower_95 <- selected$lower_95
  data$upper_95 <- selected$upper_95
  data
}

heatmap <- function(level, panel) {
  z <- gllvm_correlations[gllvm_correlations$level == level, ]
  z$label <- sprintf("%.2f", z$correlation)
  z$fill <- z$correlation
  if (!is.null(intervals)) {
    i <- match(z$trait_2, traits)
    j <- match(z$trait_1, traits)
    off <- i != j
    limits <- add_intervals(z[off, ], "correlation", level,
      traits[pmin(i[off], j[off])], traits[pmax(i[off], j[off])], z$correlation[off])
    show_interval <- i[off] > j[off]
    clear_sign <- limits$lower_95 > 0 | limits$upper_95 < 0
    label <- paste0(sprintf("%.2f", limits$correlation), ifelse(clear_sign, "*", ""))
    label[show_interval] <- sprintf("%.2f\n%.2f", limits$lower_95[show_interval],
                                    limits$upper_95[show_interval])
    z$label[off] <- label
    z$label[!off] <- ""
    z$fill[i >= j] <- NA_real_
  }
  short_labels <- c(
    mass = "Mass", gizzard = "Gizzard", BMR_W = "BMR",
    exploration = "Exploration", activity = "Activity", feeding = "Feeding"
  )
  z$trait_1 <- factor(unname(short_labels[z$trait_1]),
                      levels = unname(short_labels[traits]))
  z$trait_2 <- factor(unname(short_labels[z$trait_2]),
                      levels = unname(short_labels[rev(traits)]))
  ggplot2::ggplot(z, ggplot2::aes(trait_1, trait_2, fill = fill)) +
    ggplot2::geom_tile(colour = "white", linewidth = .35) +
    ggplot2::geom_text(ggplot2::aes(label = label), size = 2.7) +
    ggplot2::scale_fill_gradient2(low = "#bb675d", mid = "#fafafa", high = "#6595b9",
      midpoint = 0, na.value = "#f4f4f4", limits = c(-1, 1), name = "Correlation") +
    ggplot2::coord_equal() +
    ggplot2::labs(title = panel, x = NULL, y = NULL) +
    ggplot2::theme_minimal(base_size = 10) +
    ggplot2::theme(axis.text.x = ggplot2::element_text(angle = 45, hjust = 1),
      panel.grid = ggplot2::element_blank(), plot.title = ggplot2::element_text(face = "bold"))
}
ord_B <- plot(fit_gllvm, type = "ordination", level = "unit", rotation = "varimax") +
  ggplot2::labs(title = "C. Between-bird ordination", x = "Axis 1", y = "Axis 2") +
  ggplot2::theme(plot.caption = ggplot2::element_blank())
ord_W <- plot(fit_gllvm, type = "ordination", level = "unit_obs", rotation = "varimax") +
  ggplot2::labs(title = "D. Within-period ordination", x = "Axis 1", y = "Axis 2") +
  ggplot2::theme(plot.caption = ggplot2::element_blank())
comm_data <- rbind(
  data.frame(trait = traits, level = "Between birds", value = gllvm_summary$communality_B),
  data.frame(trait = traits, level = "Within periods", value = gllvm_summary$communality_W)
)
trait_labels <- c(
  mass = "Body mass", gizzard = "Gizzard mass",
  BMR_W = "BMR", exploration = "Exploration",
  activity = "Activity", feeding = "Feeding"
)
comm_data <- add_intervals(comm_data, "communality",
  rep(c("B", "W"), each = length(traits)), comm_data$trait, comm_data$trait, comm_data$value)
comm_data$trait_label <- unname(trait_labels[as.character(comm_data$trait)])
comm_data$trait <- factor(comm_data$trait_label,
                          levels = unname(trait_labels[rev(traits)]))
comm_data$y <- as.numeric(comm_data$trait) +
  ifelse(comm_data$level == "Between birds", -.12, .12)
comm_plot <- ggplot2::ggplot(comm_data, ggplot2::aes(value, y, colour = level, shape = level))
if (!is.null(intervals)) comm_plot <- comm_plot +
  ggplot2::geom_errorbar(ggplot2::aes(xmin = lower_95, xmax = upper_95),
    orientation = "y", width = .12, linewidth = .5, show.legend = FALSE)
comm_plot <- comm_plot +
  ggplot2::geom_point(size = 2.5) +
  ggplot2::scale_y_continuous(breaks = seq_along(traits), labels = unname(trait_labels[rev(traits)])) +
  ggplot2::scale_colour_manual(values = c("Between birds" = "#235985", "Within periods" = "#a7460c")) +
  ggplot2::scale_shape_manual(values = c("Between birds" = 16, "Within periods" = 17)) +
  ggplot2::scale_x_continuous(limits = c(0, 1), breaks = seq(0, 1, .25)) +
  ggplot2::labs(title = "E. Communality", x = "Shared fraction at that level", y = NULL,
                colour = NULL, shape = NULL) + ggplot2::theme_minimal(base_size = 10) +
  ggplot2::theme(plot.title = ggplot2::element_text(face = "bold"),
                 legend.position = "bottom", panel.grid.minor = ggplot2::element_blank())
rep_data <- add_intervals(gllvm_summary, "repeatability", "B_over_total",
  gllvm_summary$trait, gllvm_summary$trait, gllvm_summary$repeatability)
rep_data$trait <- factor(unname(trait_labels[rep_data$trait]),
                         levels = unname(trait_labels[rev(traits)]))
rep_plot <- ggplot2::ggplot(rep_data, ggplot2::aes(repeatability, trait))
if (!is.null(intervals)) rep_plot <- rep_plot +
  ggplot2::geom_errorbar(ggplot2::aes(xmin = lower_95, xmax = upper_95),
    orientation = "y", width = .14, linewidth = .5)
rep_plot <- rep_plot +
  ggplot2::geom_vline(xintercept = 0, colour = "grey75") +
  ggplot2::geom_point(shape = 21, fill = "#1b6ca8", size = 2.7) +
  ggplot2::scale_x_continuous(limits = c(0, 1), breaks = seq(0, 1, .25)) +
  ggplot2::labs(title = "F. Repeatability", x = "Between-bird fraction of total variance", y = NULL) +
  ggplot2::theme_minimal(base_size = 10) +
  ggplot2::theme(plot.title = ggplot2::element_text(face = "bold"),
                 panel.grid.minor = ggplot2::element_blank())
figure <- (heatmap("B", "A. Between-bird correlations") |
           heatmap("W", "B. Within-period correlations")) /
  (ord_B | ord_W) /
  (comm_plot | rep_plot) +
  patchwork::plot_layout(heights = c(1, 1.25, .8), guides = "collect") &
  ggplot2::theme(legend.position = "bottom")
# Prepare every output before replacing any reader-facing files.
staging <- tempfile("red-knot-figure-staging-")
dir.create(staging)
utils::write.csv(data.frame(model = "six-trait intercept-only 2/2",
  glmmTMB_vs_gllvmTMB_max_abs_covariance_difference = engine_difference),
  file.path(staging, "red-knots-intercept-engine-comparison.csv"), row.names = FALSE)

utils::write.csv(do.call(rbind, summary_rows),
  file.path(staging, "red-knots-intercept-summary.csv"), row.names = FALSE)
utils::write.csv(do.call(rbind, correlation_rows),
  file.path(staging, "red-knots-intercept-correlations.csv"), row.names = FALSE)
utils::write.csv(diagnostics,
  file.path(staging, "red-knots-intercept-fit-diagnostics.csv"), row.names = FALSE)

figure_stem <- if (is.null(intervals)) "red-knots-intercept-point-only" else "red-knots-intercept-six-panel"
ggplot2::ggsave(file.path(staging, paste0(figure_stem, ".png")),
  figure, width = 12, height = 13, dpi = 180)
ggplot2::ggsave(file.path(staging, paste0(figure_stem, ".pdf")),
  figure, width = 12, height = 13)

for (path in list.files(staging, full.names = TRUE)) {
  destination <- if (!is.null(intervals) && grepl("\\.(png|pdf)$", path)) figure_dir else out_dir
  if (!file.copy(path, destination, overwrite = TRUE)) stop("Could not copy ", path)
}
if (is.null(intervals)) message("Point-estimate figure only. No bootstrap interval file was supplied.")

cat("PASS RED-KNOT INTERCEPT EXPORT: 6 traits; 58 birds; 464 periods; 2,101 observed responses; matched 2/2 formulas; both fits qualified.\n")
