#!/bin/bash
set -e
CHAIN_ID="genex-testnet-1"
DENOM="agnx"
HOME_DIR="/home/genex/.genexd"
KEYRING="test"
GENESIS="$HOME_DIR/config/genesis.json"

echo "[1/6] Initializing chain..."
genexd init "genex-us-east-1" --chain-id "$CHAIN_ID" --home "$HOME_DIR"

echo "[2/6] Patching genesis for Genex denom (agnx)..."
# Replace default denoms with agnx
cat "$GENESIS" | jq '
  # EVM module: set denom to agnx
  .app_state.evm.params.evm_denom = "agnx" |
  .app_state.evm.params.extended_denom_options.extended_denom = "agnx" |
  # Staking: bond denom
  .app_state.staking.params.bond_denom = "agnx" |
  # Mint: mint denom
  .app_state.mint.params.mint_denom = "agnx" |
  # Gov: min deposit denom
  .app_state.gov.params.min_deposit[0].denom = "agnx" |
  .app_state.gov.params.expedited_min_deposit[0].denom = "agnx" |
  # Bank: add denom metadata for agnx (18 decimals for EVM compat)
  .app_state.bank.denom_metadata = [{
    "description": "The native staking and gas token of Genex Chain",
    "denom_units": [
      {"denom": "agnx", "exponent": 0, "aliases": ["attoGNX"]},
      {"denom": "GNX",  "exponent": 18, "aliases": []}
    ],
    "base": "agnx",
    "display": "GNX",
    "name": "Genex Token",
    "symbol": "GNX"
  }] |
  # FeeMarket: use zero gas for dev
  .app_state.feemarket.params.min_gas_price = "0.000000000000000000" |
  .app_state.feemarket.params.base_fee = "1000000000.000000000000000000" |
  # Mint: 通胀参数 — 控制年增发率
  # 初始 5%，范围 2%-7%，目标 staking 比例 50%
  .app_state.mint.minter.inflation = "0.050000000000000000" |
  .app_state.mint.params.inflation_rate_change = "0.050000000000000000" |
  .app_state.mint.params.inflation_max = "0.070000000000000000" |
  .app_state.mint.params.inflation_min = "0.020000000000000000" |
  .app_state.mint.params.goal_bonded = "0.500000000000000000"
' > "${GENESIS}.tmp" && mv "${GENESIS}.tmp" "$GENESIS"

# ============================================================
# 代币经济模型 — 总量 10 亿 GNX (1,000,000,000)
# ============================================================
# 1 GNX = 10^18 agnx (18 位小数，与 EVM wei 对齐)
#
# 分配方案:
#   validator   3.5 亿 (35%) — 验证者节点，stake 2.5 亿保障链安全
#   treasury    2.0 亿 (20%) — 平台运营储备，Gas Relayer 补贴池
#   ecosystem   2.0 亿 (20%) — 生态发展基金，合作方/DApp 激励
#   team        1.5 亿 (15%) — 团队 & 早期投资者 (链下管理释放计划)
#   community   1.0 亿 (10%) — 社区治理 / DAO 储备
# ============================================================

VALIDATOR_AMOUNT="350000000000000000000000000"   # 3.5 亿 GNX
TREASURY_AMOUNT="200000000000000000000000000"    # 2.0 亿 GNX
ECOSYSTEM_AMOUNT="200000000000000000000000000"   # 2.0 亿 GNX
TEAM_AMOUNT="150000000000000000000000000"        # 1.5 亿 GNX
COMMUNITY_AMOUNT="100000000000000000000000000"   # 1.0 亿 GNX
STAKE_AMOUNT="250000000000000000000000000"       # 2.5 亿 GNX (validator self-delegation)

echo "[3/8] Creating genesis keys..."
genexd keys add validator  --keyring-backend "$KEYRING" --home "$HOME_DIR" 2>&1
genexd keys add treasury   --keyring-backend "$KEYRING" --home "$HOME_DIR" 2>&1
genexd keys add ecosystem  --keyring-backend "$KEYRING" --home "$HOME_DIR" 2>&1
genexd keys add team       --keyring-backend "$KEYRING" --home "$HOME_DIR" 2>&1
genexd keys add community  --keyring-backend "$KEYRING" --home "$HOME_DIR" 2>&1

echo "[4/8] Retrieving addresses..."
ADDR_VALIDATOR=$(genexd keys show validator  -a --keyring-backend "$KEYRING" --home "$HOME_DIR")
ADDR_TREASURY=$(genexd keys show treasury    -a --keyring-backend "$KEYRING" --home "$HOME_DIR")
ADDR_ECOSYSTEM=$(genexd keys show ecosystem  -a --keyring-backend "$KEYRING" --home "$HOME_DIR")
ADDR_TEAM=$(genexd keys show team            -a --keyring-backend "$KEYRING" --home "$HOME_DIR")
ADDR_COMMUNITY=$(genexd keys show community  -a --keyring-backend "$KEYRING" --home "$HOME_DIR")

echo "[5/8] Adding genesis accounts (total: 1,000,000,000 GNX)..."
genexd genesis add-genesis-account "$ADDR_VALIDATOR"  "${VALIDATOR_AMOUNT}${DENOM}"  --home "$HOME_DIR" --keyring-backend "$KEYRING"
genexd genesis add-genesis-account "$ADDR_TREASURY"   "${TREASURY_AMOUNT}${DENOM}"   --home "$HOME_DIR" --keyring-backend "$KEYRING"
genexd genesis add-genesis-account "$ADDR_ECOSYSTEM"  "${ECOSYSTEM_AMOUNT}${DENOM}"  --home "$HOME_DIR" --keyring-backend "$KEYRING"
genexd genesis add-genesis-account "$ADDR_TEAM"       "${TEAM_AMOUNT}${DENOM}"       --home "$HOME_DIR" --keyring-backend "$KEYRING"
genexd genesis add-genesis-account "$ADDR_COMMUNITY"  "${COMMUNITY_AMOUNT}${DENOM}"  --home "$HOME_DIR" --keyring-backend "$KEYRING"

echo "[6/8] Creating genesis transaction (validator stakes 2.5 亿 GNX)..."
genexd genesis gentx validator "${STAKE_AMOUNT}${DENOM}" \
    --chain-id "$CHAIN_ID" \
    --moniker "genex-us-east-1" \
    --commission-rate "0.10" \
    --commission-max-rate "0.20" \
    --commission-max-change-rate "0.01" \
    --min-self-delegation "1" \
    --keyring-backend "$KEYRING" \
    --home "$HOME_DIR"

echo "[7/8] Collecting genesis transactions and validating..."
genexd genesis collect-gentxs --home "$HOME_DIR"

echo "[8/8] Configure node — 性能优化配置..."
# ============================================================
# Configure node — 性能优化配置
# ============================================================

CONFIG_TOML="$HOME_DIR/config/config.toml"
APP_TOML="$HOME_DIR/config/app.toml"

# --- app.toml 配置 ---
sed -i "s/minimum-gas-prices = \"\"/minimum-gas-prices = \"0${DENOM}\"/" "$APP_TOML"
# Enable API
sed -i "/\[api\]/,/\[/ s/enable = false/enable = true/" "$APP_TOML"
# Enable JSON-RPC
sed -i "/\[json-rpc\]/,/\[/ s/enable = false/enable = true/" "$APP_TOML"
sed -i "s/address = \"127.0.0.1:8545\"/address = \"0.0.0.0:8545\"/" "$APP_TOML"
sed -i "s/ws-address = \"127.0.0.1:8546\"/ws-address = \"0.0.0.0:8546\"/" "$APP_TOML"
# Set EVM chain ID
sed -i "s/evm-chain-id = 262144/evm-chain-id = 8888/" "$APP_TOML" 2>/dev/null || true

# IAVL 缓存优化: 增大缓存提升状态读取速度 (默认 781250)
# 16 核 126GB 内存服务器，提升到 2,000,000 节点缓存
sed -i "s/iavl-cache-size = 781250/iavl-cache-size = 2000000/" "$APP_TOML"

# 启用 inter-block-cache: 跨区块状态缓存，减少重复读取
# (默认已启用，确保未被关闭)

# --- config.toml 配置 ---
# CORS 和 RPC 监听
sed -i "s/cors_allowed_origins = \[\]/cors_allowed_origins = [\"*\"]/" "$CONFIG_TOML"
sed -i "s/laddr = \"tcp:\/\/127.0.0.1:26657\"/laddr = \"tcp:\/\/0.0.0.0:26657\"/" "$CONFIG_TOML"

# ============================================================
# 共识参数优化 — 出块速度提升
# ============================================================
# timeout_propose: 提议超时 3s → 1.5s (单节点无网络延迟)
sed -i 's/timeout_propose = "3s"/timeout_propose = "1500ms"/' "$CONFIG_TOML"
sed -i 's/timeout_propose_delta = "500ms"/timeout_propose_delta = "200ms"/' "$CONFIG_TOML"

# timeout_prevote/precommit: 投票超时 (单节点无需等待其他验证者)
sed -i 's/timeout_prevote = "1s"/timeout_prevote = "500ms"/' "$CONFIG_TOML"
sed -i 's/timeout_prevote_delta = "500ms"/timeout_prevote_delta = "200ms"/' "$CONFIG_TOML"
sed -i 's/timeout_precommit = "1s"/timeout_precommit = "500ms"/' "$CONFIG_TOML"
sed -i 's/timeout_precommit_delta = "500ms"/timeout_precommit_delta = "200ms"/' "$CONFIG_TOML"

# timeout_commit: 5s → 1s — 稳定 ~1s/块
# genexd init 生成的 config.toml 默认 5s，必须通过 sed 修改
# (initCometConfig 的代码设置仅用于首次生成模板，不会覆盖已有文件)
# 单验证者: ~0.75-0.88s, 多验证者(20-50): ~1.5-2s
# 对标: dYdX 1-2s, Injective 1.2s, Cosmos Hub 6-7s
sed -i 's/timeout_commit = "5s"/timeout_commit = "1s"/' "$CONFIG_TOML"

# create_empty_blocks 保持默认 true:
# cosmos/evm 链的 EVM EndBlock 每次都改变 app hash,
# needProofBlock() 始终返回 true, 设 false 无实际效果 (ethermint#308)
# 磁盘: ~86,400 块/天 × ~1.5KB ≈ 130 MB/天, 配合 pruning 可控

# ============================================================
# Mempool 优化 — 提升交易吞吐
# ============================================================
# 增大 mempool 容量: 5000 → 10000 笔待处理交易
sed -i 's/^size = 5000/size = 10000/' "$CONFIG_TOML"
# 缓存大小: 10000 → 20000 (已见交易 hash 缓存，减少重复校验)
sed -i 's/cache_size = 10000/cache_size = 20000/' "$CONFIG_TOML"

echo ""
echo "============================================================"
echo "Genesis initialization complete!"
echo "============================================================"
echo "Chain ID:     $CHAIN_ID"
echo "EVM Chain ID: 8888"
echo "Denom:        $DENOM (GNX, 18 decimals)"
echo "Total Supply: 1,000,000,000 GNX (10 亿)"
echo ""
echo "Genesis Accounts:"
echo "  validator   $ADDR_VALIDATOR  350,000,000 GNX (35%) — staked 250M"
echo "  treasury    $ADDR_TREASURY   200,000,000 GNX (20%) — Gas Relayer pool"
echo "  ecosystem   $ADDR_ECOSYSTEM  200,000,000 GNX (20%) — DApp incentives"
echo "  team        $ADDR_TEAM       150,000,000 GNX (15%) — vesting"
echo "  community   $ADDR_COMMUNITY  100,000,000 GNX (10%) — DAO reserve"
echo ""
echo "Mint (Inflation):"
echo "  Initial: 5% | Range: 2%-7% | Target bonded: 50%"
echo ""
echo "Performance optimizations applied:"
echo "  - Optimistic Execution: enabled (code-level, SDK v0.53)"
echo "  - timeout_commit:       1s → ~0.75s/block (single-val), ~1.5-2s (multi-val)"
echo "  - timeout_propose:      1.5s (reduced from 3s)"
echo "  - Consensus timeouts:   prevote/precommit 500ms (reduced from 1s)"
echo "  - Empty blocks:         enabled (cosmos/evm requires, ~130 MB/day + pruning)"
echo "  - IAVL cache:           2,000,000 nodes (up from 781,250)"
echo "  - Mempool size:         10,000 txs (up from 5,000)"
echo "  - Mempool cache:        20,000 (up from 10,000)"
echo "============================================================"
