#!/bin/bash

# YG-Datasets 一键启动脚本

echo "========================================="
echo "  YG-Datasets 一键启动"
echo "========================================="

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

# 检查并创建必要目录
echo -e "${YELLOW}[1/5] 检查环境...${NC}"
mkdir -p backend/uploads
mkdir -p frontend

# 创建并激活 Python 虚拟环境
echo -e "${YELLOW}[2/5] 创建 Python 虚拟环境...${NC}"
cd backend
if [ ! -d "venv" ]; then
    python3 -m venv venv
fi
source venv/bin/activate

# 安装后端依赖
echo -e "${YELLOW}[3/5] 安装后端依赖...${NC}"
pip install -r requirements.txt

# 安装前端依赖
echo -e "${YELLOW}[4/5] 安装前端依赖...${NC}"
cd ../frontend
if [ ! -d "node_modules" ]; then
    npm install
fi

# 启动后端
echo -e "${YELLOW}[5/5] 启动服务...${NC}"
cd ../backend
echo -e "${GREEN}启动后端 (端口 8000)...${NC}"
export HOST="0.0.0.0"
export DATABASE_URL="sqlite+aiosqlite:///./ygdataset.db"
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000 &
BACKEND_PID=$!

# 等待后端启动
sleep 3

# 启动前端
cd ../frontend
echo -e "${GREEN}启动前端 (端口 3000)...${NC}"
npm run dev -- --host 0.0.0.0 &
FRONTEND_PID=$!

echo ""
echo "========================================="
echo -e "  ${GREEN}启动完成!${NC}"
echo "========================================="
echo "  后端: http://localhost:8000"
echo "  API文档: http://localhost:8000/docs"
echo "  前端: http://localhost:3000"
echo ""
echo "  按 Ctrl+C 停止所有服务"
echo "========================================="

# 捕获 Ctrl+C 并停止所有服务
trap "kill $BACKEND_PID $FRONTEND_PID 2>/dev/null; exit" INT TERM

# 等待
wait
