## ----include = FALSE----------------------------------------------------------
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  eval = FALSE # examples are illustrative; set to TRUE when running interactively
)

## ----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)
# set.seed(123)

## ----single-target, eval=FALSE------------------------------------------------
# # Suppose we have a summary target path
# summary_path <- "outputs/welfare_summary.qs2"
# 
# # Register a simple builder that loads parents and returns x+code
# st_register_builder(summary_path, function(path, parents) {
#   # Load welfare parents (illustrative — adapt to your parents layout)
#   welfare_paths <- vapply(
#     parents,
#     function(p) grepl("welfare", p$path),
#     logical(1)
#   )
#   welfare_list <- lapply(parents[welfare_paths], function(p) st_load(p$path))
# 
#   # Load macros (shared parents)
#   cpi_tbl <- st_load("data/macro/cpi.qs2")
#   gdp_tbl <- st_load("data/macro/gdp.qs2")
#   pop_tbl <- st_load("data/macro/population.qs2")
# 
#   # call a pure worker that accepts pre-loaded inputs
#   out <- bar(welfare_list, cpi_tbl, gdp_tbl, pop_tbl)
# 
#   list(
#     x = out,
#     code = list(bar = bar),
#     code_label = "aggregate_welfare"
#   )
# })
# 
# # Inspect plan (strict mode is conservative)
# plan <- st_plan_rebuild(
#   targets = summary_path,
#   include_targets = TRUE,
#   mode = "strict"
# )
# plan
# 
# # Run only if you're ready
# # st_rebuild(plan)

## ----code-multi, eval=FALSE---------------------------------------------------
# # Good: include all contributing functions
# st_save(
#   x,
#   summary_path,
#   pk = c("country", "year"),
#   parents = parents,
#   code = list(bar = bar, h1 = h1, h2 = h2)
# )

## ----plan-inspect, eval=FALSE-------------------------------------------------
# plan <- st_plan_rebuild(targets = summary_path, include_targets = TRUE)
# # Show targets that are stale
# plan[c("path", "reason")]

## ----requested-root, eval=TRUE------------------------------------------------
library(stamp)
local({
  root <- tempfile("stamp-request-")
  dir.create(root)
  on.exit(unlink(root, recursive = TRUE), add = TRUE)
  alias <- basename(root)
  st_init(root, alias = alias, verbose = FALSE)
  old <- st_opts(.get = TRUE)
  on.exit(suppressMessages(do.call(st_opts, old)), add = TRUE)
  st_opts(versioning = "content", retain_versions = Inf, meta_format = "json")
  seed <- 1:3
  offset <- 2L
  helper <- function(x, offset) x + offset
  calculate <- function() helper(seed, offset)
  component <- function(value, schema) {
    list(hash = st_hash_obj(value), algorithm = "siphash13", schema = schema)
  }
  code_record <- function(fun) list(formals = formals(fun), body = body(fun))
  request <- list(
    schema = 1L, path = file.path(root, "requested.rds"),
    root = TRUE, parents = list(),
    required_components = c("calculation", "helper", "constants"),
    components = list(
      calculation = component(code_record(calculate), "r-formals-body-v1"),
      helper = component(code_record(helper), "r-formals-body-v1"),
      constants = component(list(seed = seed, offset = offset), "r-values-v1")
    ),
    semantic_schema = list(rule = list(
      type = "character", shape = "scalar", required = TRUE,
      nullable = FALSE, allow_na = FALSE
    )),
    semantic = list(rule = "add-v1"), format = "rds"
  )
  builder <- function(path, parents) {
    list(x = calculate(), metadata = list(rule = "add-v1"))
  }
  plan <- st_plan_rebuild(request$path, include_targets = TRUE,
    requests = list(request))
  plan[c("decision", "reason")]
  st_rebuild(plan, rebuild_fun = builder, dry_run = TRUE) # no invocation/writes
  st_rebuild(plan, rebuild_fun = builder)
  st_execution_info(request$path, alias = alias)[c("state", "receipt_id")]
  repeat_plan <- st_plan_rebuild(request$path, include_targets = TRUE,
    requests = list(request))
  st_rebuild(repeat_plan, rebuild_fun = builder) # satisfied: skip, no writes
})

## ----typed-history, eval=TRUE-------------------------------------------------
library(stamp)
local({
  root <- tempfile("stamp-metadata-")
  dir.create(root)
  on.exit(unlink(root, recursive = TRUE), add = TRUE)
  alias <- basename(root)
  st_init(root, alias = alias, verbose = FALSE)
  old <- st_opts(.get = TRUE)
  on.exit(suppressMessages(do.call(st_opts, old)), add = TRUE)
  st_opts(versioning = "content", retain_versions = Inf, meta_format = "both")
  schema <- list(
    count = list(type = "integer", shape = "scalar", required = TRUE,
      nullable = FALSE, allow_na = FALSE),
    weights = list(type = "double", shape = "vector", required = FALSE,
      nullable = TRUE, allow_na = TRUE)
  )
  first <- st_save(1:3, "typed.rds", alias = alias, verbose = FALSE,
    metadata = list(count = 1L, weights = numeric(), note = "first"),
    semantic_schema = schema)
  second <- st_save(1:3, "typed.rds", alias = alias, verbose = FALSE,
    metadata = list(count = 1L, weights = NULL, note = "second"),
    semantic_schema = schema)
  st_read_sidecar("typed.rds", alias, first$version_id)$weights # numeric(0)
  st_read_sidecar("typed.rds", alias, second$version_id)$weights # NULL
  same <- st_save(1:3, "typed.rds", alias = alias, verbose = FALSE,
    metadata = list(count = 1L, weights = NULL, note = "description edit"),
    semantic_schema = schema)
  same[c("skipped", "version_id")] # descriptions are not rewritten
  st_execution_info("typed.rds", alias = alias)$state # raw saves: absent
})

