#!/bin/bash
# Jingrow 统一开发脚本

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

# 打印函数
info() { echo -e "${BLUE}ℹ${NC} $1"; }
success() { echo -e "${GREEN}✓${NC} $1"; }
warn() { echo -e "${YELLOW}⚠${NC} $1"; }
error() { echo -e "${RED}✗${NC} $1"; }

# 检查命令是否存在
check_cmd() {
    if ! command -v "$1" &> /dev/null; then
        error "$1 未安装"
        return 1
    fi
}

# 清理进程
cleanup() {
    info "清理现有进程..."
    pkill -f "uvicorn.*jingrow.main:app" 2>/dev/null || true
    pkill -f "concurrently" 2>/dev/null || true
    pkill -f "dramatiq.*jingrow.services.queue" 2>/dev/null || true
    pkill -f "vite" 2>/dev/null || true
    sleep 1
    
    # 强制释放端口
    if lsof -ti:9001 &> /dev/null; then
        warn "释放端口 9001..."
        lsof -ti:9001 | xargs kill -9 2>/dev/null || true
    fi
    if lsof -ti:3002 &> /dev/null; then
        warn "释放端口 3002..."
        lsof -ti:3002 | xargs kill -9 2>/dev/null || true
    fi
    success "清理完成"
}

# 检查Redis
check_redis() {
    if redis-cli ping &> /dev/null; then
        success "Redis 已运行"
        return 0
    fi
    
    warn "Redis 未运行，尝试启动..."
    if command -v redis-server &> /dev/null; then
        redis-server ./redis.conf &> /dev/null &
        sleep 2
        if redis-cli ping &> /dev/null; then
            success "Redis 启动成功"
            return 0
        fi
    fi
    
    error "Redis 未运行，请手动启动: redis-server"
    return 1
}

# 检查依赖
check_deps() {
    info "检查依赖..."
    
    check_cmd node || exit 1
    check_cmd python3 || exit 1
    
    # 检查前端依赖
    if [ ! -d "apps/jingrow/frontend/node_modules" ]; then
        warn "前端依赖未安装"
        info "安装前端依赖..."
        cd apps/jingrow/frontend && npm install && cd ../..
    fi
    
    # 检查后端依赖
    if ! python3 -c "import uvicorn" &> /dev/null; then
        warn "后端依赖未安装"
        info "安装后端依赖..."
        cd apps/jingrow && pip install -r requirements.txt && cd ../..
    fi
    
    success "依赖检查完成"
}

# 启动所有服务
start_all() {
    info "启动开发环境..."
    cleanup
    check_redis
    check_deps
    
    # 加载环境变量
    if [ -f .env ]; then
        export $(grep -v '^#' .env | xargs)
    fi
    
    info "启动所有服务..."
    # 使用延迟启动，让后端先启动3秒
    npx concurrently \
        --names "BACKEND,WORKER,FRONTEND" \
        --prefix-colors "blue,yellow,green" \
        "cd apps/jingrow && uvicorn jingrow.main:app --host 0.0.0.0 --port 9001 --reload" \
        "cd apps/jingrow && dramatiq jingrow.services.queue --processes 1 --threads 1" \
        "sleep 3 && cd apps/jingrow/frontend && npm run dev"
}

# 只启动前端
start_frontend() {
    info "启动前端..."
    cleanup
    check_deps
    cd apps/jingrow/frontend && npm run dev
}

# 只启动后端
start_backend() {
    info "启动后端..."
    cleanup
    check_redis
    check_deps
    
    if [ -f .env ]; then
        export $(grep -v '^#' .env | xargs)
    fi
    
    npx concurrently \
        --names "BACKEND,WORKER" \
        --prefix-colors "blue,yellow" \
        "cd apps/jingrow && uvicorn jingrow.main:app --host 0.0.0.0 --port 9001 --reload" \
        "cd apps/jingrow && dramatiq jingrow.services.queue --processes 1 --threads 1"
}

# 停止服务
stop_all() {
    info "停止所有服务..."
    cleanup
    success "已停止"
}

# 重启服务
restart() {
    stop_all
    sleep 2
    start_all
}

# 主函数
main() {
    case "${1:-start}" in
        start)
            start_all
            ;;
        stop)
            stop_all
            ;;
        restart)
            restart
            ;;
        frontend)
            start_frontend
            ;;
        backend)
            start_backend
            ;;
        *)
            echo "用法: ./dev.sh [start|stop|restart|frontend|backend]"
            echo ""
            echo "命令:"
            echo "  start     启动所有服务（默认）"
            echo "  stop      停止所有服务"
            echo "  restart   重启所有服务"
            echo "  frontend  只启动前端"
            echo "  backend   只启动后端"
            exit 1
            ;;
    esac
}

main "$@"

