## Build script: assemble rsrc_tree/ into R/ with correct collation order
##
## Usage: source("inst/copy_r_source.R") from the CVXR package root
##        OR: Rscript inst/copy_r_source.R
##
## This script:
## 1. Reads the collation order from inst/all_files.csv
## 2. Deletes the existing R/ directory
## 3. Copies files from rsrc_tree/ to R/ with numeric prefixes for collation
## 4. Each file gets a header noting its source location
##
## Adapted from the prior art branch's build script concept, but for S7.
## The key difference: NO S4-specific files (set_class_unions.R, set_old_class.R).

pkg_dir <- if (interactive()) here::here() else getwd()

csv_path <- file.path(pkg_dir, "inst", "all_files.csv")
if (!file.exists(csv_path)) {
  stop("Cannot find ", csv_path, "\nRun from the CVXR package root directory.")
}

all_files <- read.csv(csv_path, stringsAsFactors = FALSE)$file

## Validate all source files exist
missing <- all_files[!file.exists(file.path(pkg_dir, all_files))]
if (length(missing) > 0) {
  stop("Missing source files:\n", paste("  ", missing, collapse = "\n"))
}

## Create numbered output names for collation
## Use full rsrc_tree path (/ -> _) to avoid basename collisions
## e.g. rsrc_tree/reductions/dcp2cone/canonicalizers/abs_canon.R
##   -> 112_reductions_dcp2cone_canonicalizers_abs_canon.R
.path_to_flat <- function(path) {
  ## Strip leading rsrc_tree/ or zzz_R_specific/ prefix, replace / with _
  flat <- gsub("/", "_", path)
  ## Remove leading rsrc_tree_ prefix for brevity (it's implied)
  flat <- sub("^rsrc_tree_", "", flat)
  flat
}
names(all_files) <- sprintf("%03d_%s", seq_along(all_files), .path_to_flat(all_files))

## Rebuild R/ directory
r_dir <- file.path(pkg_dir, "R")
if (dir.exists(r_dir)) {
  unlink(r_dir, recursive = TRUE)
}
dir.create(r_dir)

for (f in names(all_files)) {
  src_path <- file.path(pkg_dir, all_files[f])
  lines <- c(
    "#####",
    sprintf("## DO NOT EDIT THIS FILE!! EDIT THE SOURCE INSTEAD: %s", all_files[f]),
    "#####",
    "",
    readLines(src_path)
  )
  writeLines(lines, file.path(r_dir, f))
}

cat(sprintf("Copied %d files to R/\n", length(all_files)))

## Generate Collate field for DESCRIPTION
collate_entries <- paste0("    '", names(all_files), "'", collapse = "\n")
cat("\n## Add to DESCRIPTION Collate field:\nCollate:\n", collate_entries, "\n")

## ── Test files ──────────────────────────────────────────────
## Copy tests from test_tree/ → tests/testthat/
## By default, copy ALL tests (for development).
## Set CRAN_BUILD=true to copy only the CRAN subset.

test_src <- file.path(pkg_dir, "test_tree")
test_dst <- file.path(pkg_dir, "tests", "testthat")

if (!dir.exists(test_src)) {
  cat("No test_tree/ found — skipping test copy.\n")
} else {
  if (dir.exists(test_dst)) unlink(test_dst, recursive = TRUE)
  dir.create(test_dst, recursive = TRUE)

  cran_build <- identical(Sys.getenv("CRAN_BUILD"), "true")

  if (cran_build) {
    cran_csv <- file.path(pkg_dir, "inst", "cran_tests.csv")
    test_files <- read.csv(cran_csv, stringsAsFactors = FALSE)$file
    cat(sprintf("CRAN_BUILD=true: copying %d CRAN test files\n", length(test_files)))
  } else {
    test_files <- list.files(test_src, pattern = "\\.(R|r)$")
    cat(sprintf("Copying all %d test files (development mode)\n", length(test_files)))
  }

  for (f in test_files) {
    file.copy(file.path(test_src, f), file.path(test_dst, f))
  }

  ## Copy _problems/ subdirectory if it exists and we're in dev mode
  problems_src <- file.path(test_src, "_problems")
  if (dir.exists(problems_src) && !cran_build) {
    problems_dst <- file.path(test_dst, "_problems")
    dir.create(problems_dst, recursive = TRUE)
    problem_files <- list.files(problems_src, pattern = "\\.(R|r)$")
    for (f in problem_files) {
      file.copy(file.path(problems_src, f), file.path(problems_dst, f))
    }
    cat(sprintf("Copied %d problem files to tests/testthat/_problems/\n", length(problem_files)))
  }

  cat(sprintf("Copied %d test files to tests/testthat/\n", length(test_files)))
}
