#!/usr/bin/env bash
# ----------------------------------------------------------------------------
# Hostinger / cPanel safe Python dependency installer.
#
# Hostinger's "Setup Node.js app" runs `npm install` inside a chroot where
# `pip3` is NOT on PATH, even though Python interpreters ARE installed at
# well-known absolute paths (/opt/alt/python311/bin/python3.11, etc.).
#
# This script tries every known invocation and the FIRST one that responds
# to `--version` is used to install backend/requirements.txt.
#
# Exits 0 on success, 0 (intentional!) on failure with a clear log so the
# Node deploy continues and the operator can SSH in to finish manually.
# ----------------------------------------------------------------------------
set -u
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
PYREQ="$ROOT/backend/requirements.txt"

log() { printf '\n[install-python-deps] %s\n' "$*"; }

if [ ! -f "$PYREQ" ]; then
  log "✗ requirements file missing at: $PYREQ"
  exit 0
fi

CANDIDATES=(
  "python3 -m pip"
  "python3.11 -m pip"
  "python3.10 -m pip"
  "python3.9 -m pip"
  "/opt/alt/python311/bin/python3.11 -m pip"
  "/opt/alt/python310/bin/python3.10 -m pip"
  "/opt/alt/python39/bin/python3.9 -m pip"
  "/usr/local/bin/python3 -m pip"
  "/usr/bin/python3 -m pip"
  "/home/$(whoami)/.local/bin/pip3"
  "pip3"
  "pip"
)

for cmd in "${CANDIDATES[@]}"; do
  if $cmd --version >/dev/null 2>&1; then
    log "→ using: $cmd"
    if $cmd install --user \
        --no-warn-script-location \
        --disable-pip-version-check \
        --prefer-binary \
        -r "$PYREQ"; then
      log "✓ Python deps installed."
      exit 0
    else
      log "⚠ '$cmd install' failed; trying next candidate …"
    fi
  fi
done

log "✗ No working Python/pip found on this host."
log "  SSH in once and run:"
log "      python3 -m pip install --user -r backend/requirements.txt"
log "  Continuing — Node will boot but FastAPI will be unavailable until pip install succeeds."
exit 0
