#!/usr/bin/env bash
# Phase 2a+ Feature Flag Service · local dev starter
# A-owned · session_a
#
# One-shot bootstrap: creates .venv, installs requirements, verifies parity,
# then runs the FastAPI service on port 8080.
#
# Requires: python3 (>=3.11)
#
# Not for production. Dev-mode auth shim · localhost only by default.

set -euo pipefail

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

PORT="${FF_PORT:-8080}"
HOST="${FF_HOST:-127.0.0.1}"
VENV="${FF_VENV:-.venv}"

if [ ! -d "$VENV" ]; then
  echo "[ff-service] creating venv at $VENV"
  python3 -m venv "$VENV"
fi

# shellcheck disable=SC1091
source "$VENV/bin/activate"

echo "[ff-service] installing requirements"
pip install --quiet --disable-pip-version-check -r requirements.txt

echo "[ff-service] verifying parity against evaluator.js examples"
python3 verify_parity.py > /tmp/ff-parity.log || {
  echo "[ff-service] PARITY CHECK FAILED · aborting"
  tail -20 /tmp/ff-parity.log
  exit 1
}
tail -1 /tmp/ff-parity.log

echo "[ff-service] starting on http://$HOST:$PORT"
echo "[ff-service] endpoints:"
echo "  GET  http://$HOST:$PORT/api/flags/health"
echo "  GET  http://$HOST:$PORT/api/flags/eval?key=flags.registry_v1&user=U-1&tier=staff"
echo "  POST http://$HOST:$PORT/api/flags/eval/batch"
echo "  GET  http://$HOST:$PORT/api/flags/registry?summary=true"
echo

exec python3 -m uvicorn app:app --host "$HOST" --port "$PORT" --log-level info
