#!/bin/bash
# 语义分割系统 — 一键启动脚本
# 时间戳: 2026-04-29-21-51-19

set -e

PROJECT_DIR="/home/wkmgc/Desktop/Seg_Server"
CONDA_ENV="seg_server"

echo "========================================"
echo "  语义分割系统全栈启动"
echo "========================================"

# 1. 检查 PostgreSQL
echo "[1/6] 检查 PostgreSQL..."
if ! pg_isready -q; then
    echo "Wkmgc" | sudo -S systemctl start postgresql
    sleep 1
fi
pg_isready && echo "  ✓ PostgreSQL 就绪"

# 2. 检查 Redis
echo "[2/6] 检查 Redis..."
if ! redis-cli ping > /dev/null 2>&1; then
    echo "Wkmgc" | sudo -S systemctl start redis-server
    sleep 1
fi
redis-cli ping && echo "  ✓ Redis 就绪"

# 3. 检查 MinIO
echo "[3/6] 检查 MinIO..."
if ! curl -s http://localhost:9000/minio/health/live > /dev/null; then
    nohup minio server /home/wkmgc/minio_data --console-address :9001 > /tmp/minio.log 2>&1 &
    sleep 3
fi
curl -s http://localhost:9000/minio/health/live > /dev/null && echo "  ✓ MinIO 就绪 (http://localhost:9001)"

# 4. 启动 FastAPI 后端
echo "[4/6] 启动 FastAPI 后端..."
source /home/wkmgc/miniconda3/etc/profile.d/conda.sh
conda activate "$CONDA_ENV"
cd "$PROJECT_DIR/backend"
nohup uvicorn main:app --host 0.0.0.0 --port 8000 --reload > /tmp/fastapi.log 2>&1 &
sleep 2
echo "  ✓ FastAPI 已启动 (http://localhost:8000/docs)"

# 5. 启动 Celery Worker
echo "[5/6] 启动 Celery Worker..."
cd "$PROJECT_DIR/backend"
nohup celery -A celery_app:celery_app worker --loglevel=info --concurrency=1 > /tmp/celery.log 2>&1 &
sleep 2
echo "  ✓ Celery Worker 已启动"

# 6. 启动前端
echo "[6/6] 启动前端..."
cd "$PROJECT_DIR"
nohup npm start > /tmp/frontend.log 2>&1 &
sleep 2
echo "  ✓ 前端已启动 (http://localhost:3000)"

echo ""
echo "========================================"
echo "  所有服务已启动"
echo "========================================"
echo "前端:     http://localhost:3000"
echo "后端 API: http://localhost:8000/docs"
echo "MinIO:    http://localhost:9001"
echo ""
echo "日志文件:"
echo "  FastAPI:  /tmp/fastapi.log"
echo "  Celery:   /tmp/celery.log"
echo "  前端:     /tmp/frontend.log"
echo "  MinIO:    /tmp/minio.log"
echo "========================================"
