args <- commandArgs(trailingOnly = TRUE)

output_dir <- if (length(args) >= 1L && nzchar(args[[1L]])) {
  args[[1L]]
} else {
  file.path(tempdir(), "SelectBoost.quantile-validation")
}
replications <- if (length(args) >= 2L) as.integer(args[[2L]]) else 4L
threshold <- if (length(args) >= 3L) as.numeric(args[[3L]]) else 0.55
seed <- if (length(args) >= 4L && nzchar(args[[4L]])) as.integer(args[[4L]]) else NULL

if (is.na(replications) || replications < 1L) {
  stop("`replications` must be a positive integer.", call. = FALSE)
}
if (is.na(threshold) || threshold < 0 || threshold > 1) {
  stop("`threshold` must be a scalar in [0, 1].", call. = FALSE)
}
if (!is.null(seed) && (is.na(seed) || length(seed) != 1L)) {
  stop("`seed` must be omitted or be a single integer.", call. = FALSE)
}

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

if (!requireNamespace("SelectBoost.quantile", quietly = TRUE)) {
  if (!file.exists("DESCRIPTION") || !requireNamespace("pkgload", quietly = TRUE)) {
    stop(
      "Install `SelectBoost.quantile` or run this script from a source checkout with `pkgload` available.",
      call. = FALSE
    )
  }
  pkgload::load_all(".", quiet = TRUE, export_all = FALSE)
}

pkg_ns <- asNamespace("SelectBoost.quantile")
scenarios <- get("default_quantile_benchmark_scenarios", envir = pkg_ns)()
benchmark <- get("benchmark_quantile_selection", envir = pkg_ns)(
  scenarios = scenarios,
  replications = replications,
  threshold = threshold,
  selection_metric = "hybrid",
  selectboost_args = list(
    B = 8,
    step_num = 0.5,
    screen = "auto",
    tune_lambda = "cv",
    lambda_rule = "one_se",
    lambda_inflation = 1.25,
    folds = 5,
    repeats = 1,
    subsamples = 12,
    sample_fraction = 0.5,
    complementary_pairs = TRUE,
    max_group_size = 15,
    nlambda = 8,
    verbose = FALSE
  ),
  tuned_args = list(
    method = "cv",
    rule = "one_se",
    lambda_inflation = 1.25,
    folds = 5,
    repeats = 1,
    nlambda = 8,
    verbose = FALSE
  ),
  seed = seed,
  verbose = TRUE
)

summary_table <- summary(benchmark)
raw_results <- benchmark$results
raw_results$support <- vapply(
  raw_results$support,
  function(x) paste(x, collapse = ";"),
  character(1)
)

output_prefix <- file.path(output_dir, "quantile_benchmark_release")
saveRDS(benchmark, file = paste0(output_prefix, ".rds"), version = 2)
utils::write.csv(summary_table, file = paste0(output_prefix, "_summary.csv"), row.names = FALSE)
utils::write.csv(raw_results, file = paste0(output_prefix, "_raw.csv"), row.names = FALSE)
writeLines(capture.output(sessionInfo()), con = paste0(output_prefix, "_sessionInfo.txt"))

message("Validation artifacts written to: ", normalizePath(output_dir, mustWork = FALSE))
print(summary_table)
