#!/usr/bin/env nu
# Infrastructure Validation Script
# Validates generated infrastructure configs using format-specific tools

use std log

def main [--config-dir: string = "provisioning/platform/infrastructure"] {
    log info $"Validating infrastructure configs in: ($config_dir)"

    let errors = []
    let warnings = []

    # Validate Docker Compose files
    validate_docker_compose $config_dir

    # Validate Kubernetes manifests
    validate_kubernetes $config_dir

    # Validate Nginx configurations
    validate_nginx $config_dir

    # Validate Prometheus configurations
    validate_prometheus $config_dir

    log info "✅ Infrastructure validation complete!"
}

def validate_docker_compose [config_dir: string] {
    log info "Validating Docker Compose files..."

    let dc_files = (try { ls -la $"($config_dir)/docker-compose/*.yaml" } catch { [] })
        | each { |file| $file.name }

    for file in $dc_files {
        let filename = $file | path basename
        try {
            docker-compose -f $file config --quiet
            log info $"  ✅ ($filename)"
        } catch {|e|
            log warning $"  ⚠️  ($filename): ($e.msg)"
        }
    }
}

def validate_kubernetes [config_dir: string] {
    log info "Validating Kubernetes manifests..."

    let k8s_files = (try { ls -la $"($config_dir)/kubernetes/**/*.yaml" } catch { [] })
        | each { |file| $file.name }

    for file in $k8s_files {
        let filename = $file | path basename
        try {
            kubectl apply --dry-run=client -f $file out+err> /dev/null
            log info $"  ✅ ($filename)"
        } catch {|e|
            log warning $"  ⚠️  ($filename): validation error"
        }
    }
}

def validate_nginx [config_dir: string] {
    log info "Validating Nginx configurations..."

    let nginx_files = (try { ls -la $"($config_dir)/nginx/*.conf" } catch { [] })
        | each { |file| $file.name }

    for file in $nginx_files {
        let filename = $file | path basename
        try {
            nginx -t -c $file out+err> /dev/null
            log info $"  ✅ ($filename)"
        } catch {|e|
            log info $"  ℹ️  ($filename): nginx binary not available"
        }
    }
}

def validate_prometheus [config_dir: string] {
    log info "Validating Prometheus configurations..."

    let prom_files = (try { ls -la $"($config_dir)/prometheus/*.yml" } catch { [] })
        | each { |file| $file.name }

    for file in $prom_files {
        let filename = $file | path basename
        try {
            promtool check config $file out+err> /dev/null
            log info $"  ✅ ($filename)"
        } catch {|e|
            log info $"  ℹ️  ($filename): promtool not available"
        }
    }
}
