#!/bin/bash

#!/bin/bash

# 宇之然内容创作平台 - 直接运行脚本
# 用法: cd /path/to/platform && ./run.sh [port]

set -e

PORT=${1:-8001}
PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BACKEND_DIR="$PROJECT_ROOT/backend"
FRONTEND_DIR="$PROJECT_ROOT/frontend"
DATA_DIR="$PROJECT_ROOT/data"
LOGS_DIR="$PROJECT_ROOT/logs"
CHECK_SCRIPT="$PROJECT_ROOT/check.py"

# 运行部署前检查（可选）
if [ -f "$CHECK_SCRIPT" ]; then
    echo "【0/4】运行部署前检查..."
    YZR_PORT=$PORT python3 "$CHECK_SCRIPT" "$PORT"
    echo
fi


# 检查数据目录
if [ ! -d "$DATA_DIR" ]; then
    echo "创建数据目录: $DATA_DIR"
    mkdir -p "$DATA_DIR"
fi

# 检查日志目录
if [ ! -d "$LOGS_DIR" ]; then
    echo "创建日志目录: $LOGS_DIR"
    mkdir -p "$LOGS_DIR"
fi

# 检查前端文件
if [ ! -f "$FRONTEND_DIR/index.html" ]; then
    echo "⚠️  警告: 前端 index.html 不存在"
    echo "前端目录: $FRONTEND_DIR"
    echo "请确保前端文件已就绪"
fi

# 检查Python依赖
echo "检查Python依赖..."
cd "$BACKEND_DIR"
if [ ! -d "venv" ]; then
    echo "创建虚拟环境..."
    python3 -m venv venv
fi

source venv/bin/activate || echo "使用系统Python（未激活venv）"
pip install -q -r requirements.txt

# 启动服务
echo ""
echo "🚀 启动服务器..."
echo "API文档: http://localhost:$PORT/docs"
echo "前端界面: http://localhost:$PORT/"
echo "========================================"

cd "$BACKEND_DIR"
exec python -m uvicorn app.main:app --host 0.0.0.0 --port $PORT --reload
