#!/bin/bash
# Video Flow - 开发环境启动脚本

set -e

echo "🚀 启动 Video Flow 开发环境..."

# 检查 Redis
if ! command -v redis-cli &> /dev/null; then
    echo "⚠️  Redis 未安装，使用 Docker 启动..."
    docker run -d --name video-flow-redis -p 6379:6379 redis:7-alpine 2>/dev/null || true
fi

# 启动后端 API (后台)
echo "📡 启动 FastAPI 后端 (port 8000)..."
cd "$(dirname "$0")/.."
uvicorn api.main:app --host 0.0.0.0 --port 8000 --reload &
API_PID=$!

# 启动 Celery Worker (后台)
echo "⚙️  启动 Celery Worker..."
celery -A api.celery_app worker --loglevel=info --concurrency=2 &
WORKER_PID=$!

# 启动前端 (后台)
echo "🌐 启动 React 前端 (port 3000)..."
cd web
npm install
npm run dev &
WEB_PID=$!

# 启动 Streamlit (后台)
STREAMLIT_PORT="${STREAMLIT_PORT:-8502}"
echo "📊 启动 Streamlit 调试界面 (port ${STREAMLIT_PORT})..."
cd ..
streamlit run app.py --server.port "${STREAMLIT_PORT}" &
STREAMLIT_PID=$!

echo ""
echo "✅ 所有服务已启动！"
echo ""
echo "📌 访问地址："
echo "   - 视频编辑器: http://localhost:3000"
echo "   - API 文档:   http://localhost:8000/api/docs"
echo "   - 工作流控制台: http://localhost:${STREAMLIT_PORT}"
echo ""
echo "按 Ctrl+C 停止所有服务"

# 等待并处理退出
trap "kill $API_PID $WORKER_PID $WEB_PID $STREAMLIT_PID 2>/dev/null" EXIT
wait

