#!/bin/bash
# Webhook Bot间通信演示脚本
# 这个脚本演示如何启动Webhook服务器和多个Bot来实现Bot间通信

set -e

echo "🚀 启动 Telegram Bot Webhook 演示"
echo "=================================="

# 检查Python虚拟环境
if [ ! -d "venv" ]; then
    echo "❌ 未找到venv虚拟环境，请先创建虚拟环境"
    exit 1
fi

# 激活虚拟环境
source venv/bin/activate

# 检查必要的依赖
echo "📦 检查依赖..."
python -c "import fastapi, uvicorn, aiohttp" 2>/dev/null || {
    echo "❌ 缺少必要的依赖，请安装："
    echo "pip install fastapi uvicorn aiohttp"
    exit 1
}

# 创建必要的目录
mkdir -p temp/telegram/bot1
mkdir -p temp/telegram/bot2
mkdir -p logs

echo "✅ 环境检查完成"

# 函数：启动Webhook服务器
start_webhook_server() {
    echo "🌐 启动 Webhook 服务器..."
    python scripts/webhook_server.py webhook_server > logs/webhook_server.log 2>&1 &
    WEBHOOK_PID=$!
    echo "Webhook服务器PID: $WEBHOOK_PID"

    # 等待服务器启动
    echo "⏳ 等待Webhook服务器启动..."
    sleep 3

    # 检查服务器是否启动成功
    if curl -s http://localhost:8080/health > /dev/null; then
        echo "✅ Webhook服务器启动成功"
    else
        echo "❌ Webhook服务器启动失败"
        kill $WEBHOOK_PID 2>/dev/null || true
        exit 1
    fi
}

# 函数：启动Bot1
start_bot1() {
    echo "🤖 启动 Bot1..."
    python scripts/telegram_bot.py bot1_webhook_example > logs/bot1.log 2>&1 &
    BOT1_PID=$!
    echo "Bot1 PID: $BOT1_PID"
}

# 函数：启动Bot2
start_bot2() {
    echo "🤖 启动 Bot2..."
    python scripts/telegram_bot.py bot2_webhook_example > logs/bot2.log 2>&1 &
    BOT2_PID=$!
    echo "Bot2 PID: $BOT2_PID"
}

# 函数：清理进程
cleanup() {
    echo ""
    echo "🛑 停止所有服务..."

    if [ ! -z "$BOT2_PID" ]; then
        kill $BOT2_PID 2>/dev/null || true
        echo "Bot2 已停止"
    fi

    if [ ! -z "$BOT1_PID" ]; then
        kill $BOT1_PID 2>/dev/null || true
        echo "Bot1 已停止"
    fi

    if [ ! -z "$WEBHOOK_PID" ]; then
        kill $WEBHOOK_PID 2>/dev/null || true
        echo "Webhook服务器已停止"
    fi

    echo "✅ 所有服务已停止"
}

# 设置信号处理
trap cleanup EXIT INT TERM

# 主程序
main() {
    case "${1:-demo}" in
        "server-only")
            echo "📋 启动模式: 仅Webhook服务器"
            start_webhook_server
            echo "🎯 Webhook服务器运行在 http://localhost:8080"
            echo "📊 健康检查: curl http://localhost:8080/health"
            echo "按 Ctrl+C 停止服务器"
            wait $WEBHOOK_PID
            ;;
        "demo")
            echo "📋 启动模式: 完整演示 (Webhook服务器 + 2个Bot)"
            echo ""
            echo "⚠️  注意: 请确保已在配置文件中设置了有效的Telegram Bot Token"
            echo "配置文件: configs/bot1_webhook_example.toml"
            echo "配置文件: configs/bot2_webhook_example.toml"
            echo ""

            read -p "是否继续? (y/N): " -n 1 -r
            echo
            if [[ ! $REPLY =~ ^[Yy]$ ]]; then
                echo "取消启动"
                exit 0
            fi

            start_webhook_server
            sleep 2
            start_bot1
            sleep 2
            start_bot2

            echo ""
            echo "🎉 所有服务已启动！"
            echo "=================================="
            echo "🌐 Webhook服务器: http://localhost:8080"
            echo "🤖 Bot1: 监听端口 8081"
            echo "🤖 Bot2: 监听端口 8082"
            echo ""
            echo "📝 日志文件:"
            echo "  - Webhook服务器: logs/webhook_server.log"
            echo "  - Bot1: logs/bot1.log"
            echo "  - Bot2: logs/bot2.log"
            echo ""
            echo "📊 监控命令:"
            echo "  - 查看Webhook状态: curl http://localhost:8080/health"
            echo "  - 查看注册的Bot: curl -H 'Authorization: Bearer secure-webhook-token-2024' http://localhost:8080/bots"
            echo ""
            echo "🧪 测试方法:"
            echo "1. 将Bot1和Bot2添加到同一个Telegram群组"
            echo "2. 在群组中@其中一个Bot发送消息"
            echo "3. 观察另一个Bot是否能看到第一个Bot的回复消息"
            echo ""
            echo "按 Ctrl+C 停止所有服务"

            # 等待所有进程
            wait
            ;;
        "help")
            echo "用法: $0 [模式]"
            echo ""
            echo "模式:"
            echo "  demo        - 启动完整演示 (默认)"
            echo "  server-only - 仅启动Webhook服务器"
            echo "  help        - 显示此帮助信息"
            echo ""
            echo "示例:"
            echo "  $0                    # 启动完整演示"
            echo "  $0 server-only        # 仅启动Webhook服务器"
            ;;
        *)
            echo "❌ 未知模式: $1"
            echo "使用 '$0 help' 查看可用模式"
            exit 1
            ;;
    esac
}

# 执行主程序
main "$@"