#!/bin/bash
# Genex Chain — 多验证节点测试网初始化脚本
#
# 用法: bash scripts/init-testnet.sh
# 或:   make init-testnet
#
# 生成 5 个验证节点配置:
#   genex-us-east-1   (创世节点)
#   genex-us-west-1   (创世节点)
#   genex-sg-1        (创世节点)
#   genex-inst-1      (机构节点)
#   genex-inst-2      (机构节点)
#
# 另外生成 1 个监管只读节点:
#   genex-regulatory-1

set -euo pipefail

BINARY="./build/genexd"
CHAIN_ID="genex-testnet-1"
DENOM="agnx"           # atto GNX, 18 decimals (EVM 兼容)
KEYRING="test"
BASE_DIR="./testnet"

# 节点配置
NODES=(
    "genex-us-east-1:genesis:26656:26657:8545"
    "genex-us-west-1:genesis:26666:26667:8555"
    "genex-sg-1:genesis:26676:26677:8565"
    "genex-inst-1:institution:26686:26687:8575"
    "genex-inst-2:institution:26696:26697:8585"
)

echo "============================================"
echo "  Genex Chain — Testnet Initialization"
echo "  ${#NODES[@]} Validator Nodes + 1 Regulatory"
echo "============================================"

# 编译
echo ""
echo "[1/7] Building genexd..."
make build

# 清理
echo "[2/7] Cleaning previous testnet data..."
rm -rf "$BASE_DIR"
mkdir -p "$BASE_DIR"

# 初始化所有节点
echo "[3/7] Initializing nodes..."
for node_config in "${NODES[@]}"; do
    IFS=':' read -r moniker type p2p_port rpc_port evm_port <<< "$node_config"
    node_home="$BASE_DIR/$moniker"

    echo "  Initializing $moniker ($type)..."
    $BINARY init "$moniker" --chain-id "$CHAIN_ID" --home "$node_home" > /dev/null 2>&1

    # 创建验证者密钥
    $BINARY keys add validator --keyring-backend "$KEYRING" --home "$node_home" > /dev/null 2>&1
done

# 收集所有验证者地址
echo "[4/7] Creating genesis accounts..."
GENESIS_HOME="$BASE_DIR/genex-us-east-1"

for node_config in "${NODES[@]}"; do
    IFS=':' read -r moniker type p2p_port rpc_port evm_port <<< "$node_config"
    node_home="$BASE_DIR/$moniker"

    ADDR=$($BINARY keys show validator -a --keyring-backend "$KEYRING" --home "$node_home")

    # 不同节点类型不同质押量 (18 decimals: N * 10^18)
    if [ "$type" = "genesis" ]; then
        AMOUNT="100000000000000000000000000${DENOM}"  # 100M GNX (10^8 * 10^18)
    else
        AMOUNT="50000000000000000000000000${DENOM}"   # 50M GNX (5*10^7 * 10^18)
    fi

    $BINARY genesis add-genesis-account "$ADDR" "$AMOUNT" --home "$GENESIS_HOME" --keyring-backend "$KEYRING"
    echo "  $moniker ($type): $ADDR — $AMOUNT"
done

# 平台运营账户
echo "  Adding platform operations account..."
$BINARY keys add platform --keyring-backend "$KEYRING" --home "$GENESIS_HOME" > /dev/null 2>&1
PLATFORM_ADDR=$($BINARY keys show platform -a --keyring-backend "$KEYRING" --home "$GENESIS_HOME")
$BINARY genesis add-genesis-account "$PLATFORM_ADDR" "400000000000000000000000000${DENOM}" --home "$GENESIS_HOME"  # 400M GNX

# 创建 GenTx
echo "[5/7] Creating genesis transactions..."
for node_config in "${NODES[@]}"; do
    IFS=':' read -r moniker type p2p_port rpc_port evm_port <<< "$node_config"
    node_home="$BASE_DIR/$moniker"

    if [ "$type" = "genesis" ]; then
        STAKE="50000000000000000000000000${DENOM}"   # 50M GNX
    else
        STAKE="25000000000000000000000000${DENOM}"   # 25M GNX
    fi

    $BINARY genesis gentx validator "$STAKE" \
        --chain-id "$CHAIN_ID" \
        --moniker "$moniker" \
        --commission-rate "0.10" \
        --commission-max-rate "0.20" \
        --commission-max-change-rate "0.01" \
        --min-self-delegation "1" \
        --keyring-backend "$KEYRING" \
        --home "$node_home"

    # 复制 gentx 到主节点
    cp "$node_home/config/gentx/"*.json "$GENESIS_HOME/config/gentx/" 2>/dev/null || true
done

# 收集 GenTx
echo "[6/7] Collecting genesis transactions..."
$BINARY genesis collect-gentxs --home "$GENESIS_HOME"
$BINARY genesis validate-genesis --home "$GENESIS_HOME"

# 分发创世文件和配置
echo "[7/7] Distributing genesis and configuring peers..."
PERSISTENT_PEERS=""
for node_config in "${NODES[@]}"; do
    IFS=':' read -r moniker type p2p_port rpc_port evm_port <<< "$node_config"
    node_home="$BASE_DIR/$moniker"

    # 复制创世文件
    cp "$GENESIS_HOME/config/genesis.json" "$node_home/config/genesis.json"

    # 获取 node ID
    NODE_ID=$($BINARY tendermint show-node-id --home "$node_home")

    if [ -n "$PERSISTENT_PEERS" ]; then
        PERSISTENT_PEERS="${PERSISTENT_PEERS},"
    fi
    PERSISTENT_PEERS="${PERSISTENT_PEERS}${NODE_ID}@127.0.0.1:${p2p_port}"
done

# 配置所有节点
for node_config in "${NODES[@]}"; do
    IFS=':' read -r moniker type p2p_port rpc_port evm_port <<< "$node_config"
    node_home="$BASE_DIR/$moniker"

    # 配置 P2P 端口
    sed -i "s|laddr = \"tcp://0.0.0.0:26656\"|laddr = \"tcp://0.0.0.0:${p2p_port}\"|" "$node_home/config/config.toml"
    sed -i "s|laddr = \"tcp://127.0.0.1:26657\"|laddr = \"tcp://127.0.0.1:${rpc_port}\"|" "$node_home/config/config.toml"

    # 配置持久对等节点
    sed -i "s|persistent_peers = \"\"|persistent_peers = \"${PERSISTENT_PEERS}\"|" "$node_home/config/config.toml"

    # Gas 补贴
    sed -i 's|minimum-gas-prices = ""|minimum-gas-prices = "0agnx"|' "$node_home/config/app.toml"

    echo "  $moniker configured (P2P: $p2p_port, RPC: $rpc_port, EVM: $evm_port)"
done

# 初始化监管只读节点
echo ""
echo "Initializing regulatory observer node..."
REG_HOME="$BASE_DIR/genex-regulatory-1"
$BINARY init "genex-regulatory-1" --chain-id "$CHAIN_ID" --home "$REG_HOME" > /dev/null 2>&1
cp "$GENESIS_HOME/config/genesis.json" "$REG_HOME/config/genesis.json"
sed -i "s|persistent_peers = \"\"|persistent_peers = \"${PERSISTENT_PEERS}\"|" "$REG_HOME/config/config.toml"

echo ""
echo "============================================"
echo "  Testnet Initialization Complete!"
echo "============================================"
echo ""
echo "Chain ID: $CHAIN_ID"
echo "Nodes:    ${#NODES[@]} validators + 1 regulatory"
echo "Base Dir: $BASE_DIR"
echo ""
echo "To start all nodes:"
echo "  for dir in $BASE_DIR/genex-*; do"
echo "    $BINARY start --home \$dir &"
echo "  done"
echo ""
echo "Node Endpoints:"
for node_config in "${NODES[@]}"; do
    IFS=':' read -r moniker type p2p_port rpc_port evm_port <<< "$node_config"
    echo "  $moniker ($type):"
    echo "    P2P: :$p2p_port  RPC: :$rpc_port  EVM: :$evm_port"
done
echo ""
echo "============================================"
