## render_site.R -- build the static narrative site for Netlify
##
## Usage from the repo root:
##   source("site/render_site.R"); render_site()
##
## Usage from the shell:
##   Rscript site/render_site.R

.find_site_dir <- function() {
  wd <- normalizePath(getwd(), mustWork = TRUE)
  candidates <- unique(c(wd, dirname(wd), dirname(dirname(wd))))

  for (dir in candidates) {
    if (file.exists(file.path(dir, "site", "index.qmd"))) {
      return(normalizePath(file.path(dir, "site"), mustWork = TRUE))
    }
    if (basename(dir) == "site" && file.exists(file.path(dir, "index.qmd"))) {
      return(normalizePath(dir, mustWork = TRUE))
    }
  }

  cmd_file <- grep("--file=", commandArgs(FALSE), value = TRUE)
  if (length(cmd_file)) {
    return(dirname(normalizePath(sub("--file=", "", cmd_file[[1]]), mustWork = TRUE)))
  }

  stop("Could not locate site/index.qmd from current working directory: ", wd)
}

render_site <- function() {
  site_dir <- .find_site_dir()
  chart_dir <- file.path(
    path.expand(Sys.getenv("LAHMANS_DBDIR", "~/Documents/Data/baseball")),
    "charts"
  )
  code_dir <- file.path(site_dir, "..", "scripts", "linkedin")
  asset_dir <- file.path(site_dir, "assets")
  out_dir <- file.path(site_dir, "_site")
  out_code_dir <- file.path(out_dir, "code")

  files <- c(
    "rookie_dev_chart.png",
    "talent_allocation.png",
    "dead_money.png",
    "trade_scores.png",
    "mva_quadrant.png",
    "stage1_getting_there.png",
    "stage2_going_deep.png",
    "synthesis_scorecard.png",
    "payroll_vs_achievement.png"
  )

  missing <- files[!file.exists(file.path(chart_dir, files))]
  if (length(missing)) {
    stop(
      "Missing chart files in ", chart_dir, ": ",
      paste(missing, collapse = ", "),
      ". Run scripts/linkedin/run_all.R first."
    )
  }

  dir.create(asset_dir, recursive = TRUE, showWarnings = FALSE)
  dir.create(out_dir, recursive = TRUE, showWarnings = FALSE)

  ok <- file.copy(
    from = file.path(chart_dir, files),
    to   = file.path(asset_dir, files),
    overwrite = TRUE
  )
  if (!all(ok)) {
    stop("Failed to copy one or more chart assets into ", asset_dir)
  }

  code_files <- list.files(code_dir, pattern = "\\.[Rr]$", full.names = TRUE)
  if (!length(code_files)) {
    stop("No R scripts found in ", code_dir)
  }

  old_wd <- getwd()
  on.exit(setwd(old_wd), add = TRUE)
  setwd(site_dir)

  ret <- system2("quarto", c("render", "index.qmd"), stdout = "", stderr = "")
  if (ret != 0L) {
    stop("quarto render failed with exit code ", ret)
  }

  html_src <- file.path(site_dir, "index.html")
  if (!file.exists(html_src)) {
    stop("Quarto render did not create ", html_src)
  }
  ok_html <- file.copy(html_src, file.path(out_dir, "index.html"), overwrite = TRUE)
  if (!ok_html) {
    stop("Failed to copy rendered HTML into ", out_dir)
  }

  index_files_src <- file.path(site_dir, "index_files")
  if (dir.exists(index_files_src)) {
    unlink(file.path(out_dir, "index_files"), recursive = TRUE, force = TRUE)
    ok_libs <- file.copy(index_files_src, out_dir, recursive = TRUE)
    if (!ok_libs) {
      stop("Failed to copy index_files into ", out_dir)
    }
  }

  dir.create(out_code_dir, recursive = TRUE, showWarnings = FALSE)
  ok_code <- file.copy(
    from = code_files,
    to   = file.path(out_code_dir, basename(code_files)),
    overwrite = TRUE
  )
  if (!all(ok_code)) {
    stop("Failed to copy one or more code files into ", out_code_dir)
  }

  file.copy(file.path(site_dir, "render_site.R"), file.path(out_dir, "render_site.R"), overwrite = TRUE)

  message("Site rendered to: ", out_dir)
  invisible(out_dir)
}

.cmd_file <- grep("--file=", commandArgs(FALSE), value = TRUE)
if (length(.cmd_file) && grepl("render_site\\.R$", .cmd_file[[1]])) {
  render_site()
}
