#!/usr/bin/env Rscript

# quantbayes: full development check script
# This script performs:
# 1. Documentation generation
# 2. R CMD check in CRAN mode
# 3. Load package via load_all
# 4. Test core functionality
# 5. Test plots with defaults, palettes, highlight points
# 6. Test helper functions
# 7. Test error handling

library(devtools)

# Path to the package directory (must contain DESCRIPTION)
pkg_path <- "~/so/src/quantbayes_package"

# 1. DOCUMENT PACKAGE ----
document(pkg_path)

# 2. CRAN-STYLE CHECK ----
check(pkg_path, cran = TRUE)

# 3. LOAD PACKAGE ----
load_all(pkg_path)
set.seed(666)

# 4. LOAD DEMO DATA ----
data(core_test_data, package = "quantbayes")
print(head(core_test_data))

# Construct matrix
x <- as.matrix(core_test_data[, -1])
rownames(x) <- core_test_data[[1]]

# 5. RUN CORE FUNCTION ----
res <- quant_es_core(x)
print(res$global)
print(head(res$variants))

# 6. CORE FUNCTION WITH CUSTOM PRIORS ----
res_custom <- quant_es_core(x, a = 2, b = 3, ci_level = 0.90)
print(res_custom$global)

# 7. TEST PLOTTING (default aesthetics) ----
plots <- quant_es_plots(res, x)
print(plots$p_global)
print(plots$p_overlay)
print(plots$p_matrix)
print(plots$p_p_hat)
print(plots$p_theta_ci)
print(plots$p_combined)

# 8. TEST CUSTOM PALETTES ----
palette10_test <- grDevices::colorRampPalette(c("black", "grey"))(10)
palette20_test <- grDevices::colorRampPalette(c("steelblue", "darkblue"))(20)

plots_pal <- quant_es_plots(
  res,
  x,
  palette10 = palette10_test,
  palette20 = palette20_test
)

print(plots_pal$p_overlay)

# 9. TEST HIGHLIGHT POINTS ----
highlight_demo <- list(
  list(id = core_test_data[[1]][1], colour = "#ee4035", size = 3),
  list(id = core_test_data[[1]][5], colour = "#2f4356", size = 3)
)

plots_hi <- quant_es_plots(res, x, highlight_points = highlight_demo)
print(plots_hi$p_overlay)

# 10. FLAGSHIP PLOT  ----

# Flagship overlay plot with internal colours and clean legend
swiss_red <- "#ee4035"
federal_blue <- "#2f4356"

highlight_flagship <- list(
  list(id = core_test_data[[1]][1], colour = swiss_red, size = 4),
  list(id = "6-32664815-C-G_AR", colour = federal_blue, size = 4)
)

plots_flagship <- quant_es_plots(
  res,
  x,
  highlight_points = highlight_flagship
)

flagship_plot <- plots_flagship$p_overlay +
  ggplot2::guides(
    fill = ggplot2::guide_legend(title = "highlighted variants"),
    # colour = "none",
    size = "none"
  ) +
  ggplot2::labs(
    title = "GLobal posterior theta distribution",
    subtitle = "Top 10 CrI estimates with evidence available\nand two highlighted variants"
  ) +
  ggplot2::theme(
    legend.position = "right",
    legend.title = ggplot2::element_text(size = 10),
    legend.text = ggplot2::element_text(size = 9)
  )

flagship_plot

# 11. TEST USER OVERRIDES OF GGPLOT ----
# Remove legend
print(plots_hi$p_overlay + ggplot2::theme(legend.position = "none"))

# Remove axis titles
print(plots_hi$p_overlay + ggplot2::theme(axis.title = ggplot2::element_blank()))

# Minimal theme
print(plots_hi$p_overlay + ggplot2::theme_minimal())

# Void theme
print(plots_hi$p_overlay + ggplot2::theme_void())


# 12. HIGHLIGHT POINTS WITH INVALID IDs ----
highlight_bad <- list(
  list(id = "NONEXISTENT", colour = "red", size = 4)
)

plots_bad <- quant_es_plots(res, x, highlight_points = highlight_bad)
print("This should fail")
print(plots_bad$p_overlay)

# 13. TEST FILE-BASED INPUT ----
# (Only runs if helper exists)
if ("quant_es_from_binary_table" %in% ls("package:quantbayes")) {
  
  tmpfile <- tempfile(fileext = ".tsv")
  write.table(core_test_data, tmpfile, sep = "\t", quote = FALSE, row.names = FALSE)
  
  res_from_file <- quant_es_from_binary_table(tmpfile)
  print(res_from_file$global)
}

# 14. SAVE OUTPUTS (PLOTS AND DATA) ----

# Create output directory
out_dir <- file.path(getwd(), "output")
if (!dir.exists(out_dir)) dir.create(out_dir, recursive = TRUE)

# Save all plots
ggplot2::ggsave(
  filename = file.path(out_dir, "global_density.png"),
  plot = plots$p_global,
  width = 6,
  height = 4,
  dpi = 120
)

ggplot2::ggsave(
  filename = file.path(out_dir, "overlay.png"),
  plot = plots$p_overlay,
  width = 6,
  height = 4,
  dpi = 120
)

ggplot2::ggsave(
  filename = file.path(out_dir, "evidence_matrix.png"),
  plot = plots$p_matrix,
  width = 6,
  height = 6,
  dpi = 120
)

ggplot2::ggsave(
  filename = file.path(out_dir, "p_hat.png"),
  plot = plots$p_p_hat,
  width = 6,
  height = 4,
  dpi = 120
)

ggplot2::ggsave(
  filename = file.path(out_dir, "theta_ci.png"),
  plot = plots$p_theta_ci,
  width = 6,
  height = 4,
  dpi = 120
)

ggplot2::ggsave(
  filename = file.path(out_dir, "combined.png"),
  plot = plots$p_combined,
  width = 10,
  height = 4,
  dpi = 120
)

ggplot2::ggsave(
  filename = file.path(out_dir, "flagship_plot.pdf"),
  plot = flagship_plot,
  width = 8,
  height = 4
)

# Save the core result tables
write.csv(res$variants, file.path(out_dir, "variants_output.csv"), row.names = FALSE)
write.csv(as.data.frame(res$global), file.path(out_dir, "global_output.csv"), row.names = FALSE)

# 15. ERROR HANDLING TESTS ----
handle_test <- function(expr) {
  tryCatch(expr, error = function(e) message("Expected error: ", e$message))
}

# Wrong type
print("This should fail")
handle_test(quant_es_core("not a matrix"))

# Values not 0/1 such as 2
bad_x <- x
bad_x[1, 1] <- 2
print("This should fail")
handle_test(quant_es_core(bad_x))

# Finished
print("All tests completed.")

