#!/bin/bash
# SciLit Oncology — 一键部署脚本
# Usage: bash setup.sh [dev|prod]

set -e

MODE=${1:-dev}
PROJECT_DIR=$(cd "$(dirname "$0")/.." && pwd)

echo "========================================="
echo "  SciLit Oncology — Setup ($MODE)"
echo "========================================="

# Check dependencies
check_cmd() {
    if ! command -v "$1" &>/dev/null; then
        echo "ERROR: $1 is required but not installed."
        exit 1
    fi
}

check_cmd docker
check_cmd python3

if [ "$MODE" = "prod" ]; then
    echo ""
    echo ">>> Production deployment <<<"
    echo ""

    # Check env file
    if [ ! -f "$PROJECT_DIR/.env" ]; then
        echo "Creating .env from example..."
        cp "$PROJECT_DIR/backend/.env.example" "$PROJECT_DIR/.env"
        echo "⚠️  Please edit $PROJECT_DIR/.env with your production secrets!"
        echo "    Required: DB_PASSWORD, JWT_SECRET, S3_ACCESS_KEY, S3_SECRET_KEY"
        echo "    Optional: SMTP_HOST, SMTP_USER, SMTP_PASSWORD"
        exit 1
    fi

    echo "Starting production services..."
    docker compose -f "$PROJECT_DIR/docker-compose.prod.yml" up -d

    echo ""
    echo "Running database migrations..."
    docker compose -f "$PROJECT_DIR/docker-compose.prod.yml" exec backend alembic upgrade head

    echo ""
    echo "Loading seed data..."
    docker compose -f "$PROJECT_DIR/docker-compose.prod.yml" exec backend python scripts/seed_data.py

    echo ""
    echo "========================================="
    echo "  Production deployment complete!"
    echo "  Frontend: http://localhost"
    echo "  API Docs: http://localhost:8000/docs"
    echo ""
    echo "  Admin: admin@scilit.cn / admin123"
    echo "  Demo:  demo@test.cn / 123456"
    echo "========================================="

elif [ "$MODE" = "dev" ]; then
    echo ""
    echo ">>> Development setup <<<"
    echo ""

    # Backend
    echo "Setting up backend..."
    cd "$PROJECT_DIR/backend"
    python3 -m venv venv 2>/dev/null || true
    source venv/bin/activate 2>/dev/null || source venv/Scripts/activate 2>/dev/null || true
    pip install -e ".[dev]" 2>/dev/null || pip install fastapi uvicorn sqlalchemy aiosqlite asyncpg pydantic pydantic-settings python-jose passlib bcrypt==4.0.1 python-multipart httpx lxml structlog pyyaml email-validator

    # Initialize DB + seed data
    echo "Initializing database..."
    python scripts/seed_data.py

    echo ""
    echo "Starting backend (dev mode)..."
    uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload &
    BACKEND_PID=$!
    echo "Backend PID: $BACKEND_PID"

    # Frontend
    echo ""
    echo "Setting up frontend..."
    cd "$PROJECT_DIR/frontend"
    npm install

    echo ""
    echo "Starting frontend (dev mode)..."
    npm run dev &
    FRONTEND_PID=$!
    echo "Frontend PID: $FRONTEND_PID"

    echo ""
    echo "========================================="
    echo "  Dev environment ready!"
    echo "  Frontend: http://localhost:5173"
    echo "  Backend:  http://localhost:8000/docs"
    echo "  Admin: admin@scilit.cn / admin123"
    echo "  Demo:  demo@test.cn / 123456"
    echo ""
    echo "  Press Ctrl+C to stop both services"
    echo "========================================="

    trap "kill $BACKEND_PID $FRONTEND_PID 2>/dev/null" EXIT
    wait

elif [ "$MODE" = "import-pubmed" ]; then
    echo ">>> PubMed Baseline Import <<<"
    BASELINE_DIR="$2"
    if [ -z "$BASELINE_DIR" ]; then
        echo "Usage: bash setup.sh import-pubmed /path/to/pubmed/baseline/"
        echo ""
        echo "Download baseline from: ftp.ncbi.nlm.nih.gov/pubmed/baseline/"
        exit 1
    fi
    cd "$PROJECT_DIR/backend"
    python scripts/pubmed_baseline.py --dir "$BASELINE_DIR" --demo

else
    echo "Usage: bash setup.sh [dev|prod|import-pubmed <dir>]"
    exit 1
fi
