#!/usr/bin/env bash

set -euo pipefail

# Idempotent backend setup for Firebase Functions (Python 3.10)
# - Installs Firebase CLI if missing
# - Ensures Python 3.10 is installed (via Homebrew on macOS)
# - Creates a venv in backend/functions if missing
# - Installs Python dependencies

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
FUNCTIONS_DIR="${SCRIPT_DIR}/functions"

echo "==> Backend setup starting (directory: ${SCRIPT_DIR})"

if [ ! -d "${FUNCTIONS_DIR}" ]; then
  echo "Error: Expected functions directory at ${FUNCTIONS_DIR} not found." >&2
  exit 1
fi

# 1) Ensure Firebase CLI is installed
if command -v firebase >/dev/null 2>&1; then
  echo "==> Firebase CLI already installed: $(firebase --version)"
else
  echo "==> Installing Firebase CLI..."
  # Use the official installer script (works on macOS/Linux)
  # This script is idempotent and will update if already present.
  curl -sL https://firebase.tools | bash
  if ! command -v firebase >/dev/null 2>&1; then
    echo "Error: Firebase CLI installation failed or not on PATH." >&2
    exit 1
  fi
  echo "==> Firebase CLI installed: $(firebase --version)"
fi

# 2) Ensure Python 3.10 is available
resolve_python310() {
  if command -v python3.10 >/dev/null 2>&1; then
    command -v python3.10
    return 0
  fi

  # Common Homebrew locations (Apple Silicon and Intel)
  local candidates=(
    "/opt/homebrew/opt/python@3.10/bin/python3.10"
    "/usr/local/opt/python@3.10/bin/python3.10"
  )
  for p in "${candidates[@]}"; do
    if [ -x "$p" ]; then
      echo "$p"
      return 0
    fi
  done

  return 1
}

PY310_BIN="$(resolve_python310 || true)"

if [ -z "${PY310_BIN}" ]; then
  if [ "$(uname -s)" = "Darwin" ]; then
    echo "==> python3.10 not found. Attempting Homebrew install of python@3.10..."
    if command -v brew >/dev/null 2>&1; then
      # brew install is idempotent; it will skip if already installed
      brew list python@3.10 >/dev/null 2>&1 || brew install python@3.10
      # Try to resolve again after install
      PY310_BIN="$(resolve_python310 || true)"
      if [ -z "${PY310_BIN}" ]; then
        echo "Warning: python@3.10 installed but not linked on PATH. Trying to link..."
        brew link python@3.10 --force --overwrite >/dev/null 2>&1 || true
        PY310_BIN="$(resolve_python310 || true)"
      fi
    else
      echo "Error: Homebrew not found. Please install Homebrew from https://brew.sh and re-run." >&2
      exit 1
    fi
  else
    echo "Error: python3.10 not found. Please install Python 3.10 and re-run." >&2
    exit 1
  fi
fi

if [ -z "${PY310_BIN}" ]; then
  echo "Error: Unable to locate python3.10 even after attempted installation." >&2
  exit 1
fi

echo "==> Using Python 3.10 at: ${PY310_BIN}"

# 3) Create virtual environment if missing
cd "${FUNCTIONS_DIR}"

if [ -d "venv" ]; then
  echo "==> Virtualenv already exists at ${FUNCTIONS_DIR}/venv"
else
  echo "==> Creating virtualenv at ${FUNCTIONS_DIR}/venv"
  "${PY310_BIN}" -m venv venv
fi

# 4) Install Python dependencies
echo "==> Activating virtualenv and installing dependencies"
# shellcheck disable=SC1091
source "venv/bin/activate"

python -m pip install --upgrade pip setuptools wheel
pip install -r requirements.txt

deactivate

echo "==> Setup complete. To work on functions, run:"
echo "    cd '${FUNCTIONS_DIR}' && source venv/bin/activate"


