#!/usr/bin/env Rscript
# Rebuild the dog ordination, communality, and repeatability figure.
#
# Inputs are ID-free, fit-derived score coordinates and aggregate summary
# tables. The source bootstrap draws and fitted model objects are not included.
# This script recreates the displayed figure; it does not rerun model fitting or
# the parametric bootstrap.
#
# Dependencies: ggplot2, patchwork.
# From the repository root:
#   Rscript --vanilla tutorial/downloads/figure-gallery/make-figure-4.R
# Outputs: tutorial/figures/figure-gallery/figure-4.png and .pdf

suppressPackageStartupMessages({
  library(ggplot2)
  library(patchwork)
})

data_dir <- "tutorial/downloads/figure-gallery/data"
out_dir <- "tutorial/figures/figure-gallery"
dir.create(out_dir, recursive = TRUE, showWarnings = FALSE)

scores <- read.csv(file.path(data_dir, "dogs-figure4-scores-id-free.csv"),
                   stringsAsFactors = FALSE)
loadings <- read.csv(file.path(data_dir, "dogs-figure4-loadings.csv"),
                     stringsAsFactors = FALSE)
key <- read.csv(file.path(data_dir, "dogs-figure4-trait-key.csv"),
                stringsAsFactors = FALSE)
comm <- read.csv(file.path(data_dir, "dogs-figure4-communalities.csv"),
                 stringsAsFactors = FALSE)
repeatability <- read.csv(file.path(data_dir, "dogs-figure4-repeatability.csv"),
                          stringsAsFactors = FALSE)

expected_traits <- key$trait
stopifnot(nrow(key) == 10L,
          identical(key$number, 1:10),
          "trait_label" %in% names(key),
          nrow(scores) == 1000L,
          identical(as.integer(table(factor(scores$level,
                                             levels = c("B", "W")))),
                    c(100L, 900L)),
          identical(names(scores), c("level", "axis1", "axis2", "axis3")),
          !anyDuplicated(loadings[c("level", "trait")]),
          nrow(loadings) == 20L,
          setequal(loadings$trait, expected_traits),
          nrow(comm) == 30L,
          nrow(repeatability) == 10L,
          all(comm$retained_paired_refits == 1095L),
          all(repeatability$retained_paired_refits == 1095L),
          all(is.finite(as.matrix(scores[, c("axis1", "axis2", "axis3")]))) ,
          all(is.finite(comm$lower_95)), all(is.finite(comm$upper_95)),
          all(comm$lower_95 < comm$upper_95),
          all(comm$lower_95 <= comm$estimate & comm$estimate <= comm$upper_95),
          all(repeatability$lower_95 <= repeatability$estimate &
                repeatability$estimate <= repeatability$upper_95))

axes <- list(c(1L, 2L), c(1L, 3L), c(2L, 3L))
axis_names <- c("Axes 1-2", "Axes 1-3", "Axes 2-3")
score_panels <- list()
loading_panels <- list()
for (lev in c("B", "W")) {
  s <- scores[scores$level == lev, , drop = FALSE]
  l <- loadings[loadings$level == lev, , drop = FALSE]
  l <- l[match(expected_traits, l$trait), , drop = FALSE]
  stopifnot(nrow(s) == if (lev == "B") 100L else 900L,
            identical(l$trait, expected_traits),
            setequal(names(l), c("level", "trait", "axis1", "axis2", "axis3")))

  for (k in seq_along(axes)) {
    ax <- axes[[k]]
    pair <- axis_names[[k]]
    score_panels[[paste(lev, pair)]] <- data.frame(
      level = lev, pair = pair,
      x = s[[paste0("axis", ax[[1]])]],
      y = s[[paste0("axis", ax[[2]])]]
    )
    loading_panels[[paste(lev, pair)]] <- data.frame(
      level = lev, pair = pair,
      trait_number = key$number,
      x = l[[paste0("axis", ax[[1]])]] * 5,
      y = l[[paste0("axis", ax[[2]])]] * 5
    )
  }
}
score_panels <- do.call(rbind, score_panels)
loading_panels <- do.call(rbind, loading_panels)
score_panels$pair <- factor(score_panels$pair, levels = axis_names)
loading_panels$pair <- factor(loading_panels$pair, levels = axis_names)
loading_panels$label_x <- NA_real_
loading_panels$label_y <- NA_real_
for (lev in c("B", "W")) for (pair in axis_names) {
  idx <- which(loading_panels$level == lev & loading_panels$pair == pair)
  ordering <- idx[order(atan2(loading_panels$y[idx], loading_panels$x[idx]))]
  angle <- seq(-pi, pi, length.out = 11L)[-11L]
  loading_panels$label_x[ordering] <- 4.15 * cos(angle)
  loading_panels$label_y[ordering] <- 4.15 * sin(angle)
}

ordination_panel <- function(lev, title, point_colour) {
  s <- score_panels[score_panels$level == lev, , drop = FALSE]
  l <- loading_panels[loading_panels$level == lev, , drop = FALSE]
  highlighted <- subset(l, level == "B" & pair == axis_names[[2]] &
                          trait_number %in% c(3L, 7L))
  highlighted$line <- ifelse(highlighted$trait_number == 3L, "solid", "dashed")
  ggplot() +
    geom_hline(yintercept = 0, colour = "grey82", linewidth = 0.35) +
    geom_vline(xintercept = 0, colour = "grey82", linewidth = 0.35) +
    geom_point(data = s, aes(x, y), colour = point_colour,
               alpha = if (lev == "B") 0.36 else 0.13,
               size = if (lev == "B") 0.38 else 0.24) +
    geom_segment(data = l, aes(x = 0, y = 0, xend = x, yend = y),
                 colour = "#26343B", linewidth = 0.38,
                 arrow = grid::arrow(length = grid::unit(1.2, "mm"))) +
    geom_segment(data = l,
                 aes(x = x, y = y, xend = label_x, yend = label_y),
                 colour = "grey55", linewidth = 0.20) +
    geom_segment(data = highlighted,
                 aes(x = 0, y = 0, xend = x, yend = y,
                     linetype = line),
                 colour = "#17252D", linewidth = 0.65, show.legend = FALSE,
                 arrow = grid::arrow(length = grid::unit(1.4, "mm"))) +
    geom_segment(data = highlighted,
                 aes(x = x, y = y, xend = label_x, yend = label_y,
                     linetype = line),
                 colour = "#17252D", linewidth = 0.45, show.legend = FALSE) +
    scale_linetype_identity() +
    geom_label(data = l,
               aes(x = label_x, y = label_y,
                   label = as.character(trait_number)),
               size = 2.25, linewidth = 0, label.padding =
                 grid::unit(0.04, "lines"), fill = "white",
               colour = "#17252D") +
    facet_wrap(~pair, nrow = 1) +
    coord_equal(xlim = c(-5, 5), ylim = c(-5, 5), clip = "off") +
    labs(title = title,
         x = "Conditional score (arrows show loadings scaled by 5)",
         y = "Conditional score") +
    theme_minimal(base_size = 8.5) +
    theme(panel.grid.minor = element_blank(),
          strip.text = element_text(face = "bold", size = 8),
          plot.title = element_text(face = "bold", size = 10),
          plot.margin = margin(4, 7, 4, 4))
}

comm <- subset(comm, level %in% c("Between dogs", "Within dogs"))
comm$trait <- factor(comm$trait, levels = rev(key$trait_label))
comm$level <- factor(comm$level, levels = c("Between dogs", "Within dogs"))
stopifnot(nrow(comm) == 20L, !anyNA(comm$trait), !anyNA(comm$level))
communality_panel <- ggplot(comm, aes(x = estimate, y = trait,
                                      colour = level, shape = level)) +
  geom_point(position = position_dodge(width = 0.56), size = 1.6) +
  geom_errorbar(aes(xmin = lower_95, xmax = upper_95), orientation = "y",
                position = position_dodge(width = 0.56),
                width = 0.12, linewidth = 0.68) +
  scale_colour_manual(values = c("Between dogs" = "#0072B2",
                                 "Within dogs" = "#D55E00")) +
  scale_shape_manual(values = c("Between dogs" = 16,
                                "Within dogs" = 17)) +
  scale_x_continuous(breaks = seq(0, 1, 0.25),
                     expand = expansion(mult = c(0, 0))) +
  coord_cartesian(xlim = c(0, 1.04)) +
  labs(title = "C  Communality",
       x = "Shared variance / variance at this level",
       y = NULL, colour = NULL, shape = NULL) +
  theme_minimal(base_size = 8.5) +
  theme(panel.grid.minor = element_blank(),
        plot.title = element_text(face = "bold", size = 10),
        legend.position = "bottom")

repeatability$trait <- factor(repeatability$trait,
                              levels = rev(key$trait_label))
stopifnot(!anyNA(repeatability$trait))
repeatability_panel <- ggplot(repeatability,
                              aes(x = estimate, y = trait)) +
  geom_segment(aes(x = lower_95, xend = upper_95, yend = trait),
               colour = "#0072B2", linewidth = 0.62) +
  geom_point(colour = "#25333D", shape = 18, size = 1.8) +
  scale_x_continuous(breaks = seq(0, 1, 0.25),
                     expand = expansion(mult = c(0, 0))) +
  coord_cartesian(xlim = c(0, 1.04)) +
  labs(title = "D  Repeatability",
       x = "Between / (between + within variance)", y = NULL) +
  theme_minimal(base_size = 8.5) +
  theme(panel.grid.minor = element_blank(),
        plot.title = element_text(face = "bold", size = 10),
        # Panels C and D share trait rows. Keep one readable trait-name column
        # on C rather than repeating long labels beside the narrow D panel.
        axis.text.y = element_blank(),
        axis.ticks.y = element_blank())

key_lines <- split(seq_len(nrow(key)), ceiling(seq_len(nrow(key)) / 5))
trait_key <- paste(vapply(key_lines, function(i) {
  paste(sprintf("%d %s", key$number[i], key$trait_label[i]), collapse = "   |   ")
}, character(1)), collapse = "\n")
figure <- ordination_panel("B", "A  Between-dog ordination", "#17699C") /
  ordination_panel("W", "B  Within-dog ordination", "#BD5C14") /
  (communality_panel | repeatability_panel) +
  plot_layout(heights = c(1, 1, 0.82)) +
  plot_annotation(caption = paste("Trait key:", trait_key)) &
  theme(plot.caption = element_text(size = 7.8, hjust = 0,
                                    margin = margin(t = 5)))

# Render both formats before replacing either existing figure.
scratch <- tempfile("figure-4-", tmpdir = out_dir)
dir.create(scratch)
on_error <- function(message) {
  if (length(published)) unlink(file.path(out_dir, published))
  restored <- vapply(backed_up, function(name) {
    file.rename(file.path(scratch, paste0("previous-", name)),
                file.path(out_dir, name))
  }, logical(1))
  if (all(restored)) unlink(scratch, recursive = TRUE)
  if (!all(restored)) {
    stop(message, ". Recovery files are in ", scratch, call. = FALSE)
  }
  stop(message, call. = FALSE)
}

# Move the PDF first so a PDF locked by a viewer leaves both outputs alone.
files <- c("figure-4.pdf", "figure-4.png")
backed_up <- published <- character()
tryCatch({
  ggsave(file.path(scratch, "figure-4.png"), figure,
         width = 7.2, height = 9.3, dpi = 300, bg = "white")
  ggsave(file.path(scratch, "figure-4.pdf"), figure,
         width = 7.2, height = 9.3, device = cairo_pdf, bg = "white")
  for (name in files) {
    original <- file.path(out_dir, name)
    if (file.exists(original)) {
      if (!file.rename(original, file.path(scratch, paste0("previous-", name)))) {
        stop("Could not move the existing ", name, ". Close it and retry.")
      }
      backed_up <- c(backed_up, name)
    }
  }
  for (name in files) {
    if (!file.rename(file.path(scratch, name), file.path(out_dir, name))) {
      stop("Could not install the new ", name)
    }
    published <- c(published, name)
  }
}, error = function(err) on_error(conditionMessage(err)))
unlink(scratch, recursive = TRUE)

cat("PASS FIGURE 4: 100 between-dog and 900 within-dog conditional scores;",
    "all three projections per level; communality before repeatability;",
    "1095 archived paired refits per interval summary.\n")
