#!/bin/bash

# Agent 2: Syntax Fixer
# Fixes syntax errors in a specific file
# Usage: ./02_fix_syntax.sh path/to/file.nu

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

FILE_PATH="$1"

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

echo "🔧 Launching Syntax Fixer Agent for: $FILE_PATH"

# Create knowledge bundle for agent
KNOWLEDGE=$(cat << 'EOF'
# Syntax Fix Patterns

## Critical Fixes:
1. $"(get-provisioning-args)? | default "") "
   → ((get-provisioning-args) | default "")

2. ^$"(get-provisioning-name))" -mod server
   → ^(get-provisioning-name) -mod server

3. let ops = $"(get-provisioning-args)? | default "") "
   → let ops = ((get-provisioning-args) | default "")

## Rules:
- Always wrap function calls in expressions with parentheses
- Remove extra parentheses from commands
- Preserve all logic and functionality
- Test syntax after each fix

## Validation:
Run: nu --ide-check FILE_PATH after changes
EOF
)

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

# Launch Claude Code agent
claude-code task \
  --description "Fix syntax errors in $FILE_PATH" \
  --prompt "$KNOWLEDGE

TARGET FILE: $FILE_PATH
TASK: Fix all syntax errors in this file only
REQUIREMENT: Preserve functionality, fix only syntax
OUTPUT: Report what was fixed + confirmation that syntax is valid" \
  --type "general-purpose"

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

    # Update migration state
    echo "$(date): Fixed syntax in $FILE_PATH" >> .migration/state/fixes_applied.log
else
    echo "❌ Syntax validation failed! Restoring backup..."
    mv "$FILE_PATH.backup" "$FILE_PATH"
fi