#!/usr/bin/env bash
# ============================================================
#   TA-ATS one-shot installer (AlmaLinux 9.x)
#   Creates venvs + installs ALL packages for every service
#   in one run. No need to install package-by-package.
#
#   Usage:
#     chmod +x install_linux.sh
#     ./install_linux.sh
#
#   After this finishes, use ./run_linux.sh to start everything.
# ============================================================
set -euo pipefail

BASE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
MCP="$(cd "$BASE/.." && pwd)/auth_mcp"

# Pick a Python 3.12+ interpreter (falls back to python3)
PY="$(command -v python3.12 || command -v python3)"
echo "Using Python: $PY  ($("$PY" --version))"

# Packages that only exist on Windows — must be removed on Linux
WINONLY='pywin32|pywin32-ctypes'

# Install one Python service: make venv, strip win-only lines, pip install
install_py () {
  local name="$1" dir="$2" req="$3"
  echo
  echo "=========================================="
  echo "  [$name]  $dir"
  echo "=========================================="
  if [ ! -d "$dir" ]; then
    echo "  !! folder not found, skipping: $dir"
    return
  fi
  cd "$dir"
  "$PY" -m venv venv
  ./venv/bin/python -m pip install --upgrade pip setuptools wheel
  if [ -f "$req" ]; then
    # strip Windows-only deps so pip doesn't fail on Linux
    grep -viE "^($WINONLY)==" "$req" > /tmp/req.$name.txt || true
    ./venv/bin/pip install -r /tmp/req.$name.txt
    rm -f /tmp/req.$name.txt
  else
    echo "  !! requirements file not found: $req"
  fi
}

# --- 1) MCP service ----------------------------------------
install_py mcp     "$MCP"          "$MCP/requirements.txt"

# --- 2) Backend (Django) -----------------------------------
install_py backend "$BASE/backend" "$BASE/backend/requirements/base.txt"

# --- 3) Gateway (FastAPI) ----------------------------------
install_py gateway "$BASE/gateway" "$BASE/gateway/requirements.txt"

# --- 4) Frontend (Next.js) ---------------------------------
echo
echo "=========================================="
echo "  [frontend]  $BASE/frontend"
echo "=========================================="
cd "$BASE/frontend"
npm install

echo
echo "============================================"
echo "  All packages installed."
echo "  Next steps:"
echo "    1) Create the .env files for each service"
echo "    2) cd backend && ./venv/bin/python manage.py migrate"
echo "    3) ./run_linux.sh   (to start all services)"
echo "============================================"
