#!/bin/bash
# validate-configs.sh
# Validates all configuration files without requiring external access

set -euo pipefail

# Colors
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

ERRORS=0
WARNINGS=0

log() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

error() {
    echo -e "${RED}[ERROR]${NC} $1" >&2
    ((ERRORS++))
}

warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
    ((WARNINGS++))
}

success() {
    echo -e "${GREEN}[✓]${NC} $1"
}

check_yaml_syntax() {
    local file=$1
    
    if [ ! -f "$file" ]; then
        return 1
    fi
    
    if command -v yamllint &> /dev/null; then
        if yamllint -d relaxed "$file" &> /dev/null; then
            return 0
        else
            return 1
        fi
    elif command -v python3 &> /dev/null; then
        if python3 -c "import yaml; list(yaml.safe_load_all(open('$file')))" &> /dev/null 2>&1; then
            return 0
        else
            return 1
        fi
    else
        # Basic check - file exists and is readable, and has .yaml/.yml extension
        if [[ "$file" =~ \.(yaml|yml)$ ]] && [ -r "$file" ]; then
            return 0
        else
            return 1
        fi
    fi
}

check_placeholders() {
    local file=$1
    local placeholders=(
        "CHANGE_ME"
        "your-"
        "TBD"
        "TODO"
        "FIXME"
        "placeholder"
    )
    
    local found=false
    for placeholder in "${placeholders[@]}"; do
        if grep -qi "$placeholder" "$file" 2>/dev/null; then
            if [ "$found" = false ]; then
                warn "Found placeholders in: $file"
                found=true
            fi
            grep -ni "$placeholder" "$file" 2>/dev/null | head -3 | sed 's/^/    /'
        fi
    done
    
    if [ "$found" = false ]; then
        return 0
    else
        return 1
    fi
}

validate_provider_config() {
    log "Validating provider configuration..."
    
    local config_file="crossplane-provider-proxmox/examples/provider-config.yaml"
    
    if [ ! -f "$config_file" ]; then
        error "Provider config not found: $config_file"
        return 1
    fi
    
    # Check YAML syntax
    if check_yaml_syntax "$config_file"; then
        success "Provider config YAML syntax valid"
    else
        error "Provider config YAML syntax invalid"
    fi
    
    # Check for placeholders
    if check_placeholders "$config_file"; then
        success "Provider config has no placeholders"
    else
        warn "Provider config may contain placeholders"
    fi
    
    # Check required fields
    if grep -q "ml110-01.sankofa.nexus" "$config_file" && grep -q "r630-01.sankofa.nexus" "$config_file"; then
        success "Provider config has correct FQDNs"
    else
        error "Provider config missing correct FQDNs"
    fi
    
    if grep -q "ML110-01" "$config_file" && grep -q "R630-01" "$config_file"; then
        success "Provider config has correct node names"
    else
        error "Provider config missing correct node names"
    fi
}

validate_tunnel_configs() {
    log "Validating Cloudflare tunnel configurations..."
    
    local tunnel_configs=(
        "cloudflare/tunnel-configs/proxmox-site-1.yaml"
        "cloudflare/tunnel-configs/proxmox-site-2.yaml"
        "cloudflare/tunnel-configs/proxmox-site-3.yaml"
    )
    
    for config in "${tunnel_configs[@]}"; do
        if [ ! -f "$config" ]; then
            error "Tunnel config not found: $config"
            continue
        fi
        
        if check_yaml_syntax "$config"; then
            success "Tunnel config YAML valid: $(basename $config)"
        else
            error "Tunnel config YAML invalid: $(basename $config)"
        fi
        
        if check_placeholders "$config"; then
            success "Tunnel config has no placeholders: $(basename $config)"
        else
            warn "Tunnel config may contain placeholders: $(basename $config)"
        fi
    done
}

validate_vm_manifests() {
    log "Validating VM manifests..."
    
    local vm_manifests=(
        "crossplane-provider-proxmox/examples/test-vm-instance-1.yaml"
        "crossplane-provider-proxmox/examples/test-vm-instance-2.yaml"
        "crossplane-provider-proxmox/examples/vm-example.yaml"
    )
    
    for manifest in "${vm_manifests[@]}"; do
        if [ ! -f "$manifest" ]; then
            warn "VM manifest not found: $manifest"
            continue
        fi
        
        if check_yaml_syntax "$manifest"; then
            success "VM manifest YAML valid: $(basename $manifest)"
        else
            error "VM manifest YAML invalid: $(basename $manifest)"
        fi
        
        # Check for required fields
        if grep -q "site:" "$manifest" && grep -q "node:" "$manifest"; then
            success "VM manifest has required fields: $(basename $manifest)"
        else
            error "VM manifest missing required fields: $(basename $manifest)"
        fi
    done
}

validate_dns_configs() {
    log "Validating DNS configurations..."
    
    local dns_files=(
        "cloudflare/dns/sankofa.nexus-records.yaml"
        "cloudflare/terraform/dns.tf"
    )
    
    for dns_file in "${dns_files[@]}"; do
        if [ ! -f "$dns_file" ]; then
            warn "DNS config not found: $dns_file"
            continue
        fi
        
        if check_yaml_syntax "$dns_file" 2>/dev/null || [ -f "$dns_file" ]; then
            success "DNS config valid: $(basename $dns_file)"
        else
            error "DNS config invalid: $(basename $dns_file)"
        fi
    done
}

check_file_structure() {
    log "Checking file structure..."
    
    local required_dirs=(
        "crossplane-provider-proxmox"
        "cloudflare/tunnel-configs"
        "cloudflare/dns"
        "docs/proxmox"
        "scripts"
        "infrastructure/monitoring/dashboards"
    )
    
    for dir in "${required_dirs[@]}"; do
        if [ -d "$dir" ]; then
            success "Directory exists: $dir"
        else
            error "Directory missing: $dir"
        fi
    done
}

print_summary() {
    echo ""
    echo "═══════════════════════════════════════════════════════════════"
    echo "Validation Summary"
    echo "═══════════════════════════════════════════════════════════════"
    echo ""
    echo "Errors: ${ERRORS}"
    echo "Warnings: ${WARNINGS}"
    echo ""
    
    if [ "${ERRORS}" -eq 0 ]; then
        success "All configuration files are valid!"
        if [ "${WARNINGS}" -gt 0 ]; then
            warn "Some warnings found, but configurations appear valid"
        fi
        return 0
    else
        error "Some errors were found. Please review and fix them."
        return 1
    fi
}

main() {
    echo ""
    echo "╔══════════════════════════════════════════════════════════════╗"
    echo "║          Configuration Validation                            ║"
    echo "╚══════════════════════════════════════════════════════════════╝"
    echo ""
    
    check_file_structure
    echo ""
    
    validate_provider_config
    echo ""
    
    validate_tunnel_configs
    echo ""
    
    validate_vm_manifests
    echo ""
    
    validate_dns_configs
    echo ""
    
    print_summary
}

main "$@"

