#!/usr/bin/env bash

# Generate Genesis with Validator Addresses for IBFT 2.0
# This script generates validator keys and creates a proper genesis.json with extraData

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/../lib/init.sh"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
cd "$PROJECT_ROOT"
# Load .env via dotenv (RPC CR/LF trim). Fallback: raw source.
if [[ -f "$SCRIPT_DIR/../lib/deployment/dotenv.sh" ]]; then
  # shellcheck disable=SC1090
  source "$SCRIPT_DIR/../lib/deployment/dotenv.sh"
  load_deployment_env --repo-root "${PROJECT_ROOT:-$REPO_ROOT}"
elif [[ -n "${PROJECT_ROOT:-}" && -f "$PROJECT_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$PROJECT_ROOT/.env"
  set +a
elif [[ -n "${REPO_ROOT:-}" && -f "$REPO_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$REPO_ROOT/.env"
  set +a
fi

CONFIG_DIR="$PROJECT_ROOT/config"
KEYS_DIR="$PROJECT_ROOT/keys"
VALIDATORS_DIR="$KEYS_DIR/validators"


CHAIN_ID=138
NUM_VALIDATORS=4

log_info "=== Generating Genesis with Validators for Chain ID ${CHAIN_ID} ==="

# Step 1: Generate validator keys if they don't exist
log_warn "Step 1: Checking validator keys..."
if [ ! -d "$VALIDATORS_DIR" ] || [ -z "$(ls -A $VALIDATORS_DIR 2>/dev/null)" ]; then
    log_warn "  Generating ${NUM_VALIDATORS} validator keys..."
    if [ -f "scripts/key-management/generate-validator-keys.sh" ]; then
        ./scripts/key-management/generate-validator-keys.sh $NUM_VALIDATORS
    else
        log_error "  ❌ Key generation script not found"
        log_warn "  Creating keys manually..."
        mkdir -p "$VALIDATORS_DIR"
        for i in $(seq 1 $NUM_VALIDATORS); do
            VALIDATOR_DIR="$VALIDATORS_DIR/validator-$i"
            mkdir -p "$VALIDATOR_DIR"
            PRIVATE_KEY=$(openssl rand -hex 32)
            echo "$PRIVATE_KEY" > "$VALIDATOR_DIR/key.priv"
            chmod 600 "$VALIDATOR_DIR/key.priv"
            log_success "  ✅ Generated validator $i key"
        done
    fi
else
    KEY_COUNT=$(find "$VALIDATORS_DIR" -name "key.priv" 2>/dev/null | wc -l)
    log_success "  ✅ Found ${KEY_COUNT} validator keys"
fi

# Step 2: Try to generate proper genesis using Besu
log_warn "Step 2: Generating genesis with Besu..."
if command -v besu &> /dev/null; then
    log_success "  ✅ Besu CLI found"
    
    # Create genesis template if it doesn't exist
    if [ ! -f "$CONFIG_DIR/genesis-template.json" ]; then
        cat > "$CONFIG_DIR/genesis-template.json" <<EOF
{
  "genesis": {
    "config": {
      "chainId": ${CHAIN_ID},
      "berlinBlock": 0,
      "londonBlock": 0,
      "istanbulBlock": 0,
      "ibft2": {
        "blockperiodseconds": 2,
        "epochlength": 30000,
        "requesttimeoutseconds": 10
      }
    },
    "nonce": "0x0",
    "timestamp": "0x0",
    "gasLimit": "0x1c9c380",
    "difficulty": "0x1",
    "mixHash": "0x63746963616c2062797a616e74696e65206661756c7420746f6c6572616e6365",
    "coinbase": "0x0000000000000000000000000000000000000000",
    "alloc": {}
  },
  "blockchain": {
    "nodes": {
      "generate": true,
      "count": ${NUM_VALIDATORS}
    }
  }
}
EOF
        log_success "  ✅ Created genesis-template.json"
    fi
    
    # Try to use Besu to generate proper genesis
    TEMP_GENESIS_DIR=$(mktemp -d)
    if besu operator generate-blockchain-config \
        --config-file="$CONFIG_DIR/genesis-template.json" \
        --to="$TEMP_GENESIS_DIR" \
        --private-key-file-name=key.priv 2>/dev/null; then
        log_success "  ✅ Generated genesis using Besu"
        
        # Copy generated genesis if it exists
        if [ -f "$TEMP_GENESIS_DIR/genesis.json" ]; then
            cp "$TEMP_GENESIS_DIR/genesis.json" "$CONFIG_DIR/genesis.json"
            log_success "  ✅ Updated config/genesis.json with proper extraData"
        fi
        
        # Copy validator keys if generated
        if [ -d "$TEMP_GENESIS_DIR/keys" ]; then
            cp -r "$TEMP_GENESIS_DIR/keys"/* "$VALIDATORS_DIR/" 2>/dev/null || true
        fi
        
        rm -rf "$TEMP_GENESIS_DIR"
    else
        log_warn "  ⚠️  Besu genesis generation failed (may need manual configuration)"
        rm -rf "$TEMP_GENESIS_DIR"
    fi
else
    log_warn "  ⚠️  Besu CLI not found"
    log_warn "  Install Besu to generate proper IBFT 2.0 extraData"
    log_warn "  Visit: https://besu.hyperledger.org/en/stable/HowTo/Get-Started/Installation-Options/"
fi

# Step 3: Verify genesis file
log_warn "Step 3: Verifying genesis file..."
if [ -f "$CONFIG_DIR/genesis.json" ]; then
    EXTRADATA=$(grep -oE '"extraData"[[:space:]]*:[[:space:]]*"[^"]*"' "$CONFIG_DIR/genesis.json" | cut -d'"' -f4)
    if [ "$EXTRADATA" = "0x" ] || [ -z "$EXTRADATA" ]; then
        log_error "  ❌ Genesis extraData is still empty"
        log_warn "  ⚠️  Manual step required:"
        log_warn "     1. Extract validator addresses from keys/validators/*/key.priv"
        log_warn "     2. Use Besu to generate proper RLP-encoded extraData"
        log_warn "     3. Update config/genesis.json extraData field"
        log_warn "  Alternative: Use Besu's operator generate-blockchain-config command"
        log_warn "  Example:"
        log_warn "    besu operator generate-blockchain-config \\"
        log_warn "      --config-file=config/genesis-template.json \\"
        log_warn "      --to=keys/validators \\"
        log_warn "      --private-key-file-name=key.priv"
    else
        EXTRADATA_LEN=${#EXTRADATA}
        if [ "$EXTRADATA_LEN" -gt 4 ]; then
            log_success "  ✅ Genesis extraData appears to contain validators (length: ${EXTRADATA_LEN} chars)"
        else
            log_warn "  ⚠️  Genesis extraData may be incomplete (length: ${EXTRADATA_LEN} chars)"
        fi
    fi
    
    # Verify Chain ID
    GENESIS_CHAIN_ID=$(grep -oE '"chainId"[[:space:]]*:[[:space:]]*[0-9]+' "$CONFIG_DIR/genesis.json" | grep -oE '[0-9]+')
    if [ "$GENESIS_CHAIN_ID" = "138" ]; then
        log_success "  ✅ Chain ID: 138 (correct)"
    else
        log_error "  ❌ Chain ID mismatch: ${GENESIS_CHAIN_ID} (expected 138)"
    fi
else
    log_error "  ❌ Genesis file not found"
fi

log_info "=== Summary ==="
log_success "Genesis generation process completed"
log_warn "Next Steps:"
echo "  1. Verify validator keys exist: ls -la keys/validators/*/key.priv"
echo "  2. If extraData is still empty, use Besu to generate proper genesis:"
echo "     besu operator generate-blockchain-config --config-file=config/genesis-template.json --to=keys/validators"
echo "  3. Update all ConfigMaps in k8s/base/*/statefulset.yaml with new genesis.json"
echo "  4. Update Helm ConfigMaps if using Helm deployment"

