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

# 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-demo----------------------------------------------------------------
# Create a temporary project directory for demonstration
demo_dir <- tempfile("stamp-demo-")
fs::dir_create(demo_dir)

# Initialize stamp
st_init(demo_dir)

# Inspect what was created
fs::dir_tree(fs::path(demo_dir, ".stamp"), recurse = TRUE, all = TRUE)

## ----reinit-demo--------------------------------------------------------------
# Save an artifact to create version history
test_data <- data.frame(x = 1:5, y = letters[1:5])
test_path <- fs::path(demo_dir, "data", "test.qs2")
st_save(test_data, test_path)

# Check versions exist
versions_before <- st_versions(test_path)
nrow(versions_before)

# Re-initialize (this is safe!)
st_init(demo_dir)

# Version history is preserved
versions_after <- st_versions(test_path)
identical(versions_before, versions_after)

## ----catalog-structure, eval=FALSE--------------------------------------------
# catalog <- list(
#   artifacts = data.table(
#     artifact_id,          # Stable hash of normalized path
#     path,                 # Current canonical path
#     format,               # File format (rds, qs2, csv, etc.)
#     latest_version_id,    # Most recent version identifier
#     n_versions            # Total number of saved versions
#   ),
#   versions = data.table(
#     version_id,           # Unique version identifier
#     artifact_id,          # Links to artifacts table
#     content_hash,         # Hash of file contents
#     code_hash,            # Hash of generating code (if tracked)
#     size_bytes,           # File size in bytes
#     created_at,           # ISO8601 UTC timestamp
#     sidecar_format        # "json", "qs2", "both", or "none"
#   )
# )

## ----catalog-functions--------------------------------------------------------
# List all versions of an artifact
versions <- st_versions(test_path)
str(versions)

# Get latest version ID
latest_id <- st_latest(test_path)
latest_id

# Get comprehensive info (catalog + sidecar + snapshot location)
info <- st_info(test_path)
str(info, max.level = 1)

## ----version-snapshot-demo----------------------------------------------------
# Save the same artifact multiple times with changes
st_opts(versioning = "timestamp")  # ensure snapshots are created
v1 <- data.frame(x = 1:3)
st_save(v1, test_path, code_label = "initial")
Sys.sleep(1.1)

v2 <- data.frame(x = 1:5)
st_save(v2, test_path, code_label = "added rows")
Sys.sleep(1.1)

v3 <- data.frame(x = 1:5, y = 10:14)
st_save(v3, test_path, code_label = "added column")

# Version history is stored NEXT TO the artifact, not in .stamp/
# Extract the artifact directory from sidecar info  
info <- st_info(test_path, alias = NULL)
artifact_dir <- fs::path_dir(info$sidecar$path)
versions_dir <- fs::path(artifact_dir, "versions")

if (fs::dir_exists(versions_dir)) {
  cat("Version snapshots location:", versions_dir, "\n")
  fs::dir_tree(versions_dir, recurse = 1)
} else {
  cat("No versions directory found (versioning may be off).\n")
}

# reset to default behavior for the rest of the vignette
st_opts(versioning = "content")

## ----inspect-snapshot---------------------------------------------------------
# Get the latest version directory path
latest_info <- st_info(test_path)
latest_vdir <- latest_info$snapshot_dir

if (!is.na(latest_vdir) && fs::dir_exists(latest_vdir)) {
  cat("Latest snapshot directory:", latest_vdir, "\n\n")
  
  # List contents - note: parents.json only exists if parents were specified
  fs::dir_ls(latest_vdir)
  
  # Read the sidecar from the snapshot
  sidecar_path <- fs::path(latest_vdir, "sidecar.json")
  if (fs::file_exists(sidecar_path)) {
    sidecar <- jsonlite::read_json(sidecar_path)
    str(sidecar[c("path", "format", "created_at", "size_bytes", "code_label")])
  }
} else {
  cat("No snapshot directory recorded for test_path; ensure versioning created snapshots.\n")
}

## ----parents-demo-------------------------------------------------------------
# Ensure snapshots are recorded for this demo
st_opts(versioning = "timestamp")

# First, create an upstream artifact
upstream_path <- fs::path(demo_dir, "data", "upstream.qs2")
upstream_data <- data.frame(id = 1:10, value = rnorm(10))
st_save(upstream_data, upstream_path, code_label = "upstream data")
upstream_version <- st_latest(upstream_path)

# Now create a derived artifact with parent reference
derived_path <- fs::path(demo_dir, "data", "derived.qs2")
derived_data <- data.frame(id = 1:10, transformed = upstream_data$value * 2)
st_save(
  derived_data, 
  derived_path,
  parents = list(list(path = upstream_path, version_id = upstream_version)),
  code_label = "derived from upstream"
)

# Now check the derived artifact's snapshot - parents.json will be present
derived_info <- st_info(derived_path)
derived_vdir <- derived_info$snapshot_dir
if (!is.na(derived_vdir) && fs::dir_exists(derived_vdir)) {
  fs::dir_ls(derived_vdir)
  
  # Read parents.json
  parents_file <- fs::path(derived_vdir, "parents.json")
  if (fs::file_exists(parents_file)) {
    parents <- jsonlite::read_json(parents_file)
    str(parents)
  } else {
    cat("parents.json not found; ensure parents were recorded.\n")
  }
} else {
  cat("No snapshot directory recorded for derived_path; ensure versioning created snapshots.\n")
}

# Reset to default versioning for the remainder
st_opts(versioning = "content")

## ----artifact-organization-demo, eval=FALSE-----------------------------------
# # Save to a subdirectory path
# project_file <- fs::path(demo_dir, "outputs", "results.qs2")
# st_save(data.frame(x = 1:5), project_file)
# 
# # Creates:
# #   <demo_dir>/outputs/results.qs2/results.qs2  (the file)
# #   <demo_dir>/outputs/results.qs2/stmeta/      (metadata)
# #   <demo_dir>/outputs/results.qs2/versions/    (history)
# 
# # Save a bare filename
# bare_file <- fs::path(demo_dir, "summary.qs2")
# st_save(data.frame(y = 6:10), bare_file)
# 
# # Creates:
# #   <demo_dir>/summary.qs2/summary.qs2  (the file)
# #   <demo_dir>/summary.qs2/stmeta/      (metadata)
# #   <demo_dir>/summary.qs2/versions/    (history)

## ----load-example, eval=FALSE-------------------------------------------------
# # Load using the same path you saved with
# data <- st_load("outputs/results.qs2")  # stamp finds outputs/results.qs2/results.qs2
# data <- st_load("summary.qs2")          # stamp finds summary.qs2/summary.qs2

## ----versioning-modes---------------------------------------------------------
# Show current versioning mode
st_opts("versioning", .get = TRUE)

# Available modes:
# - "content" (default): Save version only when content or code changes
# - "timestamp": Save version on every st_save() call
# - "off": Disable versioning (only update current file + sidecar)

# Example: Force version on every save
st_opts(versioning = "timestamp")
v_same <- data.frame(x = 1:3)
st_save(v_same, test_path, code_label = "first")
Sys.sleep(0.2)
st_save(v_same, test_path, code_label = "second identical")  # Still creates version!

# Check: two versions with identical content
recent_versions <- st_versions(test_path)
tail(recent_versions[, .(version_id, created_at, content_hash)], 2)

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

## ----internal-funcs, eval=FALSE-----------------------------------------------
# .st_norm_path(path)           # Normalize path to absolute canonical form
# .st_artifact_id(path)         # Compute stable hash identifier from path
# .st_root_dir()                # Get project root from st_init()
# .st_state_dir_abs()           # Get absolute .stamp/ path

## ----catalog-ops, eval=FALSE--------------------------------------------------
# .st_catalog_path()            # Path to catalog.qs2
# .st_catalog_read()            # Read catalog (or create empty if missing)
# .st_catalog_write(cat)        # Atomic catalog write with locking
# .st_catalog_record_version()  # Add new version row to catalog

## ----version-ops, eval=FALSE--------------------------------------------------
# .st_version_dir(rel_path, vid, alias)    # Compute specific version snapshot path
# .st_version_commit_files()    # Copy artifact + sidecars to snapshot
# .st_version_read_parents()    # Read parents.json from snapshot
# .st_version_write_parents()   # Write parents.json to snapshot
# # Note: .st_versions_root() is deprecated (centralized storage removed in v0.0.9)

## ----locking-demo, eval=FALSE-------------------------------------------------
# # Internal locking mechanism (simplified)
# .st_with_lock(path, {
#   cat <- .st_catalog_read()     # Read catalog safely
#   # ... modify catalog ...       # Make changes
#   .st_catalog_write(cat)         # Write back safely
# })
# 
# # Lock file: .stamp/catalog.lock
# # - Created automatically during catalog updates
# # - Uses filelock package if available (recommended)
# # - 5-second timeout prevents permanent deadlocks
# # - Automatically cleaned up after operation completes

## ----user-inspection----------------------------------------------------------
# Ensure at least two versions exist for demonstration
# Use explicit alias = NULL to auto-detect current alias
versions <- st_versions(test_path, alias = NULL)
if (nrow(versions) < 2) {
  st_opts(versioning = "timestamp")
  tmp <- data.frame(x = seq_len(3L))
  st_save(tmp, test_path, code_label = "autocreate v1 (user-inspection)")
  Sys.sleep(1.1)
  tmp2 <- transform(tmp, y = x * 10L)
  st_save(tmp2, test_path, code_label = "autocreate v2 (user-inspection)")
  versions <- st_versions(test_path, alias = NULL)
  st_opts(versioning = "content")
}

# List all versions of an artifact (compact view)
versions[, .(version_id, created_at, size_bytes)]

# Get comprehensive info
info <- st_info(test_path)
info$catalog      # Latest version and count
info$snapshot_dir # Path to latest snapshot

# Load a specific historical version (previous), safely
if (nrow(versions) > 1) {
  old_version_try <- try(st_load(test_path, version = -1, alias = NULL), silent = TRUE)
  if (!inherits(old_version_try, "try-error")) {
    str(old_version_try)
  } else {
    cat("Previous version not available; skipping load.\n")
  }
}

## ----direct-catalog, eval=FALSE-----------------------------------------------
# # NOT recommended for users, but useful for debugging
# catalog_path <- fs::path(demo_dir, ".stamp", "catalog.qs2")
# if (fs::file_exists(catalog_path)) {
#   cat <- qs2::qs_read(catalog_path)
# 
#   # View all artifacts
#   print(cat$artifacts)
# 
#   # View all versions
#   print(cat$versions)
# }

## ----explore-snapshots--------------------------------------------------------
# Get all version directories for an artifact
# Version history is now stored NEXT TO the artifact, not in .stamp/
info <- st_info(test_path, alias = NULL)
artifact_dir <- fs::path_dir(info$sidecar$path)
versions_dir <- fs::path(artifact_dir, "versions")

if (fs::dir_exists(versions_dir)) {
  cat("Versions directory:", versions_dir, "\n\n")
  
  # List all version snapshots
  snapshot_dirs <- fs::dir_ls(versions_dir, type = "directory")
  cat("Found", length(snapshot_dirs), "version snapshots\n\n")
  
  # Inspect contents of latest snapshot
  if (length(snapshot_dirs) > 0) {
    latest <- snapshot_dirs[length(snapshot_dirs)]
    cat("Latest snapshot:", latest, "\n")
    fs::dir_tree(latest)
    
    # Read parents.json if present
    parents_file <- fs::path(latest, "parents.json")
    if (fs::file_exists(parents_file)) {
      parents <- jsonlite::read_json(parents_file)
      str(parents)
    }
  }
} else {
  cat("No versions directory found for this artifact\n")
}

## ----diagnose-missing, eval=FALSE---------------------------------------------
# # Check if .stamp exists
# stamp_dir <- fs::path(demo_dir, ".stamp")
# fs::dir_exists(stamp_dir)
# 
# # Check if catalog exists
# catalog_path <- fs::path(stamp_dir, "catalog.qs2")
# fs::file_exists(catalog_path)

## ----fix-missing, eval=FALSE--------------------------------------------------
# # Re-initialize (safe, won't delete existing data)
# st_init(demo_dir)
# 
# # If catalog is corrupt, it will be recreated empty on first st_save()
# # Note: This means version history is lost - restore from backup if available

## ----fix-schema, eval=FALSE---------------------------------------------------
# # Back up existing catalog
# backup_path <- fs::path(stamp_dir, "catalog_backup.qs2")
# fs::file_copy(catalog_path, backup_path, overwrite = TRUE)
# 
# # Option 1: Delete catalog and rebuild (LOSES VERSION HISTORY)
# fs::file_delete(catalog_path)
# # Next st_save() will create fresh catalog
# 
# # Option 2: Manual migration (advanced - contact package maintainer)

## ----disk-usage, eval=FALSE---------------------------------------------------
# # Check total .stamp/ state size
# stamp_dir <- fs::path(demo_dir, ".stamp")
# info <- fs::dir_info(stamp_dir, recurse = TRUE)
# data.table::data.table(stamp_state_mb = sum(info$size, na.rm = TRUE) / 1024^2)
# 
# # Find artifacts with large version histories
# # Version directories are now distributed: <artifact-dir>/versions/
# 
# all_files <- fs::dir_info(demo_dir, recurse = TRUE, all = TRUE)
# version_files <- all_files[grepl("/versions/", all_files$path) & all_files$type == "file", ]
# if (nrow(version_files) > 0) {
#   # Group by artifact and sum sizes of version files
#   version_files$artifact <- dirname(dirname(dirname(version_files$path)))
#   agg <- aggregate(size ~ artifact, version_files, sum)
#   agg[order(-agg$size), ]
# }

## ----fix-disk, eval=FALSE-----------------------------------------------------
# # Configure retention policy to auto-prune old versions
# st_opts(retain_versions = list(n = 10, days = 90))
# 
# # Manually prune versions for specific artifact
# st_prune_versions(test_path, policy = list(n = 5), dry_run = FALSE)
# 
# # Prune all artifacts (use with caution!)
# catalog <- st_catalog_query()
# for (artifact_path in catalog$path) {
#   st_prune_versions(artifact_path, policy = list(n = 5), dry_run = FALSE)
# }

## ----diagnose-timestamps------------------------------------------------------
# Check for invalid timestamps
vers <- st_versions(test_path)
bad_timestamps <- vers[is.na(created_at) | created_at == ""]
nrow(bad_timestamps)

## ----fix-lock, eval=FALSE-----------------------------------------------------
# # Safe to delete if no stamp operations are running
# lock_file <- fs::path(stamp_dir, "catalog.lock")
# if (fs::file_exists(lock_file)) {
#   fs::file_delete(lock_file)
# }

## ----backup-strategy, eval=FALSE----------------------------------------------
# # Periodic catalog backup
# backup_dir <- fs::path(demo_dir, "_backups")
# fs::dir_create(backup_dir)
# 
# # Backup the catalog (small, fast)
# catalog_src <- fs::path(demo_dir, ".stamp", "catalog.qs2")
# catalog_dst <- fs::path(backup_dir, sprintf("catalog_%s.qs2", Sys.Date()))
# fs::file_copy(catalog_src, catalog_dst, overwrite = TRUE)
# 
# # For critical projects, backup specific artifacts with version history
# # Version directories are now distributed: <artifact-dir>/versions/
# artifact_dir <- fs::path(demo_dir, "results", "model.rds")
# if (fs::dir_exists(artifact_dir)) {
#   artifact_backup <- fs::path(backup_dir, sprintf("model_artifact_%s", Sys.Date()))
#   fs::dir_copy(artifact_dir, artifact_backup, overwrite = TRUE)
# }
# 
# # Or backup the entire project directory (includes all artifacts + versions)
# project_backup <- fs::path(backup_dir, sprintf("project_%s", Sys.Date()))
# fs::dir_copy(demo_dir, project_backup, overwrite = TRUE)

## ----cleanup, include=FALSE---------------------------------------------------
# Clean up demo directory
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(demo_dir, recursive = TRUE)

