## ----include = FALSE----------------------------------------------------------
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)

## ----setup--------------------------------------------------------------------
# Use development build when interactive *and* explicitly enabled via env var.
dev_mode <- (Sys.getenv("DEV_VIGNETTES", "false") == "true")

if (dev_mode && requireNamespace("pkgload", quietly = TRUE)) {
  pkgload::load_all(
    export_all = FALSE,
    helpers = FALSE,
    attach_testthat = FALSE
  )
} else {
  # fall back to the installed package (the path CRAN, CI, and pkgdown take)
  library(stamp)
}
library(data.table)
old_opts <- st_opts_get()
old_alias <- st_alias_get()
set.seed(123)

# Create an isolated temporary root so all writes occur outside the package tree.
# Use a short name to avoid long path issues on Windows (PATH_MAX = 260).
root_dir <- tempfile("s") |>
  fs::dir_create()

# Initialize stamp under this temp root
st_init(root = root_dir)

# Helper: list only data files with known extensions to avoid locks/sidecars
# Returns relative paths from alias root (suitable for st_load)
data_files <- function(dir) {
  # Convert dir to relative path from root_dir if it's absolute
  rel_dir <- if (fs::is_absolute_path(dir)) {
    as.character(fs::path_rel(dir, start = root_dir))
  } else {
    dir
  }
  
  # Get absolute path for listing
  abs_dir <- fs::path(root_dir, rel_dir)
  if (!fs::dir_exists(abs_dir)) {
    return(character(0))
  }
  
  f <- fs::dir_ls(abs_dir)
  ext <- tolower(fs::path_ext(f))
  allowed <- c("qs2", "rds", "csv", "fst", "json")
  f <- f[ext %in% allowed]
  
  # Return relative paths from root_dir
  as.character(fs::path_rel(f, start = root_dir))
}

## ----simulate-welfare---------------------------------------------------------
welfare_specs <- data.frame(
  country = c("COL", "COL", "MEX", "MEX", "PRY", "PRY"),
  year = c(2010, 2012, 2010, 2015, 2011, 2014),
  stringsAsFactors = FALSE
)

mk_reporting <- function(cty) {
  if (cty %in% c("COL", "MEX")) c("urban", "rural") else c("national")
}

simulate_welfare <- function(country, year) {
  rl <- mk_reporting(country)
  # 200 households per reporting level
  dt_list <- lapply(rl, function(rlev) {
    n <- 200L
    data.table(
      country = country,
      year = year,
      reporting_level = rlev,
      hh_id = sprintf("%s_%s_%s_%03d", country, year, rlev, seq_len(n)),
      welfare = round(
        rlnorm(n, meanlog = log(1000 + year) - 7, sdlog = 0.5),
        2
      ),
      weight = runif(n, 0.5, 2)
    )
  })
  rbindlist(dt_list)
}

welfare_paths <- list()
for (i in seq_len(nrow(welfare_specs))) {
  row <- welfare_specs[i, ]
  dt <- simulate_welfare(row$country, row$year)
  fn <- sprintf("data/welfare/%s_%d.qs2", row$country, row$year)
  # Primary key columns include household id for uniqueness
  st_save(
    dt,
    fn,
    pk = c("country", "year", "reporting_level", "hh_id"),
    domain = "welfare",
    alias = NULL
  )
  welfare_paths[[length(welfare_paths) + 1]] <- fn
}
unlist(welfare_paths)

## ----welfare-info-------------------------------------------------------------
st_info("data/welfare/COL_2010.qs2", alias = NULL)

## ----simulate-macro-----------------------------------------------------------
years <- 2010:2015
countries_macro <- c("COL", "MEX", "PRY", "BRA", "ARG")
levels_all <- c("national", "urban", "rural")

simulate_cpi <- function() {
  out <- CJ(
    country = countries_macro,
    year = years,
    reporting_level = levels_all
  )
  out[, cpi := round(runif(.N, 80, 140), 2)]
  out
}

simulate_population <- function() {
  out <- CJ(
    country = countries_macro,
    year = years,
    reporting_level = levels_all
  )
  out[, population := round(runif(.N, 5e5, 20e6))]
  out
}

simulate_gdp <- function() {
  out <- CJ(country = countries_macro, year = years)
  out[, gdp := round(runif(.N, 1e9, 5e11))]
  out
}

cpi <- simulate_cpi()
pop <- simulate_population()
gdp <- simulate_gdp()

st_save(
  cpi,
  "data/macro/cpi.qs2",
  pk = c("country", "year", "reporting_level"),
  domain = "macro",
  alias = NULL
)
st_save(
  pop,
  "data/macro/population.qs2",
  pk = c("country", "year", "reporting_level"),
  domain = "macro",
  alias = NULL
)
st_save(
  gdp,
  "data/macro/gdp.qs2",
  pk = c("country", "year"),
  domain = "macro",
  alias = NULL
)

## ----cpi-versions-------------------------------------------------------------
print(st_versions("data/macro/cpi.qs2", alias = NULL))

## ----define-foo---------------------------------------------------------------
foo <- function() {
  # Load all welfare micro artifacts (only recognized data files)
  welfare_files <- data_files("data/welfare")
  if (length(welfare_files) == 0) {
    cat("No welfare files found; returning empty table.\n")
    return(data.table::data.table())
  }
  wf <- rbindlist(lapply(welfare_files, st_load))

  stats <- wf[,
    .(
      welfare_mean = weighted.mean(welfare, weight),
      welfare_median = as.numeric(stats::median(welfare)),
      welfare_sd = stats::sd(welfare),
      welfare_n = .N
    ),
    by = .(country, year, reporting_level)
  ]

  cpi <- st_load("data/macro/cpi.qs2", alias = NULL)
  gdp <- st_load("data/macro/gdp.qs2", alias = NULL)
  pop <- st_load("data/macro/population.qs2", alias = NULL)

  # Merge; CPI & population contain rows not present in welfare; keep welfare rows only
  out <- merge(
    stats,
    cpi,
    by = c("country", "year", "reporting_level"),
    all.x = TRUE
  )
  out <- merge(
    out,
    pop,
    by = c("country", "year", "reporting_level"),
    all.x = TRUE
  )
  out <- merge(out, gdp, by = c("country", "year"), all.x = TRUE)
  setcolorder(
    out,
    c(
      "country",
      "year",
      "reporting_level",
      "welfare_mean",
      "welfare_median",
      "welfare_sd",
      "welfare_n",
      "cpi",
      "gdp",
      "population"
    )
  )
  out
}

# Call foo() to compute summary (empty if no data found)
summary_table <- foo()
if (nrow(summary_table) > 0) {
  head(summary_table)
} else {
  cat("Summary table is empty; ensure welfare data was saved.\n")
  summary_table
}

## ----save-summary-------------------------------------------------------------
# Only save summary if it has data (i.e., welfare data was available)
if (nrow(summary_table) > 0) {
  parent_paths <- c(
    data_files("data/welfare"),
    "data/macro/cpi.qs2",
    "data/macro/gdp.qs2",
    "data/macro/population.qs2"
  )
  parents <- lapply(parent_paths, function(p) {
    list(path = p, version_id = st_latest(p, alias = NULL))
  })

  st_save(
    summary_table,
    "outputs/welfare_summary.qs2",
    pk = c("country", "year", "reporting_level"),
    parents = parents,
    domain = "summary",
    alias = NULL
  )
  st_lineage("outputs/welfare_summary.qs2", depth = 1, alias = NULL)
} else {
  cat("Summary table is empty; skipping save and lineage demo.\n")
}

## ----bar-and-save-------------------------------------------------------------
# Variant that accepts loaded objects (preferred for testability and clarity)
bar <- function(welfare_list, cpi_tbl, gdp_tbl, pop_tbl) {
  if (length(welfare_list) == 0) {
    cat("No welfare data provided; returning empty table.\n")
    return(data.table::data.table())
  }
  wf <- data.table::rbindlist(welfare_list)
  stats <- wf[,
    .(
      welfare_mean = weighted.mean(welfare, weight),
      welfare_median = as.numeric(stats::median(welfare)),
      welfare_sd = stats::sd(welfare),
      welfare_n = .N
    ),
    by = .(country, year, reporting_level)
  ]

  out <- merge(
    stats,
    cpi_tbl,
    by = c("country", "year", "reporting_level"),
    all.x = TRUE
  )
  out <- merge(
    out,
    pop_tbl,
    by = c("country", "year", "reporting_level"),
    all.x = TRUE
  )
  out <- merge(out, gdp_tbl, by = c("country", "year"), all.x = TRUE)
  setcolorder(
    out,
    c(
      "country",
      "year",
      "reporting_level",
      "welfare_mean",
      "welfare_median",
      "welfare_sd",
      "welfare_n",
      "cpi",
      "gdp",
      "population"
    )
  )
  out
}

# Example: load inputs outside the worker and call bar()
welfare_files <- data_files("data/welfare")
if (length(welfare_files) > 0) {
  welfare_list <- lapply(welfare_files, st_load)
  cpi_tbl <- st_load("data/macro/cpi.qs2", alias = NULL)
  gdp_tbl <- st_load("data/macro/gdp.qs2", alias = NULL)
  pop_tbl <- st_load("data/macro/population.qs2", alias = NULL)

  summary_table2 <- bar(welfare_list, cpi_tbl, gdp_tbl, pop_tbl)
  if (nrow(summary_table2) > 0) {
    parent_paths <- c(
      data_files("data/welfare"),
      "data/macro/cpi.qs2",
      "data/macro/gdp.qs2",
      "data/macro/population.qs2"
    )
    parents <- lapply(parent_paths, function(p) {
      list(path = p, version_id = st_latest(p, alias = NULL))
    })
    st_save(
      summary_table2,
      "outputs/welfare_summary.qs2",
      pk = c("country", "year", "reporting_level"),
      parents = parents,
      code = bar, # addition the function as parent so st_save() can track it
      domain = "summary",
      alias = NULL
    )
    st_lineage("outputs/welfare_summary.qs2", depth = 1, alias = NULL)
  } else {
    cat("Summary table2 is empty; skipping save.\n")
  }
} else {
  cat("No welfare data to process in bar-and-save example.\n")
}

## ----code-multiple------------------------------------------------------------
# Provide multiple functions to st_save so code_hash changes if any of them change
# st_save(x, path, code = list(foo = foo, helper1 = f1, helper2 = f2))

## ----modify-cpi---------------------------------------------------------------
cpi2 <- st_load("data/macro/cpi.qs2", alias = NULL)
cpi2[country == "COL" & year == 2012, cpi := cpi * 1.05] # 5% adjustment
st_save(cpi2, "data/macro/cpi.qs2", alias = NULL) # new version recorded
st_versions("data/macro/cpi.qs2", alias = NULL)[1:3]
st_is_stale("outputs/welfare_summary.qs2") # should be TRUE

## -----------------------------------------------------------------------------
# Example: register a builder that uses the provided `parents` list and avoids global loads
summary_path <- fs::path(root_dir, "outputs", "welfare_summary.qs2")
st_register_builder(summary_path, function(path, parents) {
  # parents is a list of lists: each element has $path and $version_id
  # Filter parent paths to identify welfare inputs vs macro inputs, then load them
  welfare_parent_paths <- vapply(
    parents,
    function(p) grepl("welfare", p$path),
    logical(1)
  )
  welfare_list <- lapply(parents[welfare_parent_paths], function(p) {
    st_load(p$path, alias = NULL)
  })

  cpi_tbl <- st_load("data/macro/cpi.qs2", alias = NULL)
  gdp_tbl <- st_load("data/macro/gdp.qs2", alias = NULL)
  pop_tbl <- st_load("data/macro/population.qs2", alias = NULL)

  # Produce the output using a helper function (bar) that accepts pre-loaded inputs
  out <- bar(welfare_list, cpi_tbl, gdp_tbl, pop_tbl)

  # Return the produced object plus code metadata (capture both producer and helpers)
  list(
    x = out,
    code = list(bar = bar), # include helpers as needed
    code_label = "aggregate_welfare"
  )
})

## -----------------------------------------------------------------------------
plan <- st_plan_rebuild(
  targets = "outputs/welfare_summary.qs2",
  include_targets = TRUE,
  mode = "strict"
)
print(plan)

## -----------------------------------------------------------------------------
st_rebuild(plan)

## ----rebuild-summary----------------------------------------------------------
st_register_builder(summary_path, function(path, parents) {
  list(x = foo(), code = foo, code_label = "aggregate_welfare")
})

plan <- st_plan_rebuild(
  targets = "outputs/welfare_summary.qs2",
  include_targets = TRUE,
  mode = "strict"
)
plan
st_rebuild(plan)
st_lineage("outputs/welfare_summary.qs2", depth = 1, alias = NULL)

## ----add-arg------------------------------------------------------------------
dt_arg_2015 <- simulate_welfare("ARG", 2015)
st_save(
  dt_arg_2015,
  "data/welfare/ARG_2015.qs2",
  pk = c("country", "year", "reporting_level", "hh_id"),
  domain = "welfare",
  alias = NULL
)

# Only recompute and save summary if we have welfare data
if (length(data_files("data/welfare")) > 0 && nrow(summary_table) > 0) {
  parents2 <- lapply(
    c(
      data_files("data/welfare"),
      "data/macro/cpi.qs2",
      "data/macro/gdp.qs2",
      "data/macro/population.qs2"
    ),
    function(p) list(path = p, version_id = st_latest(p, alias = NULL))
  )
  summary_table_new <- foo()
  if (nrow(summary_table_new) > 0) {
    st_save(
      summary_table_new,
      "outputs/welfare_summary.qs2",
      pk = c("country", "year", "reporting_level"),
      parents = parents2,
      domain = "summary",
      alias = NULL
    )
    head(st_load("outputs/welfare_summary.qs2", alias = NULL))
  } else {
    cat("Summary table after adding ARG 2015 is empty; skipping save.\n")
  }
} else {
  cat("Insufficient data to recompute summary.\n")
}

## ----final-lineage------------------------------------------------------------
st_lineage("outputs/welfare_summary.qs2", depth = 2, alias = NULL)[1:10, ]

## ----cleanup, include=FALSE---------------------------------------------------
st_clear_builders(summary_path)
suppressMessages(do.call(st_opts, old_opts))
if (!is.null(old_alias)) {
  st_init(old_alias$root, state_dir = old_alias$state_dir, verbose = FALSE)
}
unlink(root_dir, recursive = TRUE)

