#!/bin/bash
# 启动回测API服务脚本

echo "🚀 启动回测API服务..."

# 1. 首先检查容器是否运行
echo "1. 检查Docker容器状态..."
ssh admin@192.168.2.154 "export PATH=\$PATH:/var/packages/Docker/target/usr/bin && docker ps | grep sanguo_vnpy"

if [ $? -ne 0 ]; then
    echo "❌ 容器未运行，请先启动容器"
    exit 1
fi

echo "✅ 容器正在运行"

# 2. 检查服务是否已经在运行
echo -e "\n2. 检查服务是否已在运行..."

# 尝试连接ZMQ端口
timeout 5 bash -c "echo >/dev/tcp/192.168.2.154/2014" 2>/dev/null
if [ $? -eq 0 ]; then
    echo "✅ ZMQ RPC服务 (端口2014) 已在运行"
    ZMQ_RUNNING=true
else
    echo "❌ ZMQ RPC服务未运行"
    ZMQ_RUNNING=false
fi

# 尝试连接HTTP API端口
curl -s http://192.168.2.154:8088/docs > /dev/null 2>&1
if [ $? -eq 0 ]; then
    echo "✅ HTTP API服务 (端口8088) 已在运行"
    API_RUNNING=true
else
    echo "❌ HTTP API服务未运行"
    API_RUNNING=false
fi

# 3. 启动缺失的服务
echo -e "\n3. 启动缺失的服务..."

if [ "$ZMQ_RUNNING" = false ]; then
    echo "启动ZMQ RPC服务 (test_server.py)..."
    ssh admin@192.168.2.154 "export PATH=\$PATH:/var/packages/Docker/target/usr/bin && docker exec -d sanguo_vnpy python3 /app/scripts/test_server.py"
    sleep 3
    
    # 验证启动
    timeout 5 bash -c "echo >/dev/tcp/192.168.2.154/2014" 2>/dev/null
    if [ $? -eq 0 ]; then
        echo "✅ ZMQ RPC服务启动成功"
    else
        echo "❌ ZMQ RPC服务启动失败"
    fi
fi

if [ "$API_RUNNING" = false ]; then
    echo "启动HTTP API服务 (backtest_api.py)..."
    ssh admin@192.168.2.154 "export PATH=\$PATH:/var/packages/Docker/target/usr/bin && docker exec -d sanguo_vnpy python3 /app/scripts/backtest_api.py"
    sleep 3
    
    # 验证启动
    curl -s http://192.168.2.154:8088/docs > /dev/null 2>&1
    if [ $? -eq 0 ]; then
        echo "✅ HTTP API服务启动成功"
    else
        echo "❌ HTTP API服务启动失败"
    fi
fi

# 4. 最终状态检查
echo -e "\n4. 最终服务状态检查..."

echo -n "ZMQ RPC服务 (端口2014): "
timeout 3 bash -c "echo >/dev/tcp/192.168.2.154/2014" 2>/dev/null
if [ $? -eq 0 ]; then
    echo "✅ 运行正常"
else
    echo "❌ 未运行"
fi

echo -n "HTTP API服务 (端口8088): "
curl -s -I http://192.168.2.154:8088/docs 2>/dev/null | grep -q "200 OK"
if [ $? -eq 0 ]; then
    echo "✅ 运行正常"
    echo "   Swagger UI: http://192.168.2.154:8088/docs"
else
    echo "❌ 未运行"
fi

# 5. 测试回测功能
echo -e "\n5. 测试回测功能..."
if [ "$ZMQ_RUNNING" = true ] && [ "$API_RUNNING" = true ]; then
    echo "运行简单回测测试..."
    python3 test_api_timeout_simple.py
else
    echo "跳过回测测试（服务未完全启动）"
fi

echo -e "\n🎯 启动完成！"
echo "请通知各位将军可以开始测试回测API了。"