#!/bin/bash
# XDC Node Start Script with Genesis Guard Integration
# Usage: ./start-node.sh [mainnet|apothem] [datadir]

set -e

# Get script directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# Default values
NETWORK="${1:-mainnet}"
DATADIR="${2:-./testdata}"

# Determine chainId based on network
case "$NETWORK" in
    mainnet)
        CHAIN_ID=50
        GENESIS_FILE="$SCRIPT_DIR/genesis/xdc_mainnet.json"
        ;;
    apothem)
        CHAIN_ID=51
        GENESIS_FILE="$SCRIPT_DIR/genesis/xdc_apothem.json"
        ;;
    *)
        echo "Error: Unknown network '$NETWORK'. Use 'mainnet' or 'apothem'."
        exit 1
        ;;
esac

echo "=========================================="
echo "XDC Node Starter"
echo "Network: $NETWORK (Chain ID: $CHAIN_ID)"
echo "Data Directory: $DATADIR"
echo "=========================================="

# Run Genesis Guard to validate genesis hash
if [[ -f "$SCRIPT_DIR/scripts/genesis-guard.sh" ]]; then
    echo "Running Genesis Guard validation..."
    "$SCRIPT_DIR/scripts/genesis-guard.sh" \
        --datadir "$DATADIR" \
        --chainId "$CHAIN_ID" \
        --network "$NETWORK" \
        --genesis "$GENESIS_FILE" \
        --force || {
        echo "Error: Genesis Guard validation failed!"
        exit 1
    }
else
    echo "Warning: Genesis Guard script not found. Skipping validation."
fi

# Kill any existing geth process
echo "Stopping any existing geth processes..."
pkill -9 -f "geth" 2>/dev/null || true
rm -f "$DATADIR/geth.ipc" 2>/dev/null || true
sleep 1

# Determine port based on network
if [[ "$NETWORK" == "mainnet" ]]; then
    PORT=30304
    HTTP_PORT=8547
else
    PORT=30305
    HTTP_PORT=8548
fi

# Initialize genesis if chaindata doesn't exist
if [[ ! -d "$DATADIR/geth/chaindata" && -f "$GENESIS_FILE" ]]; then
    echo "Initializing genesis block..."
    geth init --datadir "$DATADIR" "$GENESIS_FILE" 2>&1 || {
        echo "Warning: Genesis initialization may have failed. Continuing..."
    }
fi

echo "Starting XDC node on $NETWORK (Chain ID: $CHAIN_ID)..."

# Start the node
geth \
    --datadir "$DATADIR" \
    --networkid "$CHAIN_ID" \
    --port "$PORT" \
    --syncmode full \
    --verbosity 4 \
    --nodiscover \
    --http \
    --http.addr 0.0.0.0 \
    --http.port "$HTTP_PORT" \
    --http.api eth,net,web3,admin,debug,txpool \
    --http.vhosts=* \
    > /tmp/geth-$NETWORK.log 2>&1 &

PID=$!
echo "Started geth with PID: $PID"
echo "Log file: /tmp/geth-$NETWORK.log"

# Wait for node to start
sleep 5

# Check if process is still running
if ! kill -0 $PID 2>/dev/null; then
    echo "Error: Node failed to start. Check log at /tmp/geth-$NETWORK.log"
    exit 1
fi

# Test RPC connection
echo "Testing RPC connection..."
for i in {1..10}; do
    BLOCK_NUMBER=$(curl -s http://127.0.0.1:$HTTP_PORT \
        -X POST \
        -H "Content-Type: application/json" \
        -d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' 2>/dev/null | grep -o '"result":"[^"]*"' | cut -d'"' -f4 || echo "")
    
    if [[ -n "$BLOCK_NUMBER" ]]; then
        echo "Node is responding! Current block: $BLOCK_NUMBER"
        
        # Verify chainId
        CHAIN_CHECK=$(curl -s http://127.0.0.1:$HTTP_PORT \
            -X POST \
            -H "Content-Type: application/json" \
            -d '{"jsonrpc":"2.0","method":"eth_chainId","params":[],"id":1}' 2>/dev/null | grep -o '"result":"[^"]*"' | cut -d'"' -f4 || echo "")
        
        if [[ -n "$CHAIN_CHECK" ]]; then
            # Convert hex to decimal
            CHAIN_DECIMAL=$((CHAIN_CHECK))
            if [[ "$CHAIN_DECIMAL" == "$CHAIN_ID" ]]; then
                echo "Chain ID verified: $CHAIN_DECIMAL"
            else
                echo "Warning: Chain ID mismatch! Expected $CHAIN_ID, got $CHAIN_DECIMAL"
            fi
        fi
        
        # Get genesis block hash for validation
        GENESIS_HASH=$(curl -s http://127.0.0.1:$HTTP_PORT \
            -X POST \
            -H "Content-Type: application/json" \
            -d '{"jsonrpc":"2.0","method":"eth_getBlockByNumber","params":["0x0",false],"id":1}' 2>/dev/null | grep -o '"hash":"[^"]*"' | head -1 | cut -d'"' -f4 || echo "")
        
        if [[ -n "$GENESIS_HASH" ]]; then
            echo "Genesis block hash: $GENESIS_HASH"
        fi
        
        echo "=========================================="
        echo "Node started successfully!"
        echo "RPC endpoint: http://127.0.0.1:$HTTP_PORT"
        echo "=========================================="
        exit 0
    fi
    
    echo "Waiting for node to be ready... ($i/10)"
    sleep 2
done

echo "Warning: Could not verify RPC connection. Check log at /tmp/geth-$NETWORK.log"
exit 1
