#!/usr/bin/env Rscript

# Compare the four 1/2-rank combinations for the six-trait, intercept-only
# red-knot model. AIC differences are calculated within each engine. The
# script writes aggregate receipts only; it does not save fitted objects or
# individual-level scores.

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)
source(file.path(root, "tutorial", "data", "prepare-red-knots.R"),
       local = new.env(parent = globalenv()))
prepared <- readRDS(file.path(root, "analysis", "cache", "tutorial-data",
                              "red-knots-six-intercept.rds"))
traits <- prepared$traits
long <- prepared$long
stopifnot(nrow(long) == 2101L, nlevels(long$individual) == 58L,
          nlevels(long$occasion) == 464L)

as_trait_matrix <- function(x) {
  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
}
matrix_rows <- function(matrices) do.call(rbind, lapply(names(matrices), function(name) {
  x <- matrices[[name]]
  ij <- expand.grid(trait_row = traits, trait_col = traits,
                    stringsAsFactors = FALSE)
  data.frame(part = name, ij, estimate = as.vector(x), stringsAsFactors = FALSE)
}))

extract_glmm <- function(fit, db, dw) {
  blocks <- glmmTMB::VarCorr(fit)$cond
  type <- vapply(blocks, function(x) {
    code <- attr(x, "blockCode")
    if (is.null(code)) NA_character_ else names(code)[1L]
  }, character(1))
  keys <- names(blocks)
  group <- sub("\\.[0-9]+$", "", keys)
  brr <- keys[group == "individual" & type == "rr"]
  bdiag <- keys[group == "individual" & type == "diag"]
  wrr <- keys[group == "occasion" & type == "rr"]
  if (length(brr) != 1L || length(bdiag) != 1L || length(wrr) != 1L)
    stop("Unexpected glmmTMB covariance blocks")
  Bs <- as_trait_matrix(blocks[[brr]])
  Bu <- as_trait_matrix(blocks[[bdiag]])
  Ws <- as_trait_matrix(blocks[[wrr]])
  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")
  Wu <- diag(exp(2 * beta[match(wanted, names(beta))]), nrow = length(traits))
  dimnames(Wu) <- list(traits, traits)
  list(B_shared = Bs, B_unique = Bu, B_total = Bs + Bu,
       W_shared = Ws, W_unique = Wu, W_total = Ws + Wu)
}
extract_gllvm <- function(fit) {
  get <- function(level, part) as_trait_matrix(
    gllvmTMB::extract_Sigma(fit, level = level, part = part,
                            link_residual = "none")$Sigma
  )
  Bs <- get("unit", "shared"); Ws <- get("unit_obs", "shared")
  Bt <- get("unit", "total"); Wt <- get("unit_obs", "total")
  list(B_shared = Bs, B_unique = Bt - Bs, B_total = Bt,
       W_shared = Ws, W_unique = Wt - Ws, W_total = Wt)
}
healthy <- function(fit, engine, matrices) {
  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
  }
  cov_ok <- TRUE
  for (level in c("B", "W")) {
    shared <- matrices[[paste0(level, "_shared")]]
    unique <- matrices[[paste0(level, "_unique")]]
    total <- matrices[[paste0(level, "_total")]]
    cov_ok <- cov_ok && max(abs(total - shared - unique)) < 1e-7 &&
      max(abs(unique - diag(diag(unique)))) < 1e-8 &&
      min(eigen((total + t(total))/2, symmetric = TRUE, only.values = TRUE)$values) > -1e-8
  }
  ll <- stats::logLik(fit)
  list(convergence = as.integer(convergence), pd_hessian = pd_hessian,
       max_gradient = max_gradient, covariance_valid = cov_ok,
       fit_qualified = identical(as.integer(convergence), 0L) && pd_hessian &&
         is.finite(max_gradient) && max_gradient <= .01 && cov_ok &&
         is.finite(as.numeric(ll)),
       logLik = as.numeric(ll), npar = as.integer(attr(ll, "df")),
       AIC = stats::AIC(fit), BIC = stats::BIC(fit))
}

rows <- list()
matrices_out <- list()
for (db in 1:2) for (dw in 1:2) for (engine in c("glmmTMB", "gllvmTMB")) {
  rhs <- c("0 + trait",
    sprintf("rr(0 + trait | individual, d = %d)", db),
    "diag(0 + trait | individual)",
    sprintf("rr(0 + trait | occasion, d = %d)", dw))
  if (engine == "gllvmTMB") rhs <- c("0 + trait",
    sprintf("latent(0 + trait | individual, d = %d, unique = TRUE)", db),
    sprintf("latent(0 + trait | occasion, d = %d, unique = TRUE)", dw))
  form <- stats::as.formula(paste("value ~", paste(rhs, collapse = " + ")))
  set.seed(20261130L)
  optimizer <- if (engine == "glmmTMB" && db == 2L && dw == 2L) "BFGS" else "nlminb"
  fit <- if (engine == "glmmTMB") {
    control <- if (optimizer == "BFGS")
      glmmTMB::glmmTMBControl(optimizer = optim, optArgs = list(method = "BFGS"),
        optCtrl = list(maxit = 1500L, reltol = 1e-10)) else
      glmmTMB::glmmTMBControl(optCtrl = list(iter.max = 1500L, eval.max = 2000L))
    glmmTMB::glmmTMB(form, data = long, family = stats::gaussian(),
      dispformula = ~ 0 + trait, REML = FALSE, control = control)
  } else {
    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"))
    gllvmTMB::gllvmTMB(form, data = long, trait = "trait", unit = "individual",
      unit_obs = "occasion", family = stats::gaussian(), REML = FALSE,
      control = control)
  }
  mats <- if (engine == "glmmTMB") extract_glmm(fit, db, dw) else extract_gllvm(fit)
  health <- healthy(fit, engine, mats)
  key <- paste(engine, db, dw, sep = "-")
  matrices_out[[key]] <- mats
  rows[[key]] <- data.frame(engine = engine, d_B = db, d_W = dw,
    optimizer = optimizer, n_individuals = 58L, n_occasions = 464L,
    n_observed = nrow(long), logLik = health$logLik, npar = health$npar,
    AIC = health$AIC, BIC = health$BIC,
    convergence = health$convergence, pd_hessian = health$pd_hessian,
    max_gradient = health$max_gradient,
    covariance_valid = health$covariance_valid,
    fit_qualified = health$fit_qualified,
    near_zero_unique_B = min(diag(mats$B_unique)) < 1e-6,
    near_zero_unique_W = min(diag(mats$W_unique)) < 1e-6,
    stringsAsFactors = FALSE)
}

results <- do.call(rbind, rows)
results$delta_AIC <- NA_real_
results$akaike_weight <- NA_real_
for (engine in unique(results$engine)) {
  ix <- results$engine == engine & results$fit_qualified
  if (!any(ix)) stop("No qualified rank in ", engine)
  results$delta_AIC[ix] <- results$AIC[ix] - min(results$AIC[ix])
  w <- exp(-.5 * results$delta_AIC[ix])
  results$akaike_weight[ix] <- w / sum(w)
}
utils::write.csv(results, file.path(out_dir, "red-knots-intercept-rank-grid.csv"),
                 row.names = FALSE)
utils::write.csv(do.call(rbind, lapply(names(matrices_out), function(key) {
  bits <- strsplit(key, "-", fixed = TRUE)[[1L]]
  z <- matrix_rows(matrices_out[[key]])
  z$engine <- bits[1L]; z$d_B <- as.integer(bits[2L]); z$d_W <- as.integer(bits[3L]); z
})), file.path(out_dir, "red-knots-intercept-rank-matrices.csv"), row.names = FALSE)
cat("PASS RED-KNOT RANK GRID: eight intercept-only fits attempted; within-engine AIC tables and covariance matrices exported.\n")
