#!/bin/bash
# Batch refactor try-catch to Result pattern
# Usage: ./batch-refactor.sh [files...]

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
BACKUP_DIR="$PROJECT_ROOT/.backups/$(date +%Y%m%d_%H%M%S)"

mkdir -p "$BACKUP_DIR"

echo "🔧 Batch Refactoring: try-catch → Result Pattern"
echo "════════════════════════════════════════════════════"
echo ""

# Function to refactor a single file
refactor_file() {
    local file="$1"
    local filename=$(basename "$file")

    if [ ! -f "$file" ]; then
        echo "❌ File not found: $file"
        return 1
    fi

    echo "📄 Processing: $filename"

    # Create backup
    cp "$file" "$BACKUP_DIR/$filename.bak"
    echo "   ✓ Backup created"

    # Pattern 1: Add result.nu import if not present
    if ! grep -q "use.*result.nu" "$file"; then
        # Find the first 'use' or 'def' or 'export' line
        line_num=$(grep -n "^use\|^def\|^export" "$file" | head -1 | cut -d: -f1)
        if [ -n "$line_num" ]; then
            sed -i.tmp "${line_num}i\\
use lib_provisioning/result.nu *
" "$file" 2>/dev/null || true
            rm -f "$file.tmp"
            echo "   ✓ Added result.nu import"
        fi
    fi

    # Pattern 2: bash-check: try { bash -c ... | complete } catch { {exit_code: 1, stderr: $err} }
    # Simple pattern: try { bash -c ... | complete } catch {|err| {exit_code: 1, stderr: $err} }
    if grep -q 'try.*bash.*complete.*catch' "$file"; then
        # Count occurrences
        count=$(grep -c 'try.*bash.*complete.*catch' "$file" || echo 0)
        echo "   ⚠️  Found $count bash-check patterns (manual review needed)"
    fi

    # Pattern 3: bash-or: try { bash ... } catch { null/fallback }
    if grep -q 'try.*{$' "$file" && grep -q '} catch.*{$' "$file"; then
        count=$(grep -c 'try.*bash' "$file" || echo 0)
        if [ $count -gt 0 ]; then
            echo "   ⚠️  Found $count potential bash operations in try blocks"
        fi
    fi

    # Pattern 4: json-read: try { open ... | from json } catch { ... }
    if grep -q 'try.*open.*from json' "$file"; then
        count=$(grep -c 'open.*from json' "$file" || echo 0)
        echo "   ⚠️  Found $count JSON operations (use json-read helper)"
    fi

    # Verify syntax
    if nu --check "$file" 2>/dev/null; then
        echo "   ✓ Syntax check passed"
    else
        echo "   ⚠️  Syntax check failed - review required"
        cp "$BACKUP_DIR/$filename.bak" "$file"
        return 1
    fi

    echo "   ✅ Ready for manual review"
    echo ""
}

# Main execution
if [ $# -eq 0 ]; then
    echo "No files specified. Analyzing all .nu files..."
    echo ""

    # Find files with try-catch
    files=$(find "$PROJECT_ROOT/provisioning/core/nulib" -name "*.nu" -exec grep -l "try\s*{" {} \; | head -20)

    echo "Top 20 files with try-catch blocks:"
    echo "$files" | nl
    echo ""
    echo "Usage: $0 [files...]"
    echo "Example: $0 lib_provisioning/deploy.nu lib_provisioning/config/accessor.nu"
    exit 0
fi

# Process specified files
for file in "$@"; do
    if [ ! -f "$file" ]; then
        # Try relative to project root
        file="$PROJECT_ROOT/$file"
    fi

    if [ -f "$file" ]; then
        refactor_file "$file" || true
    fi
done

echo "════════════════════════════════════════════════════"
echo "✅ Refactoring complete!"
echo ""
echo "📋 Next steps:"
echo "1. Review changes: git diff"
echo "2. For each file, apply manual refactoring following the pattern"
echo "3. Commit with: git add . && git commit -m 'refactor: eliminate try-catch'"
echo ""
echo "📁 Backups stored in: $BACKUP_DIR"
echo ""
