#!/bin/bash

# Gitea Webhook Ambassador 启动脚本

set -e

# 检查虚拟环境
if [ ! -d "venv" ]; then
    echo "❌ 虚拟环境不存在，请先运行 ./scripts/setup.sh"
    exit 1
fi

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

# 检查环境文件
if [ ! -f ".env" ]; then
    echo "❌ .env 文件不存在，请先运行 ./scripts/setup.sh"
    exit 1
fi

# 检查 Redis 是否运行
if ! docker ps | grep -q redis; then
    echo "🐳 启动 Redis..."
    docker run -d --name webhook-redis -p 6379:6379 redis:alpine
    sleep 3
fi

echo "🚀 启动 Gitea Webhook Ambassador..."

# 启动 API 服务
echo "🌐 启动 API 服务..."
python -m uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload &
API_PID=$!

# 等待 API 服务启动
sleep 5

# 启动 Celery worker
echo "⚙️ 启动 Celery worker..."
celery -A app.tasks.jenkins_tasks worker --loglevel=info --concurrency=4 &
WORKER_PID=$!

# 启动 Celery beat (定时任务)
echo "⏰ 启动定时任务调度器..."
celery -A app.tasks.jenkins_tasks beat --loglevel=info &
BEAT_PID=$!

echo "✅ 所有服务已启动！"
echo ""
echo "📊 服务状态："
echo "- API 服务: http://localhost:8000 (PID: $API_PID)"
echo "- 健康检查: http://localhost:8000/health"
echo "- 监控指标: http://localhost:8000/metrics"
echo "- Celery Worker: PID $WORKER_PID"
echo "- Celery Beat: PID $BEAT_PID"
echo ""
echo "🛑 按 Ctrl+C 停止所有服务"

# 等待中断信号
trap 'echo "🛑 正在停止服务..."; kill $API_PID $WORKER_PID $BEAT_PID 2>/dev/null; exit 0' INT

# 等待所有后台进程
wait 