#!/bin/bash
# 启动脚本 - 同时运行FastAPI应用和队列消费者

set -e

echo "========================================="
echo "Starting Qwen Agent Application"
echo "========================================="

# 创建必要的目录
mkdir -p /app/queue_data

# 等待一下确保目录创建完成
sleep 1

echo "Starting FastAPI application..."
# 在后台启动FastAPI应用
python fastapi_app.py &

echo "Starting queue consumer..."
# 在后台启动队列消费者
python task_queue/consumer.py --workers=2 --worker-type=threads &

# 捕获所有后台进程的PID
API_PID=$!
CONSUMER_PID=$!

echo "========================================="
echo "Services started successfully!"
echo "FastAPI PID: $API_PID"
echo "Queue Consumer PID: $CONSUMER_PID"
echo "========================================="

# 定义清理函数
cleanup() {
    echo "========================================="
    echo "Stopping services..."
    echo "========================================="
    
    # 停止FastAPI应用
    if [ ! -z "$API_PID" ]; then
        echo "Stopping FastAPI application (PID: $API_PID)..."
        kill $API_PID 2>/dev/null || true
    fi
    
    # 停止队列消费者
    if [ ! -z "$CONSUMER_PID" ]; then
        echo "Stopping queue consumer (PID: $CONSUMER_PID)..."
        kill $CONSUMER_PID 2>/dev/null || true
    fi
    
    # 等待进程结束
    wait $API_PID 2>/dev/null || true
    wait $CONSUMER_PID 2>/dev/null || true
    
    echo "All services stopped."
    exit 0
}

# 捕获中断信号
trap cleanup SIGINT SIGTERM

# 持续监控进程状态
while true; do
    # 检查FastAPI进程是否还在运行
    if ! kill -0 $API_PID 2>/dev/null; then
        echo "FastAPI application has stopped unexpectedly"
        cleanup
    fi
    
    # 检查队列消费者进程是否还在运行
    if ! kill -0 $CONSUMER_PID 2>/dev/null; then
        echo "Queue consumer has stopped unexpectedly"
        cleanup
    fi
    
    # 每5秒检查一次
    sleep 5
done