#!/bin/bash

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

echo -e "${BLUE}"
echo "╔════════════════════════════════════════════════════════════╗"
echo "║              Pixel Backend 启动脚本                        ║"
echo "╚════════════════════════════════════════════════════════════╝"
echo -e "${NC}"
echo ""

# 检查是否在 backend 目录
if [[ ! -f "pyproject.toml" ]]; then
    echo -e "${RED}❌ 错误: 请在 backend 目录下运行此脚本${NC}"
    echo "   cd backend && ./start.sh"
    exit 1
fi

# 检查 uv 是否安装
if ! command -v uv &> /dev/null; then
    echo -e "${RED}❌ uv 未安装${NC}"
    echo "   请运行: pip install uv"
    exit 1
fi

# 检查虚拟环境
if [ ! -d ".venv" ]; then
    echo -e "${YELLOW}⚠️  虚拟环境不存在，正在创建...${NC}"
    uv sync
    if [ $? -ne 0 ]; then
        echo -e "${RED}❌ 虚拟环境创建失败${NC}"
        exit 1
    fi
    echo -e "${GREEN}✅ 虚拟环境创建成功${NC}"
    echo ""
fi

# 检查关键依赖
echo "🔍 检查依赖..."
MISSING_DEPS=false

if ! uv run python -c "import prometheus_client" 2>/dev/null; then
    echo -e "${RED}❌ prometheus_client 缺失${NC}"
    MISSING_DEPS=true
fi

if ! uv run python -c "import fastapi" 2>/dev/null; then
    echo -e "${RED}❌ fastapi 缺失${NC}"
    MISSING_DEPS=true
fi

if ! uv run python -c "import agentscope" 2>/dev/null; then
    echo -e "${RED}❌ agentscope 缺失${NC}"
    MISSING_DEPS=true
fi

if [ "$MISSING_DEPS" = true ]; then
    echo ""
    echo -e "${YELLOW}⚠️  检测到缺失依赖，正在同步...${NC}"
    uv sync
    if [ $? -ne 0 ]; then
        echo -e "${RED}❌ 依赖同步失败${NC}"
        echo "   请运行: ./fix_dependencies.sh"
        exit 1
    fi
    echo -e "${GREEN}✅ 依赖同步成功${NC}"
fi

echo -e "${GREEN}✅ 所有依赖已就绪${NC}"
echo ""

# 检查环境变量
if [ ! -f "src/.env" ] && [ ! -f ".env" ]; then
    echo -e "${YELLOW}⚠️  环境变量文件不存在${NC}"
    echo "   建议创建 src/.env 并配置 API 密钥"
    echo ""
fi

# 检查端口占用
if lsof -i :8000 &> /dev/null; then
    echo -e "${YELLOW}⚠️  端口 8000 已被占用${NC}"
    echo "   占用进程:"
    lsof -i :8000 | tail -n +2 | awk '{print "   PID: "$2", Command: "$1}'
    echo ""
    read -p "是否终止占用进程? (y/N): " -n 1 -r
    echo ""
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        PID=$(lsof -ti :8000)
        kill -9 $PID
        echo -e "${GREEN}✅ 已终止进程 $PID${NC}"
        echo ""
    else
        echo "   使用其他端口启动: uv run uvicorn src.main:app --reload --port 8001"
        exit 0
    fi
fi

# 启动服务
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${GREEN}🚀 启动 Pixel Backend...${NC}"
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo ""
echo "   服务地址: http://127.0.0.1:8000"
echo "   API 文档: http://127.0.0.1:8000/docs"
echo "   健康检查: http://127.0.0.1:8000/health"
echo ""
echo "   按 Ctrl+C 停止服务"
echo ""
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo ""

# 启动服务
uv run uvicorn src.main:app --reload --port 8000
