#!/usr/bin/env Rscript
# Prepare the ten-score, year-adjusted dog teaching data from the bundled file.
# Run from the repository root. The bundled dog_id values are randomized pseudonyms.
root <- normalizePath(getwd(), mustWork = TRUE)
if (!requireNamespace("digest", quietly = TRUE)) stop("Install digest to record source checksums.")
input <- file.path(root, "tutorial", "data", "dogs-modified.csv")
output_dir <- file.path(root, "analysis", "cache", "tutorial-data")
audit_path <- file.path(root, "tutorial", "downloads", "dogs-ten-data-audit.csv")
if (!file.exists(input)) stop("Bundled modified dog data not found: ", input)

raw <- utils::read.csv(input, check.names = FALSE, fileEncoding = "UTF-8-BOM")
trimmed <- trimws(names(raw))
if (anyDuplicated(trimmed)) stop("Trimming source headers would create duplicate names.")
names(raw) <- trimmed
traits_all <- grep("^score_", names(raw), value = TRUE)
if (!all(c("dog_id", "study_year") %in% names(raw)) ||
    any(c("subject_id", "source_id", "record_date", "date") %in% names(raw)) ||
    !all(grepl("^[0-9a-f]{32}$", raw$dog_id)) ||
    length(traits_all) != 14L || nrow(raw) != 900L ||
    length(unique(raw$dog_id)) != 100L ||
    anyDuplicated(raw[c("dog_id", "study_year")]) ||
    !identical(sort(unique(raw$study_year)), 0:8) ||
    anyNA(raw[c("dog_id", "study_year", traits_all)]))
  stop("Unexpected or incomplete bundled dog panel.")
if (!all(vapply(raw[traits_all], function(x) all(x >= 0 & x <= 4), logical(1))))
  stop("A bundled composite score falls outside its documented 0--4 range.")

# Retain the ten scores with fewer than half their responses exactly zero.
zero_fraction <- vapply(raw[traits_all], function(x) mean(x == 0), numeric(1))
traits <- traits_all[zero_fraction < 0.5]
if (length(traits) != 10L) stop("The documented zero-frequency rule did not select ten scores.")
wide <- raw[c("dog_id", "study_year", traits)]
wide$individual <- factor(wide$dog_id)
wide$year_in_study <- wide$study_year
wide$occasion <- interaction(wide$individual, wide$year_in_study,
                             drop = TRUE, sep = "__")
wide$year_c <- (wide$year_in_study - 4) / sqrt(60 / 9)
for (trait in traits) wide[[trait]] <- as.numeric(scale(wide[[trait]]))
long <- do.call(rbind, lapply(traits, function(trait) {
  data.frame(individual = wide$individual, occasion = wide$occasion,
             year_in_study = wide$year_in_study, year_c = wide$year_c,
             trait = trait, value = wide[[trait]])
}))
long$trait <- factor(long$trait, levels = traits)
rownames(long) <- NULL
X <- stats::model.matrix(~ 0 + trait + trait:year_c, data = long)
if (nrow(long) != 9000L || nlevels(long$individual) != 100L ||
    nlevels(long$occasion) != 900L || ncol(X) != 20L || qr(X)$rank != 20L)
  stop("The ten-score dog design did not reproduce the declared data structure.")

dir.create(output_dir, recursive = TRUE, showWarnings = FALSE)
saveRDS(list(long = long, traits = traits, traits_all = traits_all,
             zero_fraction = zero_fraction, fixed_design = X,
             source_sha256 = digest::digest(file = input, algo = "sha256")),
        file.path(output_dir, "dogs-ten-year-adjusted.rds"), version = 3)
audit <- data.frame(trait = traits_all, zero_count = vapply(raw[traits_all],
  function(x) sum(x == 0), integer(1)), zero_fraction = zero_fraction,
  retained_for_ten_trait_example = traits_all %in% traits)
utils::write.csv(audit, audit_path, row.names = FALSE)
cat("PASS dog preparation: 100 randomized pseudonymous dog IDs; 900 records; 10 selected traits; 9,000 values; fixed-design rank 20.\n")
