#!/usr/bin/env bash
# Detailed Once-Over Review Script
# Comprehensive review of all aspects of the project

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}"; }

REPORT_FILE="$PROJECT_ROOT/logs/detailed-review-$(date +%Y%m%d-%H%M%S).txt"
mkdir -p "$PROJECT_ROOT/logs"

{
log_section "Detailed Project Review"
echo "Generated: $(date)"
echo ""

log_section "1. Configuration File Validation"

# Check config files exist
CONFIG_FILES=(
    "smom-dbis-138-proxmox/config/proxmox.conf"
    "smom-dbis-138-proxmox/config/network.conf"
)

for config in "${CONFIG_FILES[@]}"; do
    if [[ -f "$PROJECT_ROOT/$config" ]]; then
        log_success "$config exists"
        # Check if file is readable
        if [[ -r "$PROJECT_ROOT/$config" ]]; then
            log_success "  Readable"
        else
            log_error "  Not readable"
        fi
    else
        log_error "$config missing"
    fi
done

echo ""

log_section "2. Configuration Value Consistency"

# Source config if possible
if [[ -f "$PROJECT_ROOT/smom-dbis-138-proxmox/config/proxmox.conf" ]]; then
    source "$PROJECT_ROOT/smom-dbis-138-proxmox/config/proxmox.conf" 2>/dev/null || true
    
    echo "VMID Ranges:"
    echo "  VALIDATOR_COUNT: ${VALIDATOR_COUNT:-not set}"
    echo "  SENTRY_COUNT: ${SENTRY_COUNT:-not set}"
    echo "  RPC_COUNT: ${RPC_COUNT:-not set}"
    echo ""
    echo "VMID Starts:"
    echo "  VMID_VALIDATORS_START: ${VMID_VALIDATORS_START:-not set}"
    echo "  VMID_SENTRIES_START: ${VMID_SENTRIES_START:-not set}"
    echo "  VMID_RPC_START: ${VMID_RPC_START:-not set}"
    
    # Validate consistency
    if [[ "${VALIDATOR_COUNT:-}" == "5" ]] && [[ "${VMID_VALIDATORS_START:-}" == "1000" ]]; then
        log_success "Validators: Correct (5 nodes starting at 1000)"
    else
        log_warn "Validators: Inconsistent or incorrect"
    fi
    
    if [[ "${SENTRY_COUNT:-}" == "4" ]] && [[ "${VMID_SENTRIES_START:-}" == "1500" ]]; then
        log_success "Sentries: Correct (4 nodes starting at 1500)"
    else
        log_warn "Sentries: Inconsistent or incorrect"
    fi
    
    if [[ "${RPC_COUNT:-}" == "3" ]] && [[ "${VMID_RPC_START:-}" == "2500" ]]; then
        log_success "RPC: Correct (3 nodes starting at 2500)"
    else
        log_warn "RPC: Inconsistent or incorrect"
    fi
fi

echo ""

log_section "3. Script Syntax Validation"

SYNTAX_ERRORS=0
SCRIPT_COUNT=0

while IFS= read -r script; do
    if [[ -f "$script" ]] && [[ -x "$script" ]] || [[ "$script" == *.sh ]]; then
        SCRIPT_COUNT=$((SCRIPT_COUNT + 1))
        if ! bash -n "$script" 2>/dev/null; then
            echo "  Syntax error: $script"
            SYNTAX_ERRORS=$((SYNTAX_ERRORS + 1))
        fi
    fi
done < <(find "$PROJECT_ROOT/smom-dbis-138-proxmox/scripts" -name "*.sh" -type f 2>/dev/null)

if [[ $SYNTAX_ERRORS -eq 0 ]]; then
    log_success "All $SCRIPT_COUNT scripts have valid syntax"
else
    log_error "Found $SYNTAX_ERRORS scripts with syntax errors"
fi

echo ""

log_section "4. Script Dependency Check"

# Check for common library usage
LIB_FILES=(
    "lib/common.sh"
    "lib/container-utils.sh"
    "lib/progress-tracking.sh"
)

for lib in "${LIB_FILES[@]}"; do
    if [[ -f "$PROJECT_ROOT/smom-dbis-138-proxmox/$lib" ]]; then
        log_success "$lib exists"
        # Count scripts using it
        usage_count=$(grep -r "source.*$lib" "$PROJECT_ROOT/smom-dbis-138-proxmox/scripts" 2>/dev/null | wc -l)
        echo "  Used by $usage_count scripts"
    else
        log_warn "$lib missing (may be optional)"
    fi
done

echo ""

log_section "5. Hardcoded Path Reference Check"

# Check for problematic hardcoded paths
HARDCODED_PATTERNS=(
    "/home/intlc/projects"
    "/opt/smom-dbis-138"
    "/opt/smom-dbis-138-proxmox"
)

for pattern in "${HARDCODED_PATTERNS[@]}"; do
    matches=$(grep -r "$pattern" "$PROJECT_ROOT/smom-dbis-138-proxmox/scripts" 2>/dev/null | grep -v ".git" | grep -v "lib/common.sh" | wc -l)
    if [[ $matches -gt 0 ]]; then
        log_warn "Found $matches references to hardcoded path: $pattern"
        echo "  Consider using PROJECT_ROOT or relative paths"
    fi
done

echo ""

log_section "6. VMID Array Hardcoding Check"

# Check scripts for hardcoded VMID arrays
HARDCODED_VMIDS=$(grep -rE "VALIDATORS=\(|SENTRIES=\(|RPC_NODES=\(" "$PROJECT_ROOT/smom-dbis-138-proxmox/scripts" 2>/dev/null | grep -v ".git" | wc -l)
if [[ $HARDCODED_VMIDS -gt 0 ]]; then
    log_warn "Found $HARDCODED_VMIDS hardcoded VMID array definitions"
    echo "  These should ideally use config values"
    grep -rE "VALIDATORS=\(|SENTRIES=\(|RPC_NODES=\(" "$PROJECT_ROOT/smom-dbis-138-proxmox/scripts" 2>/dev/null | grep -v ".git" | head -5 | sed 's/^/    /'
else
    log_success "No hardcoded VMID arrays found (using config values)"
fi

echo ""

log_section "7. Network Configuration Consistency"

if [[ -f "$PROJECT_ROOT/smom-dbis-138-proxmox/config/network.conf" ]]; then
    source "$PROJECT_ROOT/smom-dbis-138-proxmox/config/network.conf" 2>/dev/null || true
    
    echo "Network Configuration:"
    echo "  SUBNET_BASE: ${SUBNET_BASE:-not set}"
    echo "  GATEWAY: ${GATEWAY:-not set}"
    echo "  VALIDATORS_START_IP: ${VALIDATORS_START_IP:-not set}"
    echo "  SENTRIES_START_IP: ${SENTRIES_START_IP:-not set}"
    echo "  RPC_START_IP: ${RPC_START_IP:-not set}"
    
    if [[ "${SUBNET_BASE:-}" == "192.168.11" ]] && [[ "${GATEWAY:-}" == "192.168.11.1" ]]; then
        log_success "Network base and gateway correct"
    else
        log_warn "Network configuration may be incorrect"
    fi
fi

echo ""

log_section "8. Critical File Existence Check"

CRITICAL_FILES=(
    "smom-dbis-138-proxmox/scripts/deployment/deploy-validated-set.sh"
    "smom-dbis-138-proxmox/scripts/deployment/deploy-besu-nodes.sh"
    "smom-dbis-138-proxmox/scripts/copy-besu-config.sh"
    "smom-dbis-138-proxmox/scripts/network/bootstrap-network.sh"
    "smom-dbis-138-proxmox/scripts/validation/validate-deployment-comprehensive.sh"
    "smom-dbis-138-proxmox/scripts/fix-container-ips.sh"
    "smom-dbis-138-proxmox/scripts/fix-besu-services.sh"
)

for file in "${CRITICAL_FILES[@]}"; do
    if [[ -f "$PROJECT_ROOT/$file" ]]; then
        log_success "$(basename "$file")"
    else
        log_error "Missing: $file"
    fi
done

echo ""

log_section "9. IP Address Consistency"

# Check for old IP references in critical files
OLD_IP_COUNT=$(grep -rE "10\.3\.1\." "$PROJECT_ROOT/smom-dbis-138-proxmox/scripts" "$PROJECT_ROOT/smom-dbis-138-proxmox/config" 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 scripts/config"
else
    log_warn "Found $OLD_IP_COUNT references to old IP addresses in scripts/config"
fi

# Check for correct IP range usage
CORRECT_IP_COUNT=$(grep -rE "192\.168\.11\." "$PROJECT_ROOT/smom-dbis-138-proxmox/scripts" "$PROJECT_ROOT/smom-dbis-138-proxmox/config" 2>/dev/null | grep -v ".git" | wc -l)
log_info "Found $CORRECT_IP_COUNT references to correct IP range (192.168.11.X)"

echo ""

log_section "10. VMID Range Consistency"

# Check for old VMID references in critical files
OLD_VMID_COUNT=$(grep -rE "\b(106|107|108|109|110|111|112|113|114|115|116|117)\b" "$PROJECT_ROOT/smom-dbis-138-proxmox/scripts" "$PROJECT_ROOT/smom-dbis-138-proxmox/config" 2>/dev/null | grep -v ".git" | grep -v ".example" | wc -l)
if [[ $OLD_VMID_COUNT -eq 0 ]]; then
    log_success "No old VMIDs (106-117) in scripts/config"
else
    log_warn "Found $OLD_VMID_COUNT references to old VMIDs in scripts/config"
fi

# Check for correct VMID range usage
CORRECT_VMID_COUNT=$(grep -rE "\b(1000|1001|1002|1003|1004|1500|1501|1502|1503|2500|2501|2502)\b" "$PROJECT_ROOT/smom-dbis-138-proxmox/scripts" "$PROJECT_ROOT/smom-dbis-138-proxmox/config" 2>/dev/null | grep -v ".git" | wc -l)
log_info "Found $CORRECT_VMID_COUNT references to correct VMID ranges"

echo ""

log_section "Review Summary"
echo ""
echo "Configuration: $(if [[ -f "$PROJECT_ROOT/smom-dbis-138-proxmox/config/proxmox.conf" ]] && [[ -f "$PROJECT_ROOT/smom-dbis-138-proxmox/config/network.conf" ]]; then echo "✓ Complete"; else echo "✗ Incomplete"; fi)"
echo "Scripts: $SCRIPT_COUNT scripts checked, $SYNTAX_ERRORS syntax errors"
echo "Hardcoded paths: Check warnings above"
echo "VMID consistency: Check warnings above"
echo "IP consistency: Check warnings above"
echo ""

} | tee "$REPORT_FILE"

log_info "Detailed review report saved to: $REPORT_FILE"

