#!/bin/bash
set -e

echo "=========================================="
echo "  Jarvis 个人 AI 助理 - 一键启动"
echo "=========================================="
echo ""

# 检查 uv
if ! command -v uv &> /dev/null; then
    echo "[错误] 未找到 uv，请先安装: https://github.com/astral-sh/uv"
    echo "安装命令: pip install uv"
    exit 1
fi

# 检查 npm
if ! command -v npm &> /dev/null; then
    echo "[错误] 未找到 npm，请先安装 Node.js: https://nodejs.org"
    exit 1
fi

# 检查 .env
if [ ! -f backend/.env ]; then
    echo "[提示] 首次运行，请编辑 backend/.env 文件"
    echo "  填入: ANTHROPIC_API_KEY=sk-ant-xxxxxxxxxxxxxxxxxxxx"
    echo ""
fi

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"

# 安装后端依赖
echo "[1/4] 安装后端依赖..."
cd "$SCRIPT_DIR/backend"
uv sync --quiet
echo "[OK] 后端依赖安装完成"

# 安装前端依赖
echo ""
echo "[2/4] 安装前端依赖..."
cd "$SCRIPT_DIR/frontend"
npm install --silent
echo "[OK] 前端依赖安装完成"

# 启动后端
echo ""
echo "[3/4] 启动后端服务 (端口 8000)..."
cd "$SCRIPT_DIR/backend"
uv run uvicorn app.main:app --reload --port 8000 &
BACKEND_PID=$!

# 等待后端
echo "      等待后端启动..."
sleep 5

# 启动前端
echo ""
echo "[4/4] 启动前端服务 (端口 5173)..."
cd "$SCRIPT_DIR/frontend"
npm run dev &
FRONTEND_PID=$!

echo ""
echo "=========================================="
echo "  启动完成!"
echo ""
echo "  后端: http://localhost:8000"
echo "  前端: http://localhost:5173"
echo "  API文档: http://localhost:8000/docs"
echo "=========================================="
echo ""
echo "提示:"
echo "  - 首次使用请先注册账号"
echo "  - 对话前请在 backend/.env 填入 API Key"
echo "  - 关闭时请按 Ctrl+C"
echo ""

# 等待信号
trap "kill $BACKEND_PID $FRONTEND_PID 2>/dev/null; exit" SIGINT SIGTERM
wait
