#!/usr/bin/env bash
set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$ROOT"

PYTHON="${PYTHON:-python3}"
VENV="$ROOT/.venv"
PORT="${PORT:-8000}"

echo "==> ROBO-OPS: сборка и запуск"
echo "    Каталог: $ROOT"

if ! command -v "$PYTHON" >/dev/null 2>&1; then
  if command -v python >/dev/null 2>&1; then
    PYTHON=python
  else
    echo "Ошибка: Python 3 не найден. Установите Python 3.10+"
    exit 1
  fi
fi

echo "==> Python: $($PYTHON --version)"

if [ ! -d "$VENV" ]; then
  echo "==> Создание виртуального окружения..."
  "$PYTHON" -m venv "$VENV"
fi

# shellcheck disable=SC1091
source "$VENV/bin/activate" 2>/dev/null || source "$VENV/Scripts/activate"

echo "==> Установка зависимостей..."
python -m pip install --upgrade pip -q
python -m pip install -r requirements.txt -q

mkdir -p "$ROOT/data"

export ROBO_OPS_VIA_START_SH=1
export DATABASE_PATH="${DATABASE_PATH:-$ROOT/data/robo_ops.db}"
export EXTERNAL_API_KEY="${EXTERNAL_API_KEY:-robo-ops-external-demo-key-2026}"

echo ""
echo "==> Сервер запущен: http://localhost:$PORT"
echo "    Регистрация:  http://localhost:$PORT/register"
echo "    API docs:     http://localhost:$PORT/docs"
echo "    Остановка:    Ctrl+C"
echo ""

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