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

## -----------------------------------------------------------------------------
library(envsetup)

# Create temporary directory structure
dir <- fs::file_temp()
dir.create(dir)
dir.create(file.path(dir, "/demo/DEV/username/project1/script_library"), recursive = TRUE)

# Create a custom function
file_conn <- file(file.path(dir, "/demo/DEV/username/project1/script_library/test.R"))
writeLines(
"test <- function(){print('Hello from auto-sourced function!')}", file_conn)
close(file_conn)

# Write the configuration
config_path <- file.path(dir, "_envsetup.yml")
file_conn <- file(config_path)
writeLines(
  paste0(
"default:
  autos:
    dev_script_library: '", dir,"/demo/DEV/username/project1/script_library'"
  ), file_conn)
close(file_conn)

## -----------------------------------------------------------------------------
# Load configuration and apply it
envsetup_config <- config::get(file = config_path)
rprofile(envsetup_config)

## -----------------------------------------------------------------------------
# See what functions are available
objects()

# Use the function directly (no manual sourcing needed!)
test()

## -----------------------------------------------------------------------------
# Create production script library
dir.create(file.path(dir, "/demo/PROD/project1/script_library"), recursive = TRUE)

# Add production functions
file_conn <- file(file.path(dir, "/demo/PROD/project1/script_library/test2.R"))
writeLines(
"test2 <- function(){print('Hello from production function!')}", file_conn)
close(file_conn)

# Update configuration with multiple libraries
file_conn <- file(config_path)
writeLines(
  paste0(
"default:
  autos:
    dev_script_library: '", dir,"/demo/DEV/username/project1/script_library'
    prod_script_library: '", dir,"/demo/PROD/project1/script_library'"
  ), file_conn)
close(file_conn)

# Reload configuration
envsetup_config <- config::get(file = config_path)
rprofile(envsetup_config)

## -----------------------------------------------------------------------------
# Check search path - now includes both libraries
# Functions from both libraries are available
objects()

# Use functions from both libraries
test()   # From dev library
test2()  # From prod library

## -----------------------------------------------------------------------------
# Create a function that might conflict
summary_stats <- function(data) {
  print("Original summary function")
}

# Create a script with the same function name
conflict_dir <- file.path(dir, "conflict_demo")
dir.create(conflict_dir)

file_conn <- file(file.path(conflict_dir, "stats.R"))
writeLines(
"summary_stats <- function(data) {
  print('Updated summary function from the new conflict_demo script')
}", file_conn)
close(file_conn)

# Add to configuration
file_conn <- file(config_path)
writeLines(
  paste0(
"default:
  autos:
    dev_script_library: '", dir,"/demo/DEV/username/project1/script_library'
    prod_script_library: '", dir,"/demo/PROD/project1/script_library'
    conflict_demo: '", conflict_dir, "'"
  ), file_conn)
close(file_conn)

# When we reload, the auto-sourced version will overwrite the original
envsetup_config <- config::get(file = config_path)
rprofile(envsetup_config)

# Test which version we have now
summary_stats()

## -----------------------------------------------------------------------------
# Configuration that blanks out dev scripts in production
file_conn <- file(config_path)
writeLines(
  paste0(
"default:
  autos:
    dev_script_library: '", dir,"/demo/DEV/username/project1/script_library'
    prod_script_library: '", dir,"/demo/PROD/project1/script_library'

prod:
  autos:
    dev_script_library: NULL"  # NULL disables this library
  ), file_conn)
close(file_conn)

# Load production configuration
envsetup_config <- config::get(file = config_path, config = "prod")
rprofile(envsetup_config)

## -----------------------------------------------------------------------------
# Functions from production only
objects()

# Use functions from production only
test2()  # From prod library

## -----------------------------------------------------------------------------
# Create a function in global environment
my_function <- function() {
  print("Original function from global environment")
}

# Check it works
my_function()

# Create a script with the same function name
dir <- fs::file_temp()
dir.create(dir)
script_dir <- file.path(dir, "scripts")
dir.create(script_dir)

file_conn <- file(file.path(script_dir, "my_function.R"))
writeLines(
"my_function <- function() {
  print('Updated function from auto-sourced script')
}", file_conn)
close(file_conn)

# Configuration with default overwrite = TRUE
config_path <- file.path(dir, "_envsetup.yml")
file_conn <- file(config_path)
writeLines(
  paste0(
"default:
  autos:
    my_scripts: '", script_dir, "'"
  ), file_conn)
close(file_conn)

# Load configuration - this will overwrite the existing function
envsetup_config <- config::get(file = config_path)
rprofile(envsetup_config)

# The function has been overwritten
my_function()

## -----------------------------------------------------------------------------
# clean up previous runs, removing all previously attached autos
detach_autos()

# Create a function in global environment
my_function <- function() {
  print("Original function from global environment")
}

# Check it works
my_function()

# Create a script with the same function name
dir <- fs::file_temp()
dir.create(dir)
script_dir <- file.path(dir, "scripts")
dir.create(script_dir)

file_conn <- file(file.path(script_dir, "my_function.R"))
writeLines(
"my_function <- function() {
  print('Updated function from auto-sourced script')
}", file_conn)
close(file_conn)

# Configuration with default overwrite = FALSE
config_path <- file.path(dir, "_envsetup.yml")
file_conn <- file(config_path)
writeLines(
  paste0(
"default:
  autos:
    my_scripts: '", script_dir, "'"
  ), file_conn)
close(file_conn)

envsetup_config <- config::get(file = config_path)
rprofile(envsetup_config, overwrite = FALSE)

my_function()


## -----------------------------------------------------------------------------
# Create multiple functions to demonstrate conflict detection
existing_func1 <- function() "I exist in global"
existing_func2 <- function() "I also exist in global"

# Create script with mix of new and conflicting functions
file_conn <- file(file.path(script_dir, "mixed_functions.R"))
writeLines(
"# This will conflict with existing function
existing_func1 <- function() {
  'Updated from script'
}

# This is a new function
new_func <- function() {
  'Brand new function'
}

# This will also conflict
existing_func2 <- function() {
  'Also updated from script'
}", file_conn)
close(file_conn)

# Update configuration
file_conn <- file(config_path)
writeLines(
  paste0(
"default:
  autos:
    my_scripts: '", script_dir, "'"
  ), file_conn)
close(file_conn)

# Reload - watch the detailed output
envsetup_config <- config::get(file = config_path)
rprofile(envsetup_config)

## -----------------------------------------------------------------------------
# After sourcing functions, you can access the metadata
# Note: This example shows the concept - actual access depends on envsetup internals

# Create some functions to demonstrate metadata tracking
metadata_demo_dir <- file.path(dir, "metadata_demo")
dir.create(metadata_demo_dir)

# Create multiple scripts with different functions
file_conn <- file(file.path(metadata_demo_dir, "data_functions.R"))
writeLines(
"load_data <- function(file) {
  paste('Loading data from:', file)
}

clean_data <- function(data) {
  paste('Cleaning data with', nrow(data), 'rows')
}", file_conn)
close(file_conn)

file_conn <- file(file.path(metadata_demo_dir, "plot_functions.R"))
writeLines(
"create_plot <- function(data) {
  paste('Creating plot for', ncol(data), 'variables')
}

save_plot <- function(plot, filename) {
  paste('Saving plot to:', filename)
}", file_conn)
close(file_conn)

# Update configuration to include metadata demo
file_conn <- file(config_path)
writeLines(
  paste0(
"default:
  autos:
    metadata_demo: '", metadata_demo_dir, "'"
  ), file_conn)
close(file_conn)

# Source the functions
envsetup_config <- config::get(file = config_path)
rprofile(envsetup_config)

# The system now tracks which script each function came from
cat("Functions sourced with metadata tracking:")
knitr::kable(envsetup_environment$object_metadata)

## ----echo = FALSE-------------------------------------------------------------
# Clean up
unlink(dir, recursive=TRUE)

