#!/usr/bin/env Rscript
# Prepare the six-trait, intercept-only red-knot teaching data.
# Run from the repository root. Missing response cells remain missing.
root <- normalizePath(getwd(), mustWork = TRUE)
if (!requireNamespace("digest", quietly = TRUE)) stop("Install digest to record source checksums.")
input <- file.path(root, "tutorial", "data", "red-knots-original.csv")
output_dir <- file.path(root, "analysis", "cache", "tutorial-data")
audit_path <- file.path(root, "tutorial", "downloads", "red-knots-six-data-audit.csv")
if (!file.exists(input)) stop("Bundled red-knot data not found: ", input)
raw <- utils::read.csv(input, check.names = FALSE, fileEncoding = "UTF-8-BOM")
if (names(raw)[1L] == "") raw <- raw[-1L]
# Match the frozen fit trait order used by the recorded glmmTMB/gllvmTMB runs.
traits <- c("mass", "gizzard", "BMR_W", "exploration", "activity", "feeding")
required <- c("RNR", "year", "diet", "replicate", traits)
if (!all(required %in% names(raw)) || nrow(raw) != 464L ||
    length(unique(raw$RNR)) != 58L || anyNA(raw[c("RNR", "year", "diet", "replicate")]))
  stop("Unexpected red-knot source rows or grouping fields.")
if (any(vapply(raw[c("activity", "feeding", "exploration")],
               function(x) any(x < 0 | x > 1, na.rm = TRUE), logical(1))))
  stop("A proportion response falls outside [0, 1].")
key <- paste(raw$RNR, raw$year, raw$replicate, sep = "|")
if (anyDuplicated(key)) stop("Duplicate red-knot individual-period key.")

eps <- 0.001
responses <- raw[traits]
for (trait in c("activity", "feeding", "exploration")) {
  y <- responses[[trait]]
  ok <- !is.na(y)
  y[ok] <- stats::qlogis(pmin(1 - eps, pmax(eps, y[ok])))
  responses[[trait]] <- y
}
for (trait in traits) {
  x <- responses[[trait]]; ok <- !is.na(x)
  x[ok] <- (x[ok] - mean(x[ok])) / stats::sd(x[ok])
  responses[[trait]] <- x
}
individual <- factor(raw$RNR)
occasion <- interaction(individual, raw$year, raw$replicate,
                        drop = TRUE, sep = "__")
wide <- data.frame(individual, occasion, responses, check.names = FALSE)
long <- do.call(rbind, lapply(traits, function(trait) {
  data.frame(individual = wide$individual, occasion = wide$occasion,
             trait = trait, value = wide[[trait]])
}))
long <- long[!is.na(long$value), , drop = FALSE]
long$trait <- factor(long$trait, levels = traits)
rownames(long) <- NULL
observed <- vapply(responses, function(x) sum(!is.na(x)), integer(1))
if (sum(observed) != 2101L || nlevels(individual) != 58L ||
    nlevels(occasion) != 464L || nrow(long) != 2101L)
  stop("Red-knot six-trait mask differs from the registered analysis.")

dir.create(output_dir, recursive = TRUE, showWarnings = FALSE)
saveRDS(list(wide = wide, long = long, traits = traits, epsilon = eps,
             source_sha256 = digest::digest(file = input, algo = "sha256")),
        file.path(output_dir, "red-knots-six-intercept.rds"), version = 3)
audit <- data.frame(trait = traits, observed = unname(observed),
                    missing = nrow(raw) - unname(observed),
                    source_sha256 = digest::digest(file = input, algo = "sha256"))
utils::write.csv(audit, audit_path, row.names = FALSE)
cat("PASS red-knot preparation: 58 birds; 464 periods; 6 traits; 2,101 observed values; no missing responses imputed.\n")
