#!/usr/bin/env nu
# Simplified try-catch refactoring assistant
# Identifies patterns and generates refactoring suggestions
# User reviews and applies changes incrementally

def analyze-try-catch-files [] {
    print "🔍 Analyzing try-catch patterns..."
    print ""

    let files = (
        glob "provisioning/core/nulib/**/*.nu"
        | par-each -b 10 {|f|
            let has_try_result = (do {
                    open $f | str contains "try\s*{"
                } | complete)
            let has_try_catch = if $has_try_result.exit_code == 0 { $has_try_result.stdout } else { false }

            if $has_try_catch {
                let count_result = (do {
                        open $f | grep "try\s*{" | wc -l
                    } | complete)
                let count = if $count_result.exit_code == 0 { ($count_result.stdout | into int) } else { 0 }
                {file: $f, count: $count}
            } else {
                null
            }
        }
        | filter {|x| $x != null}
        | sort-by count -r
    )

    print $"Found ($($files | length)) files with try-catch blocks"
    print ""

    # Show top files by try-catch count
    print "Top files by try-catch density:"
    $files | first 20 | each {|item|
        print $"  • ($item.count | str pad -l 2) patterns in ($item.file | path basename)"
    }

    print ""
    print "Pattern categories:"
    print "  1. bash-check: try { bash -c \$cmd | complete } catch { {exit_code: 1, stderr: \$err} }"
    print "  2. bash-or: try { bash -c \$cmd } catch { fallback }"
    print "  3. json-read: try { open \$file | from json } catch { default }"
    print "  4. try-wrap: try { operation } catch { error_record }"
    print ""

    # Suggest strategy
    print "📋 Recommended Strategy:"
    print ""
    print "Phase 1: Already completed (31 try-catch refactored)"
    print "  • lib_minimal.nu ✅"
    print "  • vm_lifecycle.nu ✅"
    print "  • vm_hosts.nu ✅"
    print "  • backend_libvirt.nu ✅"
    print "  • vm_persistence.nu (partial) ⚠️"
    print ""

    print "Phase 2: Priority files (100+ try-catch total)"
    print "  • deploy.nu (13 try-catch)"
    print "  • mfa/commands.nu (20 try-catch)"
    print "  • tests/*.nu (35+ try-catch)"
    print "  • config/*.nu (31 try-catch)"
    print "  • infra_validator/*.nu (31 try-catch)"
    print ""

    print "Phase 3: Remaining VM/integration files (150+ try-catch)"
    print "  • VM core modules"
    print "  • Integration modules"
    print "  • Utility modules"
    print ""

    $files
}

def generate-refactoring-plan [files: list] {
    print "📊 REFACTORING PLAN"
    print "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    print ""

    let total_try_catch = (
        $files
        | map {|x| $x.count}
        | math sum
    )

    let by_priority = (
        $files
        | sort-by count -r
        | group-by {|x|
            if $x.count >= 10 { "critical" }
            else if $x.count >= 5 { "high" }
            else if $x.count >= 2 { "medium" }
            else { "low" }
        }
    )

    print $"Total try-catch blocks: ($total_try_catch)"
    print ""

    for {category, items} in ($by_priority | to entries) {
        print $"($category | str upcase) PRIORITY (($items | length) files)"
        $items | each {|f|
            print $"  • ($f.file | path basename) - ($f.count) patterns"
        }
        print ""
    }
}

def create-refactoring-checklist [files: list] {
    print "✅ REFACTORING CHECKLIST"
    print "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    print ""

    print "Before refactoring each file:"
    print "  1. Read .claude/guidelines/nushell.md section 7 (Result Pattern)"
    print "  2. Identify try-catch patterns (bash-check, bash-or, json-read, try-wrap)"
    print "  3. Add 'use lib_provisioning/result.nu *' import"
    print "  4. Replace try-catch with helpers"
    print "  5. Add guard comments for clarity"
    print "  6. Test with: nu --check filename.nu"
    print ""

    print "Files ready for refactoring (sorted by impact):"
    print ""

    let critical = ($files | where {|x| $x.count >= 10} | first 5)

    $critical | enumerate | each {|x|
        print $"($x.index + 1). ($x.item.file | path basename)"
        print $"   Try-catch blocks: ($x.item.count)"
        print $"   Effort: High | Impact: High"
        print ""
    }
}

# Main execution
def main [] {
    print "🔧 Automated Try-Catch Refactoring Assistant"
    print "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    print ""

    # Analyze
    let files = (analyze-try-catch-files)

    print ""
    print "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    print ""

    # Plan
    generate-refactoring-plan $files

    print "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    print ""

    # Checklist
    create-refactoring-checklist $files

    print "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    print ""
    print "📝 Next Steps:"
    print "1. Pick highest-priority file (top of critical list)"
    print "2. Follow refactoring checklist"
    print "3. Commit each file individually"
    print "4. Repeat until all refactored"
    print ""
    print "💡 Tip: Use 'nu --check filename.nu' to validate syntax"
    print "💡 Tip: grep patterns to identify try-catch blocks quickly"
}

main
