#!/usr/bin/env bash
# Start the LED controller web server (port 80 by default).
# Avoid `pipenv run` on the hot path — it re-resolves the env every time and is slow on a Pi.
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$ROOT"
export PORT="${PORT:-80}"
export PIPENV_VENV_IN_PROJECT="${PIPENV_VENV_IN_PROJECT:-1}"

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
CACHE="$SCRIPT_DIR/.led-controller-venv"
PYTHON=""

if [ -x "$ROOT/.venv/bin/python" ]; then
  PYTHON="$ROOT/.venv/bin/python"
elif [ -f "$CACHE" ]; then
  _v="$(tr -d '\r\n' < "$CACHE")"
  if [ -n "$_v" ] && [ -x "$_v/bin/python" ]; then
    PYTHON="$_v/bin/python"
  fi
fi

if [ -z "$PYTHON" ] && command -v pipenv >/dev/null 2>&1; then
  _v="$(cd "$ROOT" && pipenv --venv 2>/dev/null || true)"
  if [ -n "${_v:-}" ] && [ -x "$_v/bin/python" ]; then
    PYTHON="$_v/bin/python"
    printf '%s\n' "$_v" > "$CACHE" || true
  fi
fi

if [ -z "$PYTHON" ]; then
  echo 'led-controller: no venv resolved; using pipenv run (slow). Run: cd '"$ROOT"' && PIPENV_VENV_IN_PROJECT=1 pipenv install --skip-lock --python "$(command -v python3)"' >&2
  exec pipenv run run
fi

cd "$ROOT/src"
exec "$PYTHON" -u main.py
