#!/bin/bash
#
# Genex Blockchain — 部署管理脚本
# =========================================
#
# 用法:
#   ./deploy.sh up                # 启动全部验证节点 (3创世+2机构+1监管)
#   ./deploy.sh down              # 停止全部节点
#   ./deploy.sh restart           # 重启全部节点
#   ./deploy.sh build             # 增量编译节点镜像
#   ./deploy.sh build-no-cache    # 全新编译节点镜像 (无缓存)
#   ./deploy.sh status            # 查看节点状态
#   ./deploy.sh health            # 健康检查
#   ./deploy.sh logs [node]       # 查看日志
#
# 单节点模式:
#   ./deploy.sh dev               # 仅启动 node-1 (开发模式)
#
# 生态服务:
#   ./deploy.sh eco-up            # 启动生态服务 (Enterprise API, Gas Relayer, Faucet, Bridge, Archive)
#   ./deploy.sh eco-down          # 停止生态服务
#   ./deploy.sh eco-status        # 生态服务状态
#   ./deploy.sh eco-logs [svc]    # 生态服务日志
#   ./deploy.sh eco-build         # 增量编译生态服务
#   ./deploy.sh eco-build-no-cache # 全新编译生态服务
#
# 智能合约:
#   ./deploy.sh deploy-contracts  # 部署智能合约
#   ./deploy.sh test-contracts    # 运行合约测试
#
# 区块浏览器:
#   ./deploy.sh explorer-up       # 启动 Blockscout
#   ./deploy.sh explorer-down     # 停止 Blockscout
#   ./deploy.sh explorer-logs     # 浏览器日志
#
# 监控:
#   ./deploy.sh monitor-up        # 启动 Prometheus + Grafana
#   ./deploy.sh monitor-down      # 停止监控
#   ./deploy.sh monitor-logs      # 监控日志
#
# 单服务操作:
#   ./deploy.sh start-svc <name>               # 启动指定服务
#   ./deploy.sh stop-svc <name>                # 停止指定服务
#   ./deploy.sh restart-svc <name>             # 重启指定服务
#   ./deploy.sh rebuild-svc <name>             # 增量编译并重启
#   ./deploy.sh rebuild-svc <name> --no-cache  # 全新编译并重启
#

set -e

# ===========================================================================
# 配置
# ===========================================================================
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
COMPOSE_FILE="$SCRIPT_DIR/docker-compose.yml"
EXPLORER_COMPOSE="$SCRIPT_DIR/docker-compose.explorer.yml"
MONITOR_COMPOSE="$SCRIPT_DIR/chain-monitor/docker-compose.monitor.yml"

# 颜色
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m'

log_info()    { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[OK]${NC} $1"; }
log_warn()    { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error()   { echo -e "${RED}[ERROR]${NC} $1"; }
log_step()    { echo -e "${CYAN}[STEP]${NC} $1"; }

# 节点列表
GENESIS_NODES="genex-node-1 genex-node-2 genex-node-3"
INST_NODES="genex-inst-1 genex-inst-2"
REGULATORY_NODES="genex-regulatory"
ALL_NODES="$GENESIS_NODES $INST_NODES $REGULATORY_NODES"

# 生态服务列表
ECO_SERVICES="enterprise-api gas-relayer faucet bridge-monitor genex-archive"

compose() {
    docker compose -f "$COMPOSE_FILE" "$@"
}

# ===========================================================================
# 节点操作
# ===========================================================================

up() {
    log_step "启动 Genex Blockchain 全部节点..."
    compose up -d
    log_success "全部节点已启动 (3创世 + 2机构 + 1监管)"
    echo ""
    log_info "主节点 RPC:   http://localhost:26657"
    log_info "EVM JSON-RPC: http://localhost:8545"
    log_info "Cosmos REST:  http://localhost:1317"
}

down() {
    log_step "停止全部节点..."
    compose down
    log_success "全部节点已停止"
}

restart() {
    log_step "重启全部节点..."
    down
    sleep 3
    up
}

dev() {
    log_step "启动单节点开发模式 (genex-node-1)..."
    compose up -d genex-node-1
    log_success "开发节点已启动"
    echo ""
    log_info "CometBFT RPC: http://localhost:26657"
    log_info "EVM JSON-RPC: http://localhost:8545"
    log_info "EVM WS:       ws://localhost:8546"
    log_info "Cosmos REST:  http://localhost:1317"
    log_info "gRPC:         localhost:9090"
}

build() {
    log_step "增量编译节点镜像..."
    compose build
    log_success "节点镜像编译完成"
}

build_no_cache() {
    log_step "全新编译节点镜像 (无缓存)..."
    compose build --no-cache
    log_success "节点镜像全新编译完成"
}

status() {
    echo ""
    echo "============================================"
    echo "  Genex Blockchain 节点状态"
    echo "============================================"
    echo ""
    compose ps
    echo ""
    health
}

health() {
    echo "============================================"
    echo "  健康检查"
    echo "============================================"
    echo ""

    # 主节点检查
    local nodes=(
        "genex-node-1:26657"
        "genex-node-2:26667"
        "genex-node-3:26677"
        "genex-inst-1:26687"
        "genex-inst-2:26697"
        "genex-regulatory:26707"
    )

    echo "验证节点:"
    for node in "${nodes[@]}"; do
        name="${node%%:*}"
        port="${node#*:}"
        if curl -sf "http://localhost:${port}/status" > /dev/null 2>&1; then
            echo -e "  ${GREEN}[OK]${NC}   $name (:$port)"
        else
            echo -e "  ${RED}[FAIL]${NC} $name (:$port)"
        fi
    done

    echo ""
    echo "EVM RPC:"
    local evm_nodes=(
        "genex-node-1:8545"
        "genex-node-2:8555"
        "genex-node-3:8565"
    )
    for node in "${evm_nodes[@]}"; do
        name="${node%%:*}"
        port="${node#*:}"
        if curl -sf -X POST "http://localhost:${port}" \
            -H "Content-Type: application/json" \
            -d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' > /dev/null 2>&1; then
            echo -e "  ${GREEN}[OK]${NC}   $name EVM (:$port)"
        else
            echo -e "  ${RED}[FAIL]${NC} $name EVM (:$port)"
        fi
    done

    echo ""
}

logs() {
    local target="$1"
    if [ -n "$target" ]; then
        compose logs -f "$target"
    else
        compose logs -f
    fi
}

# ===========================================================================
# 生态服务操作
# ===========================================================================

eco_up() {
    log_step "启动生态服务..."
    compose --profile ecosystem up -d
    log_success "生态服务已启动"
    echo ""
    log_info "Enterprise API:  http://localhost:3020"
    log_info "Gas Relayer:     http://localhost:3022"
    log_info "Faucet:          http://localhost:3023"
    log_info "Bridge Monitor:  http://localhost:3024"
}

eco_down() {
    log_step "停止生态服务..."
    compose --profile ecosystem stop enterprise-api gas-relayer faucet bridge-monitor genex-archive
    log_success "生态服务已停止"
}

eco_status() {
    echo ""
    echo "============================================"
    echo "  生态服务状态"
    echo "============================================"
    echo ""
    compose --profile ecosystem ps enterprise-api gas-relayer faucet bridge-monitor genex-archive

    echo ""
    echo "健康检查:"
    local eco_checks=(
        "enterprise-api:3020:/health"
        "gas-relayer:3022:/health"
        "faucet:3023:/health"
        "bridge-monitor:3024:/health"
    )
    for svc in "${eco_checks[@]}"; do
        name="${svc%%:*}"
        rest="${svc#*:}"
        port="${rest%%:*}"
        endpoint="${rest#*:}"
        if curl -sf "http://localhost:${port}${endpoint}" > /dev/null 2>&1; then
            echo -e "  ${GREEN}[OK]${NC}   $name (:$port)"
        else
            echo -e "  ${RED}[FAIL]${NC} $name (:$port)"
        fi
    done
    echo ""
}

eco_logs() {
    local service="$1"
    if [ -n "$service" ]; then
        compose logs -f "$service"
    else
        compose --profile ecosystem logs -f enterprise-api gas-relayer faucet bridge-monitor genex-archive
    fi
}

eco_build() {
    log_step "增量编译生态服务..."
    compose --profile ecosystem build
    log_success "生态服务编译完成"
}

eco_build_no_cache() {
    log_step "全新编译生态服务 (无缓存)..."
    compose --profile ecosystem build --no-cache
    log_success "生态服务全新编译完成"
}

# ===========================================================================
# 智能合约
# ===========================================================================

deploy_contracts() {
    log_step "部署智能合约..."
    compose --profile deploy run --rm contract-deployer
    log_success "合约部署完成"
}

test_contracts() {
    log_step "运行智能合约测试..."
    cd "$SCRIPT_DIR/genex-contracts"
    forge test -vvv --gas-report
    log_success "合约测试完成"
}

# ===========================================================================
# 区块浏览器
# ===========================================================================

explorer_up() {
    log_step "启动 Blockscout 区块浏览器..."
    docker compose -f "$COMPOSE_FILE" -f "$EXPLORER_COMPOSE" up -d
    log_success "Blockscout 已启动"
    log_info "访问: http://localhost:4000"
}

explorer_down() {
    log_step "停止 Blockscout..."
    docker compose -f "$COMPOSE_FILE" -f "$EXPLORER_COMPOSE" down
    log_success "Blockscout 已停止"
}

explorer_logs() {
    docker compose -f "$COMPOSE_FILE" -f "$EXPLORER_COMPOSE" logs -f
}

# ===========================================================================
# 链监控
# ===========================================================================

monitor_up() {
    log_step "启动链监控 (Prometheus + Grafana + AlertManager)..."
    docker compose -f "$MONITOR_COMPOSE" up -d
    log_success "监控栈已启动"
    echo ""
    log_info "Prometheus:   http://localhost:9090"
    log_info "Grafana:      http://localhost:3030 (密码: genex_admin_2024)"
    log_info "AlertManager: http://localhost:9093"
}

monitor_down() {
    log_step "停止链监控..."
    docker compose -f "$MONITOR_COMPOSE" down
    log_success "监控栈已停止"
}

monitor_logs() {
    docker compose -f "$MONITOR_COMPOSE" logs -f
}

# ===========================================================================
# 单服务操作
# ===========================================================================

start_svc() {
    local service="$1"
    if [ -z "$service" ]; then
        log_error "请指定服务名"
        exit 1
    fi
    log_info "启动 $service..."
    compose up -d "$service"
    log_success "$service 已启动"
}

stop_svc() {
    local service="$1"
    if [ -z "$service" ]; then
        log_error "请指定服务名"
        exit 1
    fi
    log_info "停止 $service..."
    compose stop "$service"
    log_success "$service 已停止"
}

restart_svc() {
    local service="$1"
    if [ -z "$service" ]; then
        log_error "请指定服务名"
        exit 1
    fi
    log_info "重启 $service..."
    compose stop "$service"
    compose up -d "$service"
    log_success "$service 已重启"
}

rebuild_svc() {
    local service="$1"
    local flag="$2"
    if [ -z "$service" ]; then
        log_error "请指定服务名"
        exit 1
    fi
    log_info "编译 $service..."
    if [ "$flag" = "--no-cache" ]; then
        compose build --no-cache "$service"
    else
        compose build "$service"
    fi
    compose up -d "$service"
    log_success "$service 编译并重启完成"
}

# ===========================================================================
# 清理
# ===========================================================================

clean() {
    log_warn "这将删除全部区块链节点容器、数据卷和镜像!"
    log_warn "所有链上数据将丢失!"
    read -p "确认操作? (y/N): " confirm
    if [ "$confirm" = "y" ] || [ "$confirm" = "Y" ]; then
        log_step "清理全部区块链资源..."
        compose --profile ecosystem --profile deploy down -v --rmi all
        log_success "清理完成"
    else
        log_info "已取消"
    fi
}

# ===========================================================================
# 主入口
# ===========================================================================

case "${1:-}" in
    # 全局
    up|start)        up ;;
    down|stop)       down ;;
    restart)         restart ;;
    dev)             dev ;;
    build)           build ;;
    build-no-cache)  build_no_cache ;;
    status|ps)       status ;;
    health)          health ;;
    logs)            logs "$2" ;;
    clean)           clean ;;

    # 生态服务
    eco-up)              eco_up ;;
    eco-down)            eco_down ;;
    eco-status)          eco_status ;;
    eco-logs)            eco_logs "$2" ;;
    eco-build)           eco_build ;;
    eco-build-no-cache)  eco_build_no_cache ;;

    # 智能合约
    deploy-contracts)    deploy_contracts ;;
    test-contracts)      test_contracts ;;

    # 区块浏览器
    explorer-up)         explorer_up ;;
    explorer-down)       explorer_down ;;
    explorer-logs)       explorer_logs ;;

    # 链监控
    monitor-up)          monitor_up ;;
    monitor-down)        monitor_down ;;
    monitor-logs)        monitor_logs ;;

    # 单服务操作
    start-svc)       start_svc "$2" ;;
    stop-svc)        stop_svc "$2" ;;
    restart-svc)     restart_svc "$2" ;;
    rebuild-svc)     rebuild_svc "$2" "$3" ;;

    *)
        echo "Genex Blockchain 部署管理脚本"
        echo ""
        echo "用法: $0 <命令> [参数]"
        echo ""
        echo "节点命令:"
        echo "  up/start          启动全部节点 (3创世+2机构+1监管)"
        echo "  down/stop         停止全部节点"
        echo "  restart           重启全部节点"
        echo "  dev               单节点开发模式 (仅 node-1)"
        echo "  build             增量编译节点镜像"
        echo "  build-no-cache    全新编译 (无缓存)"
        echo "  status/ps         节点状态 + 健康检查"
        echo "  health            仅健康检查"
        echo "  logs [node]       查看日志"
        echo "  clean             清理全部 (删除链数据!)"
        echo ""
        echo "生态服务命令:"
        echo "  eco-up             启动 (Enterprise API, Gas Relayer, Faucet, Bridge, Archive)"
        echo "  eco-down           停止"
        echo "  eco-status         状态 + 健康检查"
        echo "  eco-logs [svc]     日志"
        echo "  eco-build          增量编译"
        echo "  eco-build-no-cache 全新编译 (无缓存)"
        echo ""
        echo "智能合约命令:"
        echo "  deploy-contracts   部署合约到链上"
        echo "  test-contracts     运行 Foundry 测试 (forge test)"
        echo ""
        echo "区块浏览器命令:"
        echo "  explorer-up        启动 Blockscout (:4000)"
        echo "  explorer-down      停止 Blockscout"
        echo "  explorer-logs      Blockscout 日志"
        echo ""
        echo "链监控命令:"
        echo "  monitor-up         启动 Prometheus(:9090) + Grafana(:3030) + AlertManager(:9093)"
        echo "  monitor-down       停止监控"
        echo "  monitor-logs       监控日志"
        echo ""
        echo "单服务命令:"
        echo "  start-svc <name>               启动指定服务"
        echo "  stop-svc <name>                停止指定服务"
        echo "  restart-svc <name>             重启指定服务"
        echo "  rebuild-svc <name>             增量编译并重启"
        echo "  rebuild-svc <name> --no-cache  全新编译并重启"
        echo ""
        echo "节点列表:"
        echo "  genex-node-1, genex-node-2, genex-node-3"
        echo "  genex-inst-1, genex-inst-2, genex-regulatory"
        echo ""
        echo "生态服务列表:"
        echo "  enterprise-api, gas-relayer, faucet, bridge-monitor, genex-archive"
        echo ""
        echo "示例:"
        echo "  $0 dev                             # 单节点开发"
        echo "  $0 up                              # 全网启动"
        echo "  $0 deploy-contracts                # 部署合约"
        echo "  $0 eco-up                          # 启动生态"
        echo "  $0 explorer-up                     # 启动浏览器"
        echo "  $0 rebuild-svc genex-node-1 --no-cache  # 全新编译 node-1"
        echo ""
        exit 1
        ;;
esac
