#!/usr/bin/env bash

# Validate Genesis File
# This script validates the genesis file for ChainID 138

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
CONFIG_DIR="$PROJECT_ROOT/config"
GENESIS_FILE="$CONFIG_DIR/genesis.json"

# Minimal logging (used if init.sh is not sourced or fails)
log_success() { echo -e "\033[0;32m[✓]\033[0m $*"; }
log_error()   { echo -e "\033[0;31m[✗]\033[0m $*" >&2; }
log_warn()   { echo -e "\033[0;33m[⚠]\033[0m $*"; }
# Optional: load lib (may fail if .env or Azure deps are missing)
if [ -f "$SCRIPT_DIR/../lib/init.sh" ]; then
  SCRIPT_DIR="$SCRIPT_DIR" source "$SCRIPT_DIR/../lib/init.sh" 2>/dev/null || true
fi

log_success "Validating Genesis File..."

# Check if genesis file exists
if [ ! -f "$GENESIS_FILE" ]; then
    log_error "✗ Genesis file not found: $GENESIS_FILE"
    log_warn "Generating genesis file..."
    "$PROJECT_ROOT/scripts/generate-genesis-proper.sh" 4
fi

# Validate JSON syntax
log_warn "Validating JSON syntax..."
if jq empty "$GENESIS_FILE" 2>/dev/null; then
    log_success "✓ Genesis file has valid JSON syntax"
else
    log_error "✗ Genesis file has invalid JSON syntax"
    exit 1
fi

# Check chain ID
log_warn "Checking chain ID..."
CHAIN_ID=$(jq -r '.config.chainId' "$GENESIS_FILE")
if [ "$CHAIN_ID" == "138" ]; then
    log_success "✓ Chain ID is correct: $CHAIN_ID"
else
    log_error "✗ Chain ID is incorrect: $CHAIN_ID (expected 138)"
    exit 1
fi

# Check extraData
log_warn "Checking extraData..."
EXTRA_DATA=$(jq -r '.extraData' "$GENESIS_FILE")
if [ "$EXTRA_DATA" != "0x" ] && [ -n "$EXTRA_DATA" ]; then
    log_success "✓ extraData is set: ${EXTRA_DATA:0:50}..."
    
    # Validate extraData length (should be reasonable for QBFT)
    EXTRA_DATA_LENGTH=$(echo -n "$EXTRA_DATA" | wc -c)
    if [ "$EXTRA_DATA_LENGTH" -gt 2 ]; then
        log_success "✓ extraData has content (length: $EXTRA_DATA_LENGTH)"
    else
        log_error "✗ extraData appears to be empty"
        exit 1
    fi
else
    log_error "✗ extraData is empty or invalid"
    log_warn "Note: extraData must be generated using Besu operator generate-blockchain-config"
    exit 1
fi

# Check QBFT configuration
log_warn "Checking QBFT configuration..."
CONSENSUS_CONFIG=$(jq -r '.config.qbft // .config.ibft2 // "null"' "$GENESIS_FILE")
if [ "$CONSENSUS_CONFIG" != "null" ]; then
    log_success "✓ QBFT-compatible consensus configuration exists"
    # Prefer qbft for Chain 138, but tolerate older ibft2-shaped historical files.
    BLOCK_KEY=".config.qbft.blockperiodseconds // .config.ibft2.blockperiodseconds"
    EPOCH_KEY=".config.qbft.epochlength // .config.ibft2.epochlength"
    BLOCK_PERIOD=$(jq -r "$BLOCK_KEY" "$GENESIS_FILE")
    EPOCH_LENGTH=$(jq -r "$EPOCH_KEY" "$GENESIS_FILE")
    if [ "$BLOCK_PERIOD" == "2" ]; then
        log_success "✓ Block period is correct: $BLOCK_PERIOD seconds"
    else
        log_warn "⚠ Block period is $BLOCK_PERIOD (expected 2)"
    fi
    if [ "$EPOCH_LENGTH" == "30000" ]; then
        log_success "✓ Epoch length is correct: $EPOCH_LENGTH"
    else
        log_warn "⚠ Epoch length is $EPOCH_LENGTH (expected 30000)"
    fi
else
    log_error "✗ QBFT-compatible consensus configuration not found"
    exit 1
fi

# Check gas limit
log_warn "Checking gas limit..."
GAS_LIMIT=$(jq -r '.gasLimit' "$GENESIS_FILE")
if [ "$GAS_LIMIT" == "0x1c9c380" ]; then
    log_success "✓ Gas limit is correct: $GAS_LIMIT"
else
    log_warn "⚠ Gas limit is $GAS_LIMIT (expected 0x1c9c380)"
fi

# Validate with Besu (if available)
log_warn "Validating with Besu..."
if command -v besu &> /dev/null; then
    # Try to validate genesis file with Besu
    if besu blocks import --from="$GENESIS_FILE" --to=/tmp/besu-test 2>&1 | grep -q "success\|imported"; then
        log_success "✓ Genesis file validated with Besu"
        rm -rf /tmp/besu-test
    else
        log_warn "⚠ Besu validation inconclusive (this is expected for genesis files)"
    fi
else
    log_warn "⚠ Besu not available for validation"
fi

log_success "Genesis file validation completed"
log_success "✓ All validations passed"
