# Infrastructure Validation Commands
# Integrates validation system into the main provisioning CLI

# Import validation functions
use ../lib_provisioning/infra_validator/validator.nu *
use ../lib_provisioning/infra_validator/agent_interface.nu *

# Main validation command
export def "main validate" [
    infra_path?: string         # Path to infrastructure configuration (default: current directory)
    ...args                     # Additional arguments
    --fix (-f)                  # Auto-fix issues where possible
    --report (-r): string = "md" # Report format (md|yaml|json|all)
    --output (-o): string = "./validation_results" # Output directory
    --severity (-s): string = "warning" # Minimum severity (info|warning|error|critical)
    --ci                        # CI/CD mode (exit codes, no colors, minimal output)
    --dry-run (-d)              # Show what would be fixed without actually fixing
    --rules: string             # Comma-separated list of specific rules to run
    --exclude: string           # Comma-separated list of rules to exclude
    --verbose (-v)              # Verbose output (show all details)
    --help (-h)                 # Show detailed help
]: nothing -> nothing {

    if $help {
        show_validation_help
        return
    }

    let target_path = if ($infra_path | is-empty) {
        "."
    } else {
        $infra_path
    }

    if not ($target_path | path exists) {
        if not $ci {
            print $"🛑 Infrastructure path not found: ($target_path)"
            print "Use --help for usage information"
        }
        exit 1
    }

    if not $ci {
        print_validation_banner
        print $"🔍 Validating infrastructure: ($target_path | path expand)"
        print ""
    }

    # Validate input parameters
    let valid_severities = ["info", "warning", "error", "critical"]
    if ($severity not-in $valid_severities) {
        if not $ci {
            print $"🛑 Invalid severity level: ($severity)"
            print $"Valid options: ($valid_severities | str join ', ')"
        }
        exit 1
    }

    let valid_formats = ["md", "markdown", "yaml", "yml", "json", "all"]
    if ($report not-in $valid_formats) {
        if not $ci {
            print $"🛑 Invalid report format: ($report)"
            print $"Valid options: ($valid_formats | str join ', ')"
        }
        exit 1
    }

    # Set up environment
    setup_validation_environment $verbose

    # Run validation using the validator engine
    try {
        let result = (main $target_path
            --fix=$fix
            --report=$report
            --output=$output
            --severity=$severity
            --ci=$ci
            --dry-run=$dry_run
        )

        if not $ci {
            print ""
            print $"📊 Reports generated in: ($output)"
            show_validation_next_steps $result
        }

    } catch {|error|
        if not $ci {
            print $"🛑 Validation failed: ($error.msg)"
        }
        exit 4
    }
}

# Quick validation subcommand
export def "main validate quick" [
    infra_path?: string
    --fix (-f)
]: nothing -> nothing {
    let target = if ($infra_path | is-empty) { "." } else { $infra_path }

    print "🚀 Quick Infrastructure Validation"
    print "=================================="
    print ""

    main validate $target --severity="error" --report="md" --output="./quick_validation" --fix=$fix
}

# CI validation subcommand
export def "main validate ci" [
    infra_path: string
    --format (-f): string = "yaml"
    --fix
]: nothing -> nothing {
    main validate $infra_path --ci --report=$format --output="./ci_validation" --fix=$fix
}

# Full validation subcommand
export def "main validate full" [
    infra_path?: string
    --output (-o): string = "./full_validation"
]: nothing -> nothing {
    let target = if ($infra_path | is-empty) { "." } else { $infra_path }

    print "🔍 Full Infrastructure Validation"
    print "================================="
    print ""

    main validate $target --severity="info" --report="all" --output=$output --verbose
}

# Agent interface for automation
export def "main validate agent" [
    infra_path: string
    --auto_fix: bool = false
    --severity_threshold: string = "warning"
    --format: string = "json"
]: nothing -> nothing {

    print "🤖 Agent Validation Mode"
    print "========================"
    print ""

    let result = (validate_for_agent $infra_path --auto_fix=$auto_fix --severity_threshold=$severity_threshold)

    match $format {
        "json" => { $result | to json },
        "yaml" => { $result | to yaml },
        _ => { $result }
    }
}

# List available rules
export def "main validate rules" []: nothing -> nothing {
    print "📋 Available Validation Rules"
    print "============================"
    print ""

    let rules = [
        {id: "VAL001", category: "syntax", severity: "critical", name: "YAML Syntax Validation", auto_fix: false}
        {id: "VAL002", category: "compilation", severity: "critical", name: "KCL Compilation Check", auto_fix: false}
        {id: "VAL003", category: "syntax", severity: "error", name: "Unquoted Variable References", auto_fix: true}
        {id: "VAL004", category: "schema", severity: "error", name: "Required Fields Validation", auto_fix: false}
        {id: "VAL005", category: "best_practices", severity: "warning", name: "Resource Naming Conventions", auto_fix: true}
        {id: "VAL006", category: "security", severity: "error", name: "Basic Security Checks", auto_fix: false}
        {id: "VAL007", category: "compatibility", severity: "warning", name: "Version Compatibility Check", auto_fix: false}
        {id: "VAL008", category: "networking", severity: "error", name: "Network Configuration Validation", auto_fix: false}
    ]

    for rule in $rules {
        let auto_fix_indicator = if $rule.auto_fix { "🔧" } else { "👁️" }
        let severity_color = match $rule.severity {
            "critical" => "🚨"
            "error" => "❌"
            "warning" => "⚠️"
            _ => "ℹ️"
        }

        print $"($auto_fix_indicator) ($severity_color) ($rule.id): ($rule.name)"
        print $"   Category: ($rule.category) | Severity: ($rule.severity) | Auto-fix: ($rule.auto_fix)"
        print ""
    }

    print "Legend:"
    print "🔧 = Auto-fixable | 👁️ = Manual fix required"
    print "🚨 = Critical | ❌ = Error | ⚠️ = Warning | ℹ️ = Info"
}

# Test validation system
export def "main validate test" []: nothing -> nothing {
    print "🧪 Testing Validation System"
    print "============================="
    print ""

    # Run the test script
    try {
        ^nu test_validation.nu
    } catch {|error|
        print $"❌ Test failed: ($error.msg)"
        exit 1
    }
}

def print_validation_banner []: nothing -> nothing {
    print "╔══════════════════════════════════════════════════════════════╗"
    print "║            Infrastructure Validation & Review Tool           ║"
    print "║                    Cloud Native Provisioning               ║"
    print "╚══════════════════════════════════════════════════════════════╝"
    print ""
}

def show_validation_help []: nothing -> nothing {
    print "Infrastructure Validation & Review Tool"
    print "========================================"
    print ""
    print "USAGE:"
    print "    ./core/nulib/provisioning validate [SUBCOMMAND] [INFRA_PATH] [OPTIONS]"
    print ""
    print "SUBCOMMANDS:"
    print "    (none)      Full validation with customizable options"
    print "    quick       Quick validation focusing on errors and critical issues"
    print "    ci          CI/CD optimized validation with structured output"
    print "    full        Comprehensive validation including info-level checks"
    print "    agent       Agent/automation interface with JSON output"
    print "    rules       List all available validation rules"
    print "    test        Run validation system self-tests"
    print ""
    print "ARGUMENTS:"
    print "    INFRA_PATH    Path to infrastructure configuration (default: current directory)"
    print ""
    print "OPTIONS:"
    print "    -f, --fix              Auto-fix issues where possible"
    print "    -r, --report FORMAT    Report format: md, yaml, json, all (default: md)"
    print "    -o, --output DIR       Output directory (default: ./validation_results)"
    print "    -s, --severity LEVEL   Minimum severity: info, warning, error, critical (default: warning)"
    print "    --ci                   CI/CD mode (exit codes, no colors, minimal output)"
    print "    -d, --dry-run          Show what would be fixed without actually fixing"
    print "    --rules RULES          Comma-separated list of specific rules to run"
    print "    --exclude RULES        Comma-separated list of rules to exclude"
    print "    -v, --verbose          Verbose output"
    print "    -h, --help             Show this help"
    print ""
    print "EXIT CODES:"
    print "    0    All validations passed"
    print "    1    Critical errors found (blocks deployment)"
    print "    2    Errors found (should be fixed)"
    print "    3    Only warnings found"
    print "    4    Validation system error"
    print ""
    print "EXAMPLES:"
    print ""
    print "    # Validate current directory"
    print "    ./core/nulib/provisioning validate"
    print ""
    print "    # Quick validation with auto-fix"
    print "    ./core/nulib/provisioning validate quick klab/sgoyol --fix"
    print ""
    print "    # CI/CD validation"
    print "    ./core/nulib/provisioning validate ci klab/sgoyol --format yaml"
    print ""
    print "    # Full validation with all reports"
    print "    ./core/nulib/provisioning validate full klab/sgoyol --output ./reports"
    print ""
    print "    # Agent mode for automation"
    print "    ./core/nulib/provisioning validate agent klab/sgoyol --auto_fix"
    print ""
    print "    # List available rules"
    print "    ./core/nulib/provisioning validate rules"
    print ""
    print "    # Test the validation system"
    print "    ./core/nulib/provisioning validate test"
    print ""
}

def setup_validation_environment [verbose: bool]: nothing -> nothing {
    # Check required dependencies
    let dependencies = ["kcl"]  # Add other required tools

    for dep in $dependencies {
        let check = (^bash -c $"type -P ($dep)" | complete)
        if $check.exit_code != 0 {
            if $verbose {
                print $"⚠️  Warning: ($dep) not found in PATH"
                print "   Some validation rules may be skipped"
            }
        } else if $verbose {
            print $"✅ ($dep) found"
        }
    }
}

def show_validation_next_steps [result: record]: nothing -> nothing {
    let exit_code = $result.exit_code

    print "🎯 Next Steps:"
    print "=============="

    match $exit_code {
        0 => {
            print "✅ All validations passed! Your infrastructure is ready for deployment."
            print ""
            print "Recommended actions:"
            print "• Review the validation report for any enhancement suggestions"
            print "• Consider setting up automated validation in your CI/CD pipeline"
            print "• Share the report with your team for documentation"
        }
        1 => {
            print "🚨 Critical issues found that block deployment:"
            print ""
            print "Required actions:"
            print "• Fix all critical issues before deployment"
            print "• Review the validation report for specific fixes needed"
            print "• Re-run validation after fixes: ./core/nulib/provisioning validate --fix"
            print "• Consider using --dry-run first to preview fixes"
        }
        2 => {
            print "❌ Errors found that should be resolved:"
            print ""
            print "Recommended actions:"
            print "• Review and fix the errors in the validation report"
            print "• Use --fix flag to auto-resolve fixable issues"
            print "• Test your infrastructure after fixes"
            print "• Consider the impact of proceeding with these errors"
        }
        3 => {
            print "⚠️  Warnings found - review recommended:"
            print ""
            print "Suggested actions:"
            print "• Review warnings for potential improvements"
            print "• Consider addressing warnings for better practices"
            print "• Documentation and monitoring suggestions may be included"
            print "• Safe to proceed with deployment"
        }
        _ => {
            print "❓ Unexpected validation result - please review the output"
        }
    }

    print ""
    print "For detailed information, check the generated reports in the output directory."
    print "Use --help for more usage examples and CI/CD integration guidance."
}