#!/usr/bin/env bash
# Verify IP address consistency across documentation and configuration files
# Compares IPs in key files against the physical hardware inventory

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'
NC='\033[0m'

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[⚠]${NC} $1"; }
log_error() { echo -e "${RED}[✗]${NC} $1"; }

# Load inventory
source "$SCRIPT_DIR/load-physical-inventory.sh" 2>/dev/null || {
    log_error "Failed to load physical hardware inventory"
    exit 1
}

log_info "=== IP Address Consistency Verification ==="
echo ""

# Expected IPs from inventory
declare -A EXPECTED_IPS=(
    ["ml110"]="192.168.11.10"
    ["r630-01"]="192.168.11.11"
    ["r630-02"]="192.168.11.12"
    ["r630-03"]="192.168.11.13"
    ["r630-04"]="192.168.11.14"
    ["omada"]="192.168.11.8"
    ["er605-1"]="76.53.10.34"
    ["er605-2"]="76.53.10.41"
)

# Files to check
FILES_TO_CHECK=(
    "config/physical-hardware-inventory.conf"
    "config/physical-hardware-inventory.md"
    "docs/02-architecture/PHYSICAL_HARDWARE_INVENTORY.md"
    "docs/04-configuration/OMADA_API_SETUP.md"
    "mcp-omada/README.md"
    "mcp-omada/src/index.ts"
)

ERRORS=0
WARNINGS=0

# Check each file
for file in "${FILES_TO_CHECK[@]}"; do
    filepath="$PROJECT_ROOT/$file"
    if [[ ! -f "$filepath" ]]; then
        log_warn "File not found: $file"
        ((WARNINGS++))
        continue
    fi
    
    log_info "Checking: $file"
    
    # Check for incorrect Omada IP (192.168.11.10 instead of 192.168.11.8)
    if grep -q "192.168.11.10.*8043\|192.168.11.10:8043" "$filepath" 2>/dev/null; then
        log_error "  Found incorrect Omada IP (192.168.11.10:8043) - should be 192.168.11.8:8043"
        ((ERRORS++))
    fi
    
    # Check for incorrect ER605-1 IP (76.53.10.35 instead of 76.53.10.34)
    if grep -q "76.53.10.35" "$filepath" 2>/dev/null && ! grep -q "76.53.10.34" "$filepath" 2>/dev/null; then
        log_error "  Found incorrect ER605-1 IP (76.53.10.35) - should be 76.53.10.34"
        ((ERRORS++))
    fi
    
    # Check for incorrect ER605-2 IP (76.53.10.36 instead of 76.53.10.41)
    if grep -q "76.53.10.36" "$filepath" 2>/dev/null && ! grep -q "76.53.10.41" "$filepath" 2>/dev/null; then
        log_error "  Found incorrect ER605-2 IP (76.53.10.36) - should be 76.53.10.41"
        ((ERRORS++))
    fi
done

echo ""
if [[ $ERRORS -eq 0 ]]; then
    log_success "✓ All IP addresses are consistent"
    exit 0
else
    log_error "✗ Found $ERRORS IP inconsistency issue(s)"
    exit 1
fi
