#!/usr/bin/env Rscript

# Description -------------------------------------------------------------

# Pre-compute the `batch_calc_gsea()` result object ("GseaRes") that ships in

# `data/precomputed_gseares.rds` and is consumed by:

#

#   - 8 accessor examples in R/utils-accessors.R and R/05_extraction.R

#     (get_expr_matrix, get_de_table, get_sample_meta, get_contrast_registry,

#      get_geneset_info, extract_gsea_task, inspect_gsea_res, ...). These

#     examples MUST be runnable (no \dontrun) to satisfy BiocCheck's ">= 80%

#     runnable examples" rule, but running batch_calc_gsea() inside each

#     example would inflate check time. Shipping the pre-computed result

#     keeps each accessor example < 1 s.

#

# Why a separate script (not regenerated on check): batch_calc_gsea() on the

# toy Hallmark + KEGG_LEGACY pathway set takes ~20 s and pulls in clusterProfiler

# + fgsea. Running it at install/check time would (a) bloat `R CMD check`

# runtime and (b) re-introduce the "examples took > 60s" NOTE we just removed.

#

# Run manually (maintainer only) when:

#   - batch_calc_gsea() return structure changes, OR

#   - clusterProfiler / fgsea see a version bump that alters the gseaResult

#     layout, OR

#   - the toy pathway set is regenerated (run make_gsea_pathwaysets_toy.R

#     first)

#

#   Rscript inst/scripts/make_precomputed_gseares.R

#

# Output file (written to data/):

#   - precomputed_gseares.rds  (~1.3 MB, GseaRes list for 2 contrasts)

# -------------------------------------------------------------------------



# Use the in-tree GSEAlens so the return structure matches what users get

# after install. This script must be run from the package root:

#

#   Rscript inst/scripts/make_precomputed_gseares.R

#

pkg_root <- getwd()

if (!dir.exists(file.path(pkg_root, "data"))) {

  stop("Run from the package root: `Rscript inst/scripts/make_precomputed_gseares.R`")

}



if (!nzchar(Sys.getenv("GSEALENS_USE_INSTALLED"))) {

  devtools::load_all(pkg_root)

} else {

  library(GSEAlens)

}



stopifnot(

  requireNamespace("clusterProfiler", quietly = TRUE),

  requireNamespace("fgsea", quietly = TRUE)

)



out_dir <- file.path(pkg_root, "data")

extdata <- out_dir



# ---- Load pre-computed inputs (regenerated by their own scripts) --------

stopifnot(

  file.exists(file.path(extdata, "preprocessed_limma.rds")),

  file.exists(file.path(extdata, "gsea_pathwaysets_toy.rds"))

)



precomp <- readRDS(file.path(extdata, "preprocessed_limma.rds"))

pathways <- readRDS(file.path(extdata, "gsea_pathwaysets_toy.rds"))



gsea_env <- setup_gsea_env(

  fit = precomp$fit,

  pathway_obj = pathways,

  expr_data = precomp$gsea_limma_voom_data

)



# ---- Run batch_calc_gsea (2 workers, scratch output dir) ----------------

scratch <- file.path(tempdir(), "gseares_build")

unlink(scratch, recursive = TRUE)

dir.create(scratch, showWarnings = FALSE, recursive = TRUE)



gsea_res <- batch_calc_gsea(

  gsea_env         = gsea_env,

  custom_series_name = "precomputed",

  output_dir       = scratch,

  workers          = 2,

  use_progress     = FALSE

)



# ---- Save ---------------------------------------------------------------

out_file <- file.path(out_dir, "precomputed_gseares.rds")

saveRDS(gsea_res, out_file, compress = "xz")



# ---- Report -------------------------------------------------------------

size_mb <- file.size(out_file) / 1024^2

md5 <- unname(tools::md5sum(out_file))

n_contrasts <- length(gsea_res)

n_pathways_total <- if (is.list(gsea_res)) {

  sum(vapply(gsea_res, function(t) {

    if (is.null(t$gsea_res)) return(0L)

    nrow(as.data.frame(t$gsea_res))

  }, integer(1)))

} else NA_integer_



cat(sprintf(

  "Wrote:\n  %s  (%.2f MB, %d contrasts, %d total enriched pathways, md5=%s)\n",

  basename(out_file), size_mb, n_contrasts, n_pathways_total, md5

))



cat("\nclusterProfiler version:",

    as.character(packageVersion("clusterProfiler")), "\n")

cat("fgsea version:", as.character(packageVersion("fgsea")), "\n")

cat("GSEAlens version:", as.character(packageVersion("GSEAlens")), "\n")

cat("Generation date:", format(Sys.Date(), "%Y-%m-%d"), "\n")

