#!/bin/bash

# Agent 4: ENV Migrator
# Migrates ENV references to config accessors in a specific file
# Usage: ./04_migrate_env.sh path/to/file.nu

if [ $# -eq 0 ]; then
    echo "Usage: $0 <file_path>"
    echo "Example: $0 core/nulib/servers/utils.nu"
    exit 1
fi

FILE_PATH="$1"

if [ ! -f "$FILE_PATH" ]; then
    echo "❌ Error: File $FILE_PATH not found"
    exit 1
fi

echo "🔄 Launching ENV Migrator Agent for: $FILE_PATH"

# Create knowledge bundle for agent
KNOWLEDGE=$(cat << 'EOF'
# ENV Migration Mappings

## Replace These:
$env.PROVISIONING              → (get-base-path)
$env.PROVISIONING_DEBUG         → (is-debug-enabled)
$env.PROVISIONING_PROVIDERS_PATH → (get-providers-path)
$env.PROVISIONING_TASKSERVS_PATH → (get-taskservs-path)
$env.PROVISIONING_TOOLS_PATH     → (get-tools-path)
$env.PROVISIONING_TEMPLATES_PATH → (get-templates-path)

## Keep These (Runtime State):
$env.PROVISIONING_ARGS    # Command arguments - DO NOT CHANGE
$env.PROVISIONING_OUT     # Output redirection - DO NOT CHANGE
$env.NOW                  # Timestamps - DO NOT CHANGE
$env.CURRENT_*            # Context variables - DO NOT CHANGE

## Migration Pattern:
Before: if $env.PROVISIONING_DEBUG { ... }
After:  if (is-debug-enabled) { ... }

Before: let path = $env.PROVISIONING_PROVIDERS_PATH
After:  let path = (get-providers-path)

## Add Import:
Add: use ../lib_provisioning/config/accessor.nu *
(At top of file if not already present)
EOF
)

# Create backup
cp "$FILE_PATH" "$FILE_PATH.backup"
echo "📁 Created backup: $FILE_PATH.backup"

# Launch Claude Code agent
claude-code task \
  --description "Migrate ENV references in $FILE_PATH" \
  --prompt "$KNOWLEDGE

TARGET FILE: $FILE_PATH
TASK: Replace ENV variables with config accessor functions
REQUIREMENTS:
1. Keep PROVISIONING_ARGS, PROVISIONING_OUT, NOW, CURRENT_* as ENV
2. Add config accessor import if needed
3. Preserve all functionality
4. Test syntax after changes

OUTPUT: Report what was migrated + syntax validation result" \
  --type "general-purpose"

# Validate the migration
echo "🧪 Testing syntax..."
if nu --ide-check "$FILE_PATH" 2>/dev/null; then
    echo "✅ Migration syntax validation passed for $FILE_PATH"
    rm "$FILE_PATH.backup"

    # Update migration state
    echo "$(date): Migrated ENV references in $FILE_PATH" >> .migration/state/migrations_applied.log
else
    echo "❌ Migration syntax validation failed! Restoring backup..."
    mv "$FILE_PATH.backup" "$FILE_PATH"
fi