#!/bin/bash
# Validate all enodes in generated files
# Usage: bash besu-validate-allowlist.sh <static-nodes.json> <permissions-nodes.toml>

set -euo pipefail

STATIC_NODES="${1:-static-nodes.json}"
PERMISSIONS_TOML="${2:-permissions-nodes.toml}"

ERRORS=0

validate_enode_file() {
    local file="$1"
    local file_type="$2"
    
    echo "Validating $file_type: $file"
    
    if [[ "$file_type" == "json" ]]; then
        python3 << PYEOF
import json
import re
import sys

try:
    with open('$file', 'r') as f:
        enodes = json.load(f)
except Exception as e:
    print(f"ERROR: Failed to read file: {e}", file=sys.stderr)
    sys.exit(1)

errors = 0
node_ids_seen = set()
endpoints_seen = set()

for i, enode in enumerate(enodes):
    match = re.match(r'enode://([0-9a-fA-F]+)@([0-9.]+):(\d+)', enode)
    if not match:
        print(f"ERROR: Invalid enode format at index {i}: {enode}", file=sys.stderr)
        errors += 1
        continue
    
    node_id = match.group(1).lower()
    endpoint = f"{match.group(2)}:{match.group(3)}"
    
    if len(node_id) != 128:
        print(f"ERROR: Node ID length {len(node_id)} at index {i} (expected 128): {node_id[:32]}...", file=sys.stderr)
        errors += 1
        continue
    
    if not re.match(r'^[0-9a-f]{128}$', node_id):
        print(f"ERROR: Invalid hex in node ID at index {i}: {node_id[:32]}...", file=sys.stderr)
        errors += 1
        continue
    
    if node_id in node_ids_seen:
        print(f"WARNING: Duplicate node ID at index {i}: {node_id[:32]}...", file=sys.stderr)
    node_ids_seen.add(node_id)
    
    if endpoint in endpoints_seen:
        print(f"WARNING: Duplicate endpoint at index {i}: {endpoint}", file=sys.stderr)
    endpoints_seen.add(endpoint)

sys.exit(errors)
PYEOF
        ERRORS=$((ERRORS + $?))
    else
        python3 << PYEOF
import re
import sys

try:
    with open('$file', 'r') as f:
        content = f.read()
except Exception as e:
    print(f"ERROR: Failed to read file: {e}", file=sys.stderr)
    sys.exit(1)

enodes = re.findall(r'"enode://([0-9a-fA-F]+)@([0-9.]+):(\d+)"', content)

errors = 0
node_ids_seen = set()
endpoints_seen = set()

for i, (node_id_hex, ip, port) in enumerate(enodes):
    node_id = node_id_hex.lower()
    endpoint = f"{ip}:{port}"
    
    if len(node_id) != 128:
        print(f"ERROR: Node ID length {len(node_id)} at entry {i+1} (expected 128): {node_id[:32]}...", file=sys.stderr)
        errors += 1
        continue
    
    if not re.match(r'^[0-9a-f]{128}$', node_id):
        print(f"ERROR: Invalid hex in node ID at entry {i+1}: {node_id[:32]}...", file=sys.stderr)
        errors += 1
        continue
    
    if node_id in node_ids_seen:
        print(f"WARNING: Duplicate node ID at entry {i+1}: {node_id[:32]}...", file=sys.stderr)
    node_ids_seen.add(node_id)
    
    if endpoint in endpoints_seen:
        print(f"WARNING: Duplicate endpoint at entry {i+1}: {endpoint}", file=sys.stderr)
    endpoints_seen.add(endpoint)

sys.exit(errors)
PYEOF
        ERRORS=$((ERRORS + $?))
    fi
}

validate_enode_file "$STATIC_NODES" "json"
validate_enode_file "$PERMISSIONS_TOML" "toml"

if [[ $ERRORS -eq 0 ]]; then
    echo "✓ All enodes validated successfully"
    exit 0
else
    echo "✗ Validation failed with $ERRORS errors"
    exit 1
fi
