#!/usr/bin/env Rscript
# Prepare the nine-trait, intercept-only Arctic charr teaching data.
# Run from the repository root. The original workbook is bundled in tutorial/data/.
root <- normalizePath(getwd(), mustWork = TRUE)
if (!requireNamespace("digest", quietly = TRUE)) stop("Install digest to record source checksums.")
input <- file.path(root, "tutorial", "data", "arctic-charr-original.xlsx")
output_dir <- file.path(root, "analysis", "cache", "tutorial-data")
audit_path <- file.path(root, "tutorial", "downloads", "charr-nine-data-audit.csv")
if (!requireNamespace("readxl", quietly = TRUE)) stop("Install readxl to read the bundled workbook.")
if (!file.exists(input)) stop("Bundled Arctic charr workbook not found: ", input)

raw <- as.data.frame(readxl::read_excel(input, sheet = "Sheet 1 - Tableau 1"))
traits <- c("Dtot", "Exit.time", "Border.duration", "Center.freq",
            "Center.duration", "Shelter.freq", "Entry.freq",
            "Entry.duration", "Ang.vel")
required <- c("Morph", "Indiv", "Replicate", "Dtot", traits)
if (!all(required %in% names(raw))) stop("The workbook is missing a required field.")
if (nrow(raw) != 2370L || anyNA(raw[c("Morph", "Indiv", "Replicate")]))
  stop("Unexpected charr workbook row count or missing grouping fields.")

# Morph is part of the identity because Indiv labels recur across morphs.
raw$individual <- interaction(raw$Morph, raw$Indiv, drop = TRUE, lex.order = TRUE)
raw$occasion <- interaction(raw$individual, raw$Replicate,
                            drop = TRUE, lex.order = TRUE)
if (nlevels(raw$individual) != 1185L || nlevels(raw$occasion) != 2370L ||
    any(table(raw$individual) != 2L) || anyDuplicated(raw$occasion))
  stop("Expected two replicate records for each of 1,185 fish.")

responses <- raw[traits]
responses$Ang.vel <- suppressWarnings(as.numeric(as.character(responses$Ang.vel)))
responses$Ang.vel[raw$Dtot <= 0] <- NA_real_
responses$Border.duration[responses$Border.duration < 0] <- NA_real_
observed <- vapply(responses, function(x) sum(!is.na(x)), integer(1))
expected <- c(2370L, 2370L, 2368L, 2370L, 2370L, 2370L, 2370L, 2370L, 2320L)
if (!identical(unname(observed), expected))
  stop("Charr response counts differ from the documented 21,278 observed values.")

z_observed <- function(x) {
  ok <- !is.na(x)
  x[ok] <- (x[ok] - mean(x[ok])) / stats::sd(x[ok])
  x
}
for (trait in traits) responses[[trait]] <- z_observed(responses[[trait]])
wide <- data.frame(individual = raw$individual, occasion = raw$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$individual <- factor(long$individual)
long$occasion <- factor(long$occasion)
long$trait <- factor(long$trait, levels = traits)
rownames(long) <- NULL
if (nrow(long) != 21278L) stop("Unexpected charr long-data row count.")

dir.create(output_dir, recursive = TRUE, showWarnings = FALSE)
saveRDS(list(wide = wide, long = long, traits = traits,
             source_sha256 = digest::digest(file = input, algo = "sha256")),
        file.path(output_dir, "charr-nine-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 charr preparation: 1,185 fish; 2,370 occasions; 9 traits; 21,278 observed values.\n")
