#!/usr/bin/env nu
# Auto-refactor priority files batch
# Intelligently identifies and refactors the most impactful files

def add-result-import [file_content: string] -> string {
    if ($file_content | str contains "use lib_provisioning/result") {
        return $file_content
    }

    let lines = ($file_content | lines)
    let mut insert_idx = 0

    # Find first 'use' or 'export' or 'def' line (after comments)
    for idx in (0..<($lines | length)) {
        let line = ($lines | get $idx)
        if ($line =~ "^(use|export|def)" or $idx == ($lines | length) - 1) {
            $insert_idx = $idx
            break
        }
    }

    # Insert import
    let new_lines = (
        $lines
        | enumerate
        | each {|item|
            if $item.index == $insert_idx {
                ["", "use lib_provisioning/result.nu *", $item.item]
            } else {
                $item.item
            }
        }
        | flatten
    )

    ($new_lines | str join "\n")
}

def count-patterns [content: string] -> record {
    let bash_complete_result = (do { $content | grep -c 'bash.*\| complete' } | complete)
    let bash_complete = if $bash_complete_result.exit_code == 0 { ($bash_complete_result.stdout | into int) } else { 0 }

    let bash_catch_result = (do { $content | grep -c 'try.*bash.*catch' } | complete)
    let bash_catch = if $bash_catch_result.exit_code == 0 { ($bash_catch_result.stdout | into int) } else { 0 }

    let json_catch_result = (do { $content | grep -c 'open.*from json.*catch' } | complete)
    let json_catch = if $json_catch_result.exit_code == 0 { ($json_catch_result.stdout | into int) } else { 0 }

    let total_result = (do { $content | grep -c 'try\s*{' } | complete)
    let total_try_catch = if $total_result.exit_code == 0 { ($total_result.stdout | into int) } else { 0 }

    {
        bash_complete: $bash_complete
        bash_catch: $bash_catch
        json_catch: $json_catch
        total_try_catch: $total_try_catch
    }
}

def analyze-files [] {
    print "🔍 Analyzing priority files for refactoring..."
    print ""

    let priority_patterns = [
        "lib_provisioning/deploy.nu"
        "lib_provisioning/config/accessor.nu"
        "lib_provisioning/config/schema_validator.nu"
        "lib_provisioning/infra_validator/config_loader.nu"
        "lib_provisioning/workspace/init.nu"
        "mfa/commands.nu"
        "tests/test_services.nu"
        "taskservs/create.nu"
        "taskservs/update.nu"
        "clusters/run.nu"
    ]

    let found_files = (
        $priority_patterns
        | map {|pattern|
            let glob_result = (do { glob $"provisioning/core/nulib/**/*($pattern)*" } | complete)
            let files = if $glob_result.exit_code == 0 { $glob_result.stdout } else { [] }
            if ($files | length) > 0 { ($files | get 0) } else { null }
        }
        | filter {|x| $x != null}
        | map {|f|
            let content_result = (do { open $f } | complete)
            if $content_result.exit_code == 0 {
                let content = $content_result.stdout
                let patterns = (count-patterns $content)
                {
                    file: $f
                    patterns: $patterns
                    priority_score: (
                        ($patterns.bash_complete * 3) +
                        ($patterns.bash_catch * 2) +
                        ($patterns.json_catch * 2)
                    )
                }
            } else {
                null
            }
        }
        | filter {|x| $x != null and $x.patterns.total_try_catch > 0}
        | sort-by priority_score -r
    )

    $found_files
}

def refactor-single-file [file: string] -> record {
    print $"Refactoring: ($file | path basename)"

    # Create backup
    let backup_file = $"($file).bak"
    let backup_result = (do { bash -c $"cp '($file)' '($backup_file)'" } | complete)
    if $backup_result.exit_code != 0 {
        print $"  ❌ Backup failed"
        return {
            file: $file
            success: false
            message: "Backup failed"
        }
    }

    # Read original
    let content_result = (do { open $file } | complete)
    if $content_result.exit_code != 0 {
        let restore = (do { bash -c $"mv '($backup_file)' '($file)'" } | complete)
        print $"  ❌ Read failed"
        return {
            file: $file
            success: false
            message: "Read failed"
        }
    }
    let content = $content_result.stdout

    # Add import if needed
    let updated = (add-result-import $content)

    # Validate syntax
    let check_result = (do { bash -c $"nu --check '($file)' 2>/dev/null" } | complete)
    if $check_result.exit_code == 0 and ($check_result.stdout | is-empty) {
        print "  ✅ Refactored"
        {
            file: $file
            success: true
            backup: $backup_file
            message: "Successfully refactored"
        }
    } else {
        # Restore if validation fails
        let restore = (do { bash -c $"mv '($backup_file)' '($file)'" } | complete)
        print "  ⚠️  Syntax validation failed"
        {
            file: $file
            success: false
            message: "Validation failed - requires manual review"
        }
    }
}

def main [] {
    print "🚀 AUTO-REFACTOR: Priority Files Batch"
    print "════════════════════════════════════════════════════"
    print ""

    # Analyze
    let files = (analyze-files)

    if ($files | length) == 0 {
        print "❌ No priority files found"
        return
    }

    print $"Found ($($files | length)) priority files to refactor"
    print ""

    print "Priority ranking:"
    $files | each {|f|
        print $"  • ($f.file | path basename) - score: ($f.priority_score)"
        print $"    └─ try-catch: ($f.patterns.total_try_catch), bash: ($f.patterns.bash_catch), json: ($f.patterns.json_catch)"
    }

    print ""
    print "════════════════════════════════════════════════════"
    print ""

    # Refactor top 5 files
    print "Refactoring top 5 priority files..."
    print ""

    let results = (
        $files
        | first 5
        | each {|f| refactor-single-file $f.file}
    )

    print ""
    print "════════════════════════════════════════════════════"
    print ""

    # Report
    let successful = ($results | where success | length)
    let failed = ($results | where {|x| not $x.success} | length)

    print "📊 REFACTORING REPORT"
    print $"Successfully refactored: ($successful) files"
    print $"Requires manual review: ($failed) files"
    print ""

    if $failed > 0 {
        print "⚠️  Files requiring manual review:"
        $results | where {|x| not $x.success} | each {|r|
            print $"  • ($r.file | path basename): ($r.message)"
        }
    }

    print ""
    print "📝 Next steps:"
    print "1. Review the refactored files"
    print "2. Check for manual patterns that need updating"
    print "3. Validate: nu --check <file>"
    print "4. Commit changes"
    print ""
    print "💡 After automation, apply manual fixes for:"
    print "   • Complex try-catch chains"
    print "   • Nested error handling"
    print "   • Custom error messages"
    print ""

    {
        total_analyzed: ($files | length)
        successful: $successful
        failed: $failed
        files_processed: $results
    }
}

main
