#!/usr/bin/env bash
# Fix enode URL IP mismatches between static-nodes.json and permissions-nodes.toml
# Based on analysis: extract first 128 chars of node IDs and map to correct IPs

set -euo pipefail

# Container IP mapping
declare -A CONTAINER_IPS=(
    [106]="192.168.11.13"  # besu-validator-1
    [107]="192.168.11.14"  # besu-validator-2
    [108]="192.168.11.15"  # besu-validator-3
    [109]="192.168.11.16"  # besu-validator-4
    [110]="192.168.11.18"  # besu-validator-5
    [111]="192.168.11.19"  # besu-sentry-2
    [112]="192.168.11.20"  # besu-sentry-3
    [113]="192.168.11.21"  # besu-sentry-4
    [114]="192.168.11.22"  # besu-sentry-5
    [115]="192.168.11.23"  # besu-rpc-1
    [116]="192.168.11.24"  # besu-rpc-2
    [117]="192.168.11.25"  # besu-rpc-3
)

# 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}[WARNING]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

# Extract first 128 hex chars from enode URL (removes trailing zeros)
extract_node_id() {
    local enode="$1"
    local node_id_hex
    
    # Extract hex part between enode:// and @
    node_id_hex=$(echo "$enode" | sed -n 's|enode://\([a-fA-F0-9]*\)@.*|\1|p' | tr '[:upper:]' '[:lower:]')
    
    # Take first 128 characters (removes trailing zeros padding)
    echo "${node_id_hex:0:128}"
}

# Generate corrected static-nodes.json for validators
generate_static_nodes() {
    local vmid="$1"
    local temp_file="/tmp/static-nodes-${vmid}.json"
    
    log_info "Generating static-nodes.json for container $vmid"
    
    # Get current static-nodes.json from container
    local current_content
    current_content=$(ssh -o StrictHostKeyChecking=accept-new root@192.168.11.10 "pct exec $vmid -- cat /etc/besu/static-nodes.json 2>/dev/null" || echo '[]')
    
    # Extract node IDs (first 128 chars) and map to validator IPs
    python3 << PYEOF
import json
import re

# Read current static-nodes.json
try:
    static_nodes = json.loads('''$current_content''')
except:
    static_nodes = []

# Node IDs from current file (first 128 chars of each)
node_ids = []
for enode in static_nodes:
    match = re.search(r'enode://([a-fA-F0-9]+)@', enode)
    if match:
        full_hex = match.group(1).lower()
        node_id = full_hex[:128]  # First 128 chars only
        if len(node_id) == 128:
            node_ids.append(node_id)

# Validator IPs (106-110)
validator_ips = [
    "${CONTAINER_IPS[106]}",
    "${CONTAINER_IPS[107]}",
    "${CONTAINER_IPS[108]}",
    "${CONTAINER_IPS[109]}",
    "${CONTAINER_IPS[110]}",
]

# Generate new static-nodes.json with correct IPs
corrected_enodes = []
for i, node_id in enumerate(node_ids[:5]):  # First 5 validators
    if i < len(validator_ips):
        enode = f"enode://{node_id}@{validator_ips[i]}:30303"
        corrected_enodes.append(enode)

# Write corrected file
with open('$temp_file', 'w') as f:
    json.dump(corrected_enodes, f, indent=2)

print(f"Generated static-nodes.json with {len(corrected_enodes)} validators")
PYEOF

    echo "$temp_file"
}

echo "╔════════════════════════════════════════════════════════════════╗"
echo "║         FIXING ENODE URL IP MISMATCHES                          ║"
echo "╚════════════════════════════════════════════════════════════════╝"
echo ""
echo "This script will:"
echo "1. Extract valid 128-char node IDs (remove trailing zeros)"
echo "2. Map them to correct container IP addresses"
echo "3. Generate corrected static-nodes.json and permissions-nodes.toml"
echo "4. Copy to all containers"
echo ""
echo "NOTE: This is a template script. The actual fix requires:"
echo "- Verifying node IDs match actual Besu node keys"
echo "- Determining which node IDs belong to which containers"
echo "- Ensuring all nodes are included in permissions-nodes.toml"
echo ""
echo "Would you like to continue? (This will create corrected files)"
read -p "Press Enter to continue or Ctrl+C to cancel..."

# For now, demonstrate the concept
log_info "Extracting node IDs from container 107 (running validator)..."
ssh -o StrictHostKeyChecking=accept-new root@192.168.11.10 << 'REMOTE_SCRIPT'
vmid=107
if pct exec $vmid -- test -f /etc/besu/static-nodes.json 2>/dev/null; then
    echo "Current static-nodes.json from container $vmid:"
    pct exec $vmid -- cat /etc/besu/static-nodes.json | python3 -c "
import json, re, sys
data = json.load(sys.stdin)
print(f'Found {len(data)} enode URLs')
for i, enode in enumerate(data[:3]):  # Show first 3
    match = re.search(r'enode://([a-fA-F0-9]+)@([0-9.]+):', enode)
    if match:
        full_hex = match.group(1).lower()
        ip = match.group(2)
        node_id_128 = full_hex[:128]
        print(f'Node {i+1}:')
        print(f'  Full hex length: {len(full_hex)} chars')
        print(f'  Node ID (first 128): {node_id_128[:32]}...{node_id_128[-32:]}')
        print(f'  Current IP: {ip}')
        print(f'  Has trailing zeros: {\"Yes\" if len(full_hex) > 128 else \"No\"}')
        print()
"
else
    echo "Container $vmid static-nodes.json not found"
fi
REMOTE_SCRIPT

log_info "Fix script template created. Next steps:"
log_info "1. Determine actual node IDs from Besu node keys"
log_info "2. Map node IDs to container IPs correctly"
log_info "3. Generate corrected files"
log_info "4. Deploy to all containers"
