#!/usr/bin/env bash
# Comprehensive Validation Script
# Validates templates, genesis.json, keys, configs, and synchronization

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"

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

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }
log_section() { echo -e "${CYAN}=== $1 ===${NC}"; }

ERRORS=0
WARNINGS=0

# Source project paths
SMOM_PROJECT="${SMOM_PROJECT:-$PROJECT_ROOT/../smom-dbis-138}"
PROXMOX_PROJECT="$PROJECT_ROOT/smom-dbis-138-proxmox"

log_section "Comprehensive Validation Review"
echo ""

# 1. Template Files Review
log_section "1. Template Files Validation"

TEMPLATE_FILES=(
    "$PROXMOX_PROJECT/config/proxmox.conf.example"
    "$PROXMOX_PROJECT/config/network.conf.example"
)

for template in "${TEMPLATE_FILES[@]}"; do
    if [[ -f "$template" ]]; then
        log_success "$(basename "$template") exists"
        
        # Check for old VMID references
        if grep -qE "\b(106|107|108|109|110|111|112|113|114|115|116|117)\b" "$template" 2>/dev/null; then
            log_error "$(basename "$template") contains old VMID references"
            ((ERRORS++))
        fi
        
        # Check for old IP references
        if grep -q "10\.3\.1\." "$template" 2>/dev/null; then
            log_error "$(basename "$template") contains old IP addresses (10.3.1.X)"
            ((ERRORS++))
        fi
        
        # Check for correct VMID ranges
        if grep -qE "\b(1000|1001|1002|1003|1004|1500|1501|1502|1503|2500|2501|2502)\b" "$template" 2>/dev/null; then
            log_success "  Contains correct VMID ranges"
        fi
        
        # Check for correct IP range
        if grep -q "192\.168\.11\." "$template" 2>/dev/null; then
            log_success "  Contains correct IP range (192.168.11.X)"
        fi
    else
        log_warn "$(basename "$template") not found"
        ((WARNINGS++))
    fi
done

echo ""

# 2. Genesis.json Validation
log_section "2. Genesis.json Validation"

GENESIS_FILE="$SMOM_PROJECT/config/genesis.json"

if [[ ! -f "$GENESIS_FILE" ]]; then
    log_error "genesis.json not found: $GENESIS_FILE"
    ((ERRORS++))
else
    log_success "genesis.json found"
    
    # Check if it's valid JSON
    if python3 -c "import json; json.load(open('$GENESIS_FILE'))" 2>/dev/null; then
        log_success "  Valid JSON format"
        
        # Check for validator addresses in extraData
        EXTRA_DATA=$(python3 -c "import json; g=json.load(open('$GENESIS_FILE')); print(g.get('extraData', ''))" 2>/dev/null)
        if [[ -n "$EXTRA_DATA" ]]; then
            # Remove 0x prefix if present
            HEX_DATA="${EXTRA_DATA#0x}"
            # Each validator address is 40 hex characters in extraData (20 bytes)
            VALIDATOR_COUNT=$(( ${#HEX_DATA} / 40 ))
            log_info "  Validators in extraData: $VALIDATOR_COUNT"
            
            if [[ $VALIDATOR_COUNT -eq 5 ]]; then
                log_success "  ✓ Correct number of validators (5)"
            elif [[ $VALIDATOR_COUNT -eq 4 ]]; then
                log_error "  ✗ Only 4 validators found (expected 5)"
                ((ERRORS++))
            else
                log_error "  ✗ Unexpected validator count: $VALIDATOR_COUNT (expected 5)"
                ((ERRORS++))
            fi
        else
            log_warn "  extraData field not found or empty"
        fi
    else
        log_error "  Invalid JSON format"
        ((ERRORS++))
    fi
fi

echo ""

# 3. Validator Keys Validation
log_section "3. Validator Keys Validation"

EXPECTED_VALIDATORS=5
FOUND_VALIDATORS=0
VALIDATOR_ADDRESSES=()

for i in $(seq 1 $EXPECTED_VALIDATORS); do
    KEY_DIR="$SMOM_PROJECT/keys/validators/validator-$i"
    
    if [[ -d "$KEY_DIR" ]]; then
        log_success "validator-$i directory exists"
        
        # Check for required key files
        KEY_FILES=("key.priv" "key.pem" "pubkey.pem" "address.txt")
        for key_file in "${KEY_FILES[@]}"; do
            if [[ -f "$KEY_DIR/$key_file" ]]; then
                log_success "  ✓ $key_file"
            else
                log_error "  ✗ Missing: $key_file"
                ((ERRORS++))
            fi
        done
        
        # Extract address
        if [[ -f "$KEY_DIR/address.txt" ]]; then
            ADDR=$(cat "$KEY_DIR/address.txt" | tr -d '\n' | tr '[:upper:]' '[:lower:]')
            if [[ ${#ADDR} -eq 42 ]] || [[ ${#ADDR} -eq 40 ]]; then
                VALIDATOR_ADDRESSES+=("${ADDR#0x}")  # Remove 0x prefix if present
                log_info "  Address: ${ADDR:0:10}..."
                FOUND_VALIDATORS=$((FOUND_VALIDATORS + 1))
            else
                log_error "  ✗ Invalid address format (length: ${#ADDR})"
                ((ERRORS++))
            fi
        fi
    else
        log_error "validator-$i directory missing"
        ((ERRORS++))
    fi
done

if [[ $FOUND_VALIDATORS -eq $EXPECTED_VALIDATORS ]]; then
    log_success "All $EXPECTED_VALIDATORS validator keys found"
else
    log_error "Only $FOUND_VALIDATORS/$EXPECTED_VALIDATORS validator keys found"
    ((ERRORS++))
fi

echo ""

# 4. Old References Check
log_section "4. Old References Check"

# Check config files for old VMIDs
OLD_VMID_COUNT=$(grep -rE "\b(106|107|108|109|110|111|112|113|114|115|116|117)\b" \
    "$PROXMOX_PROJECT/config" "$PROXMOX_PROJECT/scripts" 2>/dev/null | \
    grep -v ".git" | grep -v ".example" | wc -l)

if [[ $OLD_VMID_COUNT -eq 0 ]]; then
    log_success "No old VMID references (106-117) in config/scripts"
else
    log_error "Found $OLD_VMID_COUNT references to old VMIDs (106-117)"
    ((ERRORS++))
fi

# Check for old IP addresses
OLD_IP_COUNT=$(grep -rE "10\.3\.1\." \
    "$PROXMOX_PROJECT/config" "$PROXMOX_PROJECT/scripts" 2>/dev/null | \
    grep -v ".git" | grep -v ".example" | wc -l)

if [[ $OLD_IP_COUNT -eq 0 ]]; then
    log_success "No old IP addresses (10.3.1.X) in config/scripts"
else
    log_error "Found $OLD_IP_COUNT references to old IP addresses (10.3.1.X)"
    ((ERRORS++))
fi

echo ""

# 5. Configuration Completeness
log_section "5. Configuration Completeness"

CONFIG_FILES=(
    "$PROXMOX_PROJECT/config/proxmox.conf"
    "$PROXMOX_PROJECT/config/network.conf"
)

for config in "${CONFIG_FILES[@]}"; do
    if [[ -f "$config" ]]; then
        log_success "$(basename "$config") exists"
        
        # Check for correct values
        if [[ "$config" == *"proxmox.conf"* ]]; then
            VALIDATOR_COUNT=$(grep "^VALIDATOR_COUNT=" "$config" 2>/dev/null | cut -d'=' -f2 | tr -d ' ')
            if [[ "$VALIDATOR_COUNT" == "5" ]]; then
                log_success "  VALIDATOR_COUNT=5 ✓"
            else
                log_error "  VALIDATOR_COUNT=$VALIDATOR_COUNT (expected 5)"
                ((ERRORS++))
            fi
        fi
    else
        log_error "$(basename "$config") missing"
        ((ERRORS++))
    fi
done

echo ""

# Summary
log_section "Validation Summary"

echo "Errors: $ERRORS"
echo "Warnings: $WARNINGS"
echo ""

if [[ $ERRORS -eq 0 ]]; then
    log_success "✓ All validations passed!"
    exit 0
else
    log_error "✗ Validation failed with $ERRORS error(s)"
    exit 1
fi

