#!/usr/bin/env Rscript
# Simulated reaction norms for tutorial/random-slopes.qmd.  Run this script;
# website rendering only reads the files it writes.

root <- getwd()
if (!dir.exists(file.path(root, "tutorial"))) stop("Run from the repository root.")
out_analysis <- file.path(root, "analysis", "extensions", "outputs")
out_fig <- file.path(root, "tutorial", "figures", "extensions")
out_download <- file.path(root, "tutorial", "downloads", "extensions")
for (d in c(out_analysis, out_fig, out_download)) dir.create(d, recursive = TRUE, showWarnings = FALSE)

`%||%` <- function(x, y) if (is.null(x)) y else x
require_namespace <- function(x) if (!requireNamespace(x, quietly = TRUE)) stop("Need package: ", x)
require_namespace("glmmTMB"); require_namespace("gllvmTMB"); require_namespace("MASS"); require_namespace("ggplot2")
suppressPackageStartupMessages(library(ggplot2))

Sigma_uni <- matrix(c(0.70^2, -0.45 * 0.70 * 0.30,
                      -0.45 * 0.70 * 0.30, 0.30^2), 2, 2,
                    dimnames = list(c("intercept", "slope"), c("intercept", "slope")))

make_univariate <- function(n_ind = 36L, n_rep = 7L, seed = 20260906L) {
  set.seed(seed)
  x <- seq(-1.5, 1.5, length.out = n_rep)
  b <- MASS::mvrnorm(n_ind, mu = c(0, 0), Sigma = Sigma_uni)
  d <- expand.grid(individual = factor(seq_len(n_ind)), replicate = seq_len(n_rep), KEEP.OUT.ATTRS = FALSE)
  d$temp_c <- rep(x, each = n_ind)
  d$value <- 3 + 0.40 * d$temp_c + b[as.integer(d$individual), 1] +
    b[as.integer(d$individual), 2] * d$temp_c + rnorm(nrow(d), 0, 0.55)
  d
}

fit_univariate <- function(d) {
  glmmTMB::glmmTMB(value ~ temp_c + (1 + temp_c | individual), data = d, family = gaussian())
}

extract_univariate <- function(fit, x = seq(-1.5, 1.5, length.out = 100L)) {
  S <- as.matrix(glmmTMB::VarCorr(fit)$cond$individual)
  resid <- sigma(fit)^2
  cov01 <- S["(Intercept)", "temp_c"]
  vb <- S["(Intercept)", "(Intercept)"] + 2 * x * cov01 + x^2 * S["temp_c", "temp_c"]
  data.frame(temp_c = x, between_variance = vb, residual_variance = resid,
             repeatability = vb / (vb + resid))
}

reaction_norm_rows <- function(fit, d) {
  re <- glmmTMB::ranef(fit)$cond$individual
  fe <- glmmTMB::fixef(fit)$cond
  g <- expand.grid(individual = rownames(re), temp_c = seq(min(d$temp_c), max(d$temp_c), length.out = 80L), KEEP.OUT.ATTRS = FALSE)
  g$prediction <- fe["(Intercept)"] + fe["temp_c"] * g$temp_c +
    re[g$individual, "(Intercept)"] + re[g$individual, "temp_c"] * g$temp_c
  g
}

# The same ggplot2 objects can be restyled and saved at publication resolution.
save_teaching_plot <- function(p, path, width = 8, height = 5.5) {
  p <- p + theme_minimal(base_size = 12) +
    theme(panel.grid.minor = element_blank(), legend.position = "bottom",
          plot.title = element_text(face = "bold"))
  ggsave(path, p, width = width, height = height, dpi = 180)
  ggsave(sub("\\.png$", ".pdf", path), p, width = width, height = height)
}

plot_univariate <- function(d, lines, path) {
  ids <- levels(d$individual); keep <- ids[seq_len(min(12L, length(ids)))]
  # Small multiples let readers follow one animal without relying on 12 colours.
  p <- ggplot(d[d$individual %in% keep, ], aes(temp_c, value)) +
    geom_vline(xintercept = 0, linetype = "dashed", colour = "grey55") +
    geom_point(colour = "#0072B2", alpha = .7, size = 1.5) +
    geom_line(data = lines[lines$individual %in% keep, ],
              aes(y = prediction, group = individual), colour = "#D55E00", linewidth = .8) +
    facet_wrap(~individual, ncol = 4, labeller = label_both) +
    labs(x = "Temperature relative to reference", y = "Behaviour",
         title = "Each animal has its own reaction norm",
         subtitle = "Points: simulated observations; lines: fitted individual responses")
  save_teaching_plot(p, path, width = 9, height = 6.5)
}

plot_repeatability <- function(tab, path) {
  p <- ggplot(tab, aes(temp_c, repeatability)) +
    geom_vline(xintercept = 0, linetype = "dashed", colour = "grey55") +
    geom_line(colour = "#0072B2", linewidth = 1.2) +
    scale_y_continuous(limits = c(0, 1)) +
    labs(x = "Temperature relative to reference", y = "Pointwise repeatability",
         title = "Repeatability changes with temperature")
  save_teaching_plot(p, path)
}

require_healthy_fit <- function(convergence, pd_hessian, max_gradient, label) {
  if (!isTRUE(convergence == 0L) || !isTRUE(pd_hessian) ||
      !isTRUE(is.finite(max_gradient) && max_gradient <= .01)) {
    stop(label, " fit failed its numerical checks. Read the saved fit-health table.")
  }
}

run_univariate <- function() {
  d <- make_univariate(); started <- proc.time()[["elapsed"]]; fit <- fit_univariate(d)
  elapsed <- proc.time()[["elapsed"]] - started
  if (elapsed > 120) stop("First glmmTMB fit exceeded the 2-minute tutorial budget.")
  health <- data.frame(convergence = fit$fit$convergence,
    pd_hessian = isTRUE(fit$sdr$pdHess),
    max_gradient = max(abs(fit$obj$gr(fit$fit$par))))
  utils::write.csv(health, file.path(out_analysis, "univariate-fit-health.csv"), row.names = FALSE)
  require_healthy_fit(health$convergence, health$pd_hessian, health$max_gradient, "Univariate")
  tab <- extract_univariate(fit); lines <- reaction_norm_rows(fit, d)
  S <- as.matrix(glmmTMB::VarCorr(fit)$cond$individual)
  result <- data.frame(term = c("intercept_variance", "slope_variance", "intercept_slope_covariance", "intercept_slope_correlation", "residual_variance", "fit_seconds"),
                       estimate = c(S[1,1], S[2,2], S[1,2], attr(S, "correlation")[1,2], sigma(fit)^2, elapsed))
  utils::write.csv(d, file.path(out_analysis, "univariate-input.csv"), row.names = FALSE)
  utils::write.csv(tab, file.path(out_analysis, "univariate-repeatability.csv"), row.names = FALSE)
  utils::write.csv(result, file.path(out_analysis, "univariate-results.csv"), row.names = FALSE)
  plot_univariate(d, lines, file.path(out_fig, "univariate-reaction-norms.png"))
  plot_repeatability(tab, file.path(out_fig, "univariate-repeatability.png"))
  list(data = d, fit = fit, table = tab, elapsed = elapsed)
}

make_multivariate <- function(n_ind = 30L, n_rep = 6L, seed = 20260907L) {
  set.seed(seed); traits <- c("boldness", "exploration", "activity")
  # Rank-one-plus-diagonal truth, ordered intercept.trait then slope.temperature.trait.
  Lb <- c(0.65, 0.48, 0.36, 0.24, -0.18, 0.15); Sb <- tcrossprod(Lb) + diag(c(.14, .12, .11, .08, .08, .08)^2)
  Lw <- c(0.30, 0.20, 0.15); Sw <- tcrossprod(Lw) + diag(c(.24, .22, .20)^2)
  u <- MASS::mvrnorm(n_ind, rep(0, 6), Sb); w <- MASS::mvrnorm(n_ind * n_rep, rep(0, 3), Sw)
  z <- expand.grid(individual = factor(seq_len(n_ind)), session = seq_len(n_rep), trait = traits, KEEP.OUT.ATTRS = FALSE)
  z$trait <- factor(z$trait, levels = traits); z$session_id <- interaction(z$individual, z$session, drop = TRUE)
  z$temp_c <- rep(rep(seq(-1.25, 1.25, length.out = n_rep), each = n_ind), times = length(traits))
  ti <- as.integer(z$trait); ii <- as.integer(z$individual); si <- as.integer(z$session_id)
  beta0 <- c(3.2, 2.8, 3.5); beta1 <- c(.35, .20, -.15)
  z$value <- beta0[ti] + beta1[ti] * z$temp_c + u[cbind(ii, ti)] +
    u[cbind(ii, ti + 3L)] * z$temp_c + w[cbind(si, ti)]
  list(data = z, Sigma_B = Sb, Sigma_W = Sw, traits = traits)
}

fit_multivariate <- function(d) {
  # `latent()` is parsed from the formula; package qualification belongs on the fitter.
  latent <- gllvmTMB::latent
  gllvmTMB::gllvmTMB(
  value ~ 0 + trait + (0 + trait):temp_c +
    latent(0 + trait + (0 + trait):temp_c | individual, d = 1, unique = TRUE) +
    latent(0 + trait | session_id, d = 1, unique = TRUE),
  data = d, trait = "trait", unit = "individual", unit_obs = "session_id", family = gaussian(),
  control = gllvmTMB::gllvmTMBcontrol(se = TRUE), silent = TRUE)
}

multivariate_curves <- function(Sb, Sw, traits, x = seq(-1.25, 1.25, length.out = 100L)) {
  intercept <- paste0("intercept.", traits); slope <- paste0("slope.temp_c.", traits)
  # Current public extractor labels the predictor with its formula name; fail loudly if that changes.
  if (!all(intercept %in% rownames(Sb)) || !all(slope %in% rownames(Sb))) stop("Unexpected public gllvmTMB covariance labels.")
  out <- lapply(x, function(xx) {
    A <- cbind(diag(length(traits)), xx * diag(length(traits)))
    B <- Sb[c(intercept, slope), c(intercept, slope), drop = FALSE]
    V <- A %*% B %*% t(A)
    data.frame(temp_c = xx, trait = traits, between_variance = diag(V),
      repeatability = diag(V) / (diag(V) + diag(Sw[traits, traits, drop = FALSE])),
      cov_boldness_exploration = V[1, 2])
  })
  do.call(rbind, out)
}

plot_multivariate <- function(tab, path) {
  p <- ggplot(tab, aes(temp_c, repeatability, colour = trait, linetype = trait)) +
    geom_vline(xintercept = 0, linetype = "dashed", colour = "grey70") +
    geom_line(linewidth = 1.2) + scale_y_continuous(limits = c(0, 1)) +
    scale_colour_manual(values = c(activity = "#009E73", boldness = "#0072B2", exploration = "#D55E00")) +
    labs(x = "Temperature relative to reference", y = "Pointwise repeatability",
         colour = "Trait", linetype = "Trait",
         title = "Three traits, three temperature-dependent patterns")
  save_teaching_plot(p, path)
}

plot_covariance <- function(tab, path) {
  p <- ggplot(tab[tab$trait == "boldness", ], aes(temp_c, cov_boldness_exploration)) +
    geom_hline(yintercept = 0, linetype = "dashed", colour = "grey60") +
    geom_vline(xintercept = 0, linetype = "dashed", colour = "grey60") +
    geom_line(colour = "#009E73", linewidth = 1.2) +
    labs(x = "Temperature relative to reference", y = "Among-individual covariance",
         title = "Boldness and exploration can covary differently",
         subtitle = "The fitted association depends on the temperature at which it is evaluated")
  save_teaching_plot(p, path)
}

run_multivariate <- function() {
  x <- make_multivariate(); started <- proc.time()[["elapsed"]]; fit <- fit_multivariate(x$data); elapsed <- proc.time()[["elapsed"]] - started
  health <- gllvmTMB::check_gllvmTMB(fit)
  utils::write.csv(health, file.path(out_analysis, "multivariate-fit-health.csv"), row.names = FALSE)
  h <- fit$fit_health
  require_healthy_fit(h$convergence, h$pd_hessian, h$max_gradient, "Multivariate")
  Sb <- gllvmTMB::extract_Sigma(fit, level = "unit_slope", part = "total")$Sigma
  Sw <- gllvmTMB::extract_Sigma(fit, level = "unit_obs", part = "total")$Sigma
  tab <- multivariate_curves(Sb, Sw, x$traits)
  utils::write.csv(x$data, file.path(out_analysis, "multivariate-input.csv"), row.names = FALSE)
  utils::write.csv(tab, file.path(out_analysis, "multivariate-curves.csv"), row.names = FALSE)
  utils::write.csv(Sb, file.path(out_analysis, "multivariate-unit-slope-covariance.csv"))
  utils::write.csv(Sw, file.path(out_analysis, "multivariate-session-covariance.csv"))
  plot_multivariate(tab, file.path(out_fig, "multivariate-repeatability.png"))
  plot_covariance(tab, file.path(out_fig, "multivariate-covariance.png"))
  elapsed
}

# Sex is constant within an individual.  This is a group-specific covariance
# example, not a reaction norm: fit each sex directly so the estimands are
# unambiguous female and male B/W covariance matrices.
make_sex_groups <- function(n_per_sex = 60L, n_rep = 7L, seed = 1L) {
  set.seed(seed)
  traits <- c("boldness", "exploration", "activity")
  B_female <- matrix(c(.55,.22,.12, .22,.45,.15, .12,.15,.36), 3, byrow = TRUE)
  B_male <- matrix(c(.35,-.10,.08, -.10,.65,.18, .08,.18,.48), 3, byrow = TRUE)
  W <- matrix(c(.25,.08,.04, .08,.30,.07, .04,.07,.28), 3, byrow = TRUE)
  make_one <- function(sex, B) {
    u <- MASS::mvrnorm(n_per_sex, rep(0, 3), B)
    w <- MASS::mvrnorm(n_per_sex * n_rep, rep(0, 3), W)
    z <- expand.grid(individual = factor(seq_len(n_per_sex)), occasion = seq_len(n_rep),
                     trait = traits, KEEP.OUT.ATTRS = FALSE)
    z$sex <- sex
    z$trait <- factor(z$trait, levels = traits)
    z$occasion_id <- interaction(z$individual, z$occasion, drop = TRUE)
    ii <- as.integer(z$individual); jj <- as.integer(z$occasion_id); tt <- as.integer(z$trait)
    z$value <- c(1.0, 1.2, .8)[tt] + u[cbind(ii, tt)] + w[cbind(jj, tt)]
    z
  }
  list(data = rbind(make_one("female", B_female), make_one("male", B_male)), traits = traits)
}

fit_sex_group <- function(d) {
  first <- glmmTMB::glmmTMB(
    value ~ 0 + trait +
      (0 + trait | individual) + (0 + trait | occasion_id),
    family = gaussian(), dispformula = ~ 0, data = d
  )
  # A BFGS polish begins from the first fit, rather than a new default start.
  update(first,
    start = list(beta = unname(glmmTMB::fixef(first)$cond),
                 theta = unname(glmmTMB::getME(first, "theta"))),
    control = glmmTMB::glmmTMBControl(
      optimizer = optim, optArgs = list(method = "BFGS"),
      optCtrl = list(maxit = 5000, reltol = 1e-12)
    )
  )
}

sum_group_blocks <- function(fit, prefix) {
  vc <- glmmTMB::VarCorr(fit)$cond
  blocks <- vc[startsWith(names(vc), prefix)]
  if (length(blocks) != 1L) stop("Expected one unstructured covariance block for ", prefix)
  as.matrix(blocks[[1]])
}

sex_group_summary <- function(fits, traits) {
  do.call(rbind, lapply(names(fits), function(sex) {
    B <- sum_group_blocks(fits[[sex]], "individual")
    W <- sum_group_blocks(fits[[sex]], "occasion_id")
    data.frame(sex = sex, trait = traits, between_variance = diag(B),
               within_variance = diag(W), repeatability = diag(B) / diag(B + W))
  }))
}

sex_correlation_summary <- function(fits) {
  do.call(rbind, lapply(names(fits), function(sex) {
    B <- sum_group_blocks(fits[[sex]], "individual")
    C <- cov2cor(B)
    data.frame(sex = sex,
               trait_1 = sub("^trait", "", rownames(C)[c(1, 1, 2)]),
               trait_2 = sub("^trait", "", colnames(C)[c(2, 3, 3)]),
               correlation = C[cbind(c(1, 1, 2), c(2, 3, 3))])
  }))
}

plot_sex_repeatability <- function(tab, path) {
  p <- ggplot(tab, aes(trait, repeatability, colour = sex, shape = sex, group = sex)) +
    geom_point(size = 3, position = position_dodge(width = .35)) +
    scale_colour_manual(values = c(female = "#CC79A7", male = "#0072B2")) +
    scale_y_continuous(limits = c(0, 1)) +
    labs(x = "Trait", y = "Group-specific repeatability", colour = "Sex", shape = "Sex",
         title = "Repeatability can differ between groups")
  save_teaching_plot(p, path)
}

plot_sex_correlations <- function(tab, path) {
  tab$pair <- factor(paste(tab$trait_1, tab$trait_2, sep = "--"),
                     levels = c("boldness--exploration", "boldness--activity", "exploration--activity"),
                     labels = c("Boldness-exploration", "Boldness-activity", "Exploration-activity"))
  p <- ggplot(tab, aes(pair, correlation, colour = sex, shape = sex, group = sex)) +
    geom_hline(yintercept = 0, linetype = "dashed", colour = "grey60") +
    geom_point(size = 3, position = position_dodge(width = .35)) +
    scale_colour_manual(values = c(female = "#CC79A7", male = "#0072B2")) +
    coord_cartesian(ylim = c(-1, 1)) +
    labs(x = "Among-individual trait pair", y = "Correlation", colour = "Sex", shape = "Sex",
         title = "Behavioural-syndrome correlations can differ between groups")
  save_teaching_plot(p, path)
}

run_sex_groups <- function() {
  x <- make_sex_groups(); started <- proc.time()[["elapsed"]]
  fits <- lapply(split(x$data, x$data$sex), fit_sex_group)
  elapsed <- proc.time()[["elapsed"]] - started
  if (!all(vapply(fits, function(f) isTRUE(f$sdr$pdHess) && f$fit$convergence == 0 && max(abs(f$obj$gr(f$fit$par))) <= .01, logical(1)))) {
    stop("A sex-group fit did not pass the declared convergence, curvature, and gradient checks.")
  }
  summary <- sex_group_summary(fits, x$traits)
  correlations <- sex_correlation_summary(fits)
  health <- data.frame(sex = names(fits), convergence = vapply(fits, function(f) f$fit$convergence, numeric(1)),
                       pd_hessian = vapply(fits, function(f) isTRUE(f$sdr$pdHess), logical(1)),
                       max_gradient = vapply(fits, function(f) max(abs(f$obj$gr(f$fit$par))), numeric(1)))
  utils::write.csv(x$data, file.path(out_analysis, "sex-group-input.csv"), row.names = FALSE)
  utils::write.csv(summary, file.path(out_analysis, "sex-group-repeatability.csv"), row.names = FALSE)
  utils::write.csv(correlations, file.path(out_analysis, "sex-group-correlations.csv"), row.names = FALSE)
  utils::write.csv(health, file.path(out_analysis, "sex-group-fit-health.csv"), row.names = FALSE)
  plot_sex_repeatability(summary, file.path(out_fig, "sex-group-repeatability.png"))
  plot_sex_correlations(correlations, file.path(out_fig, "sex-group-correlations.png"))
  elapsed
}

u <- run_univariate()
mv_seconds <- run_multivariate()
sex_seconds <- run_sex_groups()
meta <- data.frame(component = c("univariate_first_fit", "multivariate_fit", "sex_group_fits"),
                   seconds = c(u$elapsed, mv_seconds, sex_seconds))
utils::write.csv(meta, file.path(out_analysis, "runtime.csv"), row.names = FALSE)
file.copy(list.files(out_analysis, full.names = TRUE), out_download, overwrite = TRUE)
file.copy(list.files(out_fig, full.names = TRUE), out_download, overwrite = TRUE)
file.copy(file.path(root, "analysis", "extensions", "random-slopes.R"), out_download, overwrite = TRUE)
