#!/usr/bin/env bash
# Fix genesis.json to ensure it contains exactly 5 validators
# This script checks if genesis.json needs to be regenerated

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
SMOM_PROJECT="${SMOM_PROJECT:-$PROJECT_ROOT/../smom-dbis-138}"

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

log_info() { echo "[INFO] $1"; }
log_success() { echo "[✓] $1"; }
log_warn() { echo "[⚠] $1"; }
log_error() { echo "[✗] $1"; }

log_info "=== Genesis.json Validator Check ==="
echo ""

if [[ ! -f "$GENESIS_FILE" ]]; then
    log_error "genesis.json not found: $GENESIS_FILE"
    exit 1
fi

# Extract validator addresses from keys
log_info "Extracting validator addresses from keys..."
VALIDATOR_ADDRESSES=()

for i in 1 2 3 4 5; do
    KEY_DIR="$SMOM_PROJECT/keys/validators/validator-$i"
    if [[ -f "$KEY_DIR/address.txt" ]]; then
        ADDR=$(cat "$KEY_DIR/address.txt" | tr -d '\n' | tr '[:upper:]' '[:lower:]' | sed 's/^0x//')
        VALIDATOR_ADDRESSES+=("$ADDR")
        log_success "validator-$i: 0x${ADDR:0:10}..."
    else
        log_error "validator-$i address.txt not found"
        exit 1
    fi
done

if [[ ${#VALIDATOR_ADDRESSES[@]} -ne 5 ]]; then
    log_error "Expected 5 validator addresses, found ${#VALIDATOR_ADDRESSES[@]}"
    exit 1
fi

log_success "Found all 5 validator addresses"
echo ""

# Check genesis.json
log_info "Analyzing genesis.json extraData..."

VALIDATOR_COUNT=$(python3 << PYEOF
import json
with open('$GENESIS_FILE') as f:
    g = json.load(f)
extra = g.get('extraData', '')
hex_data = extra[2:] if extra.startswith('0x') else extra
# Skip vanity (64 hex chars = 32 bytes)
if len(hex_data) > 64:
    validator_data = hex_data[64:]
    count = len(validator_data) // 40
    print(count)
else:
    print(0)
PYEOF
)

log_info "Validators in genesis.json extraData: $VALIDATOR_COUNT"
log_info "Expected: 5"

if [[ $VALIDATOR_COUNT -eq 5 ]]; then
    log_success "✓ Genesis.json contains correct number of validators (5)"
    echo ""
    log_info "Genesis.json is correct - no action needed"
    exit 0
elif [[ $VALIDATOR_COUNT -eq 0 ]]; then
    log_warn "Could not determine validator count from extraData"
    log_warn "extraData may be in RLP-encoded format"
    echo ""
    log_info "Note: QBFT uses dynamic validator management via validator contract"
    log_info "The extraData field may contain RLP-encoded data that requires special parsing"
    exit 0
else
    log_error "✗ Genesis.json contains $VALIDATOR_COUNT validators (expected 5)"
    echo ""
    log_warn "WARNING: Genesis.json needs to be regenerated with the correct 5 validators"
    log_warn "Current validator addresses:"
    for i in "${!VALIDATOR_ADDRESSES[@]}"; do
        echo "  validator-$((i+1)): 0x${VALIDATOR_ADDRESSES[$i]}"
    done
    echo ""
    log_info "To fix: Regenerate genesis.json using quorum-genesis-tool or besu"
    log_info "with the 5 validator addresses listed above"
    exit 1
fi

