# Recreate manuscript Figure 3 from bundled, aggregate dog correlation results.
# Run from the repository root:
#   Rscript --vanilla tutorial/downloads/figure-gallery/make-figure-3.R
# This script does not fit models or regenerate bootstrap intervals.

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

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

correlations <- read.csv(
  file.path(input_dir, "dogs-correlations.csv"),
  stringsAsFactors = FALSE,
  check.names = FALSE
)
trait_key <- read.csv(
  file.path(input_dir, "dogs-trait-key.csv"),
  stringsAsFactors = FALSE,
  check.names = FALSE
)

expected_traits <- c(
  "Stranger-directed aggression",
  "Dog-directed aggression",
  "Dog-directed fear",
  "Trainability",
  "Chasing",
  "Nonsocial fear",
  "Touch sensitivity",
  "Excitability",
  "Attachment and attention seeking",
  "Energy"
)
expected_levels <- c("Between dogs", "Within dogs")

stopifnot(
  nrow(correlations) == 90L,
  nrow(trait_key) == 10L,
  identical(trait_key$number, 1:10),
  identical(trait_key$trait, expected_traits),
  setequal(unique(correlations$level), expected_levels),
  all(correlations$retained_paired_refits == 1095L),
  all(correlations$trait1_number < correlations$trait2_number),
  !anyDuplicated(correlations[c("level", "trait1_number", "trait2_number")]),
  all(is.finite(correlations$estimate)),
  all(is.finite(correlations$lower_95)),
  all(is.finite(correlations$upper_95)),
  all(correlations$lower_95 <= correlations$estimate),
  all(correlations$estimate <= correlations$upper_95),
  all(correlations$lower_95 >= -1),
  all(correlations$upper_95 <= 1)
)

# Check the table’s labels against the explicit key before using their order.
for (i in seq_len(nrow(correlations))) {
  row <- correlations[i, ]
  stopifnot(
    identical(row$trait1, expected_traits[row$trait1_number]),
    identical(row$trait2, expected_traits[row$trait2_number])
  )
}

# Use a common precision in the figure. Sign markers use unrounded endpoints.
format_cell <- function(x) {
  rounded <- round(x, 3)
  sub("^(-?)0[.]", "\\1.", sprintf("%.3f", ifelse(rounded == 0, 0, rounded)))
}

# Expand each unordered pair into two matrix cells: estimates above the
# diagonal and lower/upper percentile limits below it.
panel_levels <- c("Between dogs", "Within dogs")
cell_rows <- vector("list", nrow(correlations) * 2L)
out <- 0L
for (k in seq_len(nrow(correlations))) {
  r <- correlations[k, ]
  i <- r$trait1_number
  j <- r$trait2_number
  estimate_text <- paste0(
    format_cell(r$estimate),
    if (r$lower_95 > 0 || r$upper_95 < 0) "*" else ""
  )
  interval_text <- paste(format_cell(r$lower_95), format_cell(r$upper_95), sep = "\n")
  out <- out + 1L
  cell_rows[[out]] <- data.frame(
    level = r$level, i = i, j = j, estimate = r$estimate,
    label = estimate_text, stringsAsFactors = FALSE
  )
  out <- out + 1L
  cell_rows[[out]] <- data.frame(
    level = r$level, i = j, j = i, estimate = NA_real_,
    label = interval_text, stringsAsFactors = FALSE
  )
}
cells <- do.call(rbind, cell_rows)
diagonal <- expand.grid(i = 1:10, level = panel_levels, stringsAsFactors = FALSE)
diagonal$j <- diagonal$i
diagonal$estimate <- NA_real_
diagonal$label <- ""
cells <- rbind(cells, diagonal)
cells$level <- factor(cells$level, levels = panel_levels)
cells$x <- factor(cells$j, levels = 1:10)
cells$y <- factor(cells$i, levels = 10:1)

matrix_panel <- function(level, title) {
  panel_cells <- cells[as.character(cells$level) == level, ]
  ggplot(panel_cells, aes(x = x, y = y)) +
  geom_tile(aes(fill = estimate), colour = "white", linewidth = 0.35) +
  geom_text(aes(label = label), size = 3.0, lineheight = 0.9, colour = "grey10") +
  coord_fixed() +
  scale_fill_gradient2(
    low = "#bb675d", mid = "#fafafa", high = "#6595b9",
    limits = c(-1, 1), na.value = "grey94", guide = "none"
  ) +
  scale_x_discrete(labels = setNames(expected_traits, as.character(1:10))) +
  scale_y_discrete(labels = setNames(expected_traits, as.character(1:10))) +
  labs(title = title, x = NULL, y = NULL) +
  theme_minimal(base_size = 10) +
  theme(
    panel.grid = element_blank(),
    axis.text.y = element_text(colour = "grey15", size = 8.5),
    axis.text.x = element_text(
      colour = "grey15", size = 8, angle = 45, hjust = 1, vjust = 1
    ),
    axis.ticks = element_blank(),
    plot.title = element_text(face = "bold", size = 11, hjust = 0),
    plot.margin = margin(8, 12, 8, 12)
  )
}

between <- matrix_panel("Between dogs", "A  Between dogs") +
  theme(axis.text.x = element_blank(), axis.ticks.x = element_blank())
within <- matrix_panel("Within dogs", "B  Within dogs")
p <- between / within + plot_layout(heights = c(1, 1))

ggsave(
  file.path(output_dir, "figure-3-dog-correlations.png"),
  p, width = 10, height = 13.4, units = "in", dpi = 240,
  bg = "white"
)
ggsave(
  file.path(output_dir, "figure-3-dog-correlations.pdf"),
  p, width = 10, height = 13.4, units = "in", device = grDevices::pdf,
  bg = "white"
)

cat("PASS GFG-F3: 90 aggregate pairs, 180 off-diagonal cells, 10 keyed traits; outputs written.\n")
