## ----setup--------------------------------------------------------------------
# ---- setup, include=FALSE ----------------------------------------------------

# 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)
}
old_opts <- st_opts_get()
old_alias <- st_alias_get()

## ----init-example-------------------------------------------------------------
# Use a private temp dir so the vignette is reproducible locally
tdir <- tempfile("stamp-vignette-")
fs::dir_create(tdir)
st_init(tdir)

# Inspect created structure - note .stamp/ contains only state
fs::path(tdir, ".stamp") |>
  fs::dir_tree(recurse = TRUE, all = TRUE)

## ----opts-example-------------------------------------------------------------
# show defaults
st_opts(.get = TRUE)

# write both JSON and QS2 sidecars
st_opts(meta_format = "both")
st_opts("meta_format", .get = TRUE)

## ----path-format--------------------------------------------------------------
st_formats()  # built-in handlers: csv, fst, json, parquet, qs2, rds

## ----save-load----------------------------------------------------------------
x <- data.frame(a = 1:3, b = letters[1:3])

res <- st_save(x, "stamp-output/example.qs2", metadata = list(description = "toy"), alias = NULL)
res$path

# Inspect the created structure
artifact_dir <- fs::path_dir(res$path)
fs::dir_tree(artifact_dir, recurse = 1)

# load back (format auto-detected)
y <- st_load("stamp-output/example.qs2", alias = NULL)
identical(x, y)

## ----load-versions------------------------------------------------------------
# Ensure versioning is enabled for this example
st_opts(versioning = "timestamp")  # Force version on every save

# Create multiple versions by modifying and saving
v_path <- "versioned.qs2"

# Version 1
v1 <- data.frame(x = 1:3, y = c("a", "b", "c"))
st_save(v1, v_path, code_label = "initial", alias = NULL)
Sys.sleep(1.1)  # ensure distinct timestamps on all platforms

# Version 2
v2 <- data.frame(x = 1:5, y = c("a", "b", "c", "d", "e"))
st_save(v2, v_path, code_label = "added rows", alias = NULL)
Sys.sleep(1.1)

# Version 3
v3 <- data.frame(x = 1:5, y = c("a", "b", "c", "d", "e"), z = 10:14)
st_save(v3, v_path, code_label = "added column z", alias = NULL)

# Check available versions (explicit alias auto-detect)
versions <- st_versions(v_path, alias = NULL)
if (nrow(versions) == 0) {
  cat("Warning: No versions were created. Skipping version loading examples.\n")
} else {
  print(versions[, .(version_id, created_at, size_bytes)])
  
  # Load latest (default)
  current <- st_load(v_path, alias = NULL)
  cat(sprintf("Current: %d rows, %d columns\n", nrow(current), ncol(current)))
  
  # Load previous version (version = -1) when available; skip if snapshot missing
  if (nrow(versions) >= 2) {
    prev_ok <- TRUE
    previous <- tryCatch(
      st_load(v_path, version = -1, alias = NULL),
      error = function(e) { prev_ok <<- FALSE; NULL }
    )
    if (isTRUE(prev_ok)) {
      cat(sprintf("Previous (v-1): %d rows, %d columns\n", nrow(previous), ncol(previous)))
    } else {
      cat("Previous (v-1): snapshot not available; skipping.\n")
    }
  }
}
  # Load two versions back (version = -2) when available, else oldest by ID
  older_ok <- TRUE
  if (nrow(versions) >= 3) {
    older <- tryCatch(
      st_load(v_path, version = -2, alias = NULL),
      error = function(e) { older_ok <<- FALSE; NULL }
    )
  } else if (nrow(versions) >= 1) {
    oldest_id <- versions$version_id[nrow(versions)]
    older <- tryCatch(
      st_load(v_path, version = oldest_id, alias = NULL),
      error = function(e) { older_ok <<- FALSE; NULL }
    )
  } else {
    older_ok <- FALSE
    older <- NULL
  }
  if (isTRUE(older_ok)) {
    cat(sprintf("Older: %d rows, %d columns\n", nrow(older), ncol(older)))
  } else {
    cat("Older: snapshot not available; skipping.\n")
  }
  
  # Load specific version by ID (oldest)
  vid <- versions$version_id[nrow(versions)]
  spec_ok <- TRUE
  specific <- tryCatch(
    st_load(v_path, version = vid, alias = NULL),
    error = function(e) { spec_ok <<- FALSE; NULL }
  )
  if (isTRUE(spec_ok) && isTRUE(older_ok)) {
    cat(sprintf("Specific version matches older: %s\n", identical(specific, older))) 
}

# Reset to default versioning
st_opts(versioning = "content")

## ----load-interactive, eval=FALSE---------------------------------------------
# # Interactive menu to choose a version (only works in interactive R sessions)
# # This will display a menu with formatted timestamps and file sizes
# selected <- st_load(v_path, version = "select")
# 
# # The menu looks like:
# # ℹ Select a version to load from versioned.qs2:
# #   Latest version is [1]
# #
# # Available versions:
# #
# # 1: [1] 2025-11-26 10:30:15 (0.12 MB) - 20251126T103015Z
# # 2: [2] 2025-11-26 10:30:10 (0.10 MB) - 20251126T103010Z
# # 3: [3] 2025-11-26 10:30:05 (0.08 MB) - 20251126T103005Z
# #
# # Selection: _

## ----sidecar------------------------------------------------------------------
sc <- st_read_sidecar(res$path)
str(sc)

## ----lineage-example----------------------------------------------------------
# upstream artifact
in_path <- "upstream.qs"
st_save(data.frame(id=1:3), in_path, alias = NULL)
in_vid <- st_latest(in_path, alias = NULL)

# derived artifact recording parent info
out_path <- "derived.qs"
parents <- list(list(path = in_path, version_id = in_vid))
st_save(data.frame(id=1:3, v=10), out_path, parents = parents, code_label = "multiply", alias = NULL)

st_info(out_path, alias = NULL)$sidecar
st_lineage(out_path, depth = 1, alias = NULL)

## ----pk-example---------------------------------------------------------------
st_add_pk(out_path, keys = c("id"))
st_inspect_pk(out_path)

# load and filter by pk using st_filter
df <- st_load(out_path, alias = NULL)
st_filter(df, list(id = 1))

## ----retention-example, eval=FALSE--------------------------------------------
# # dry-run to preview deletions for this artifact
# st_prune_versions(path = out_path, policy = 5, dry_run = TRUE, alias = NULL)
# 
# # apply retention (non-dry)
# st_prune_versions(path = out_path, policy = list(n = 5, days = 30), dry_run = FALSE, alias = NULL)

## ----cleanup, include=FALSE---------------------------------------------------
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(tdir, recursive = TRUE)

