#!/usr/bin/env bash
# scripts/perf-check -- curl-based latency budget enforcement.
#
# Hits 3 representative endpoints on the running server and asserts each
# returns within budget. Exits non-zero if any endpoint exceeds its budget.
#
# Scope reduction: the original plan called for a Lighthouse run, but for
# a personal tool a curl-based budget is sufficient and dependency-free.
#
# Assumes the server is already running on 127.0.0.1:8000.

set -u

HOST="${PERF_HOST:-127.0.0.1:8000}"

# endpoint|budget_seconds|label
ENDPOINTS=(
  "/api/stats|1.0|stats (KPI)"
  "/api/finder/search?q=embedding&limit=20|1.0|finder (FTS)"
  "/api/clusters?limit=20|2.0|clusters (analytics)"
)

fail=0
printf '%-32s %10s %10s %s\n' "endpoint" "took_s" "budget_s" "status"
printf '%-32s %10s %10s %s\n' "--------" "------" "--------" "------"

for entry in "${ENDPOINTS[@]}"; do
  IFS='|' read -r path budget label <<<"$entry"
  url="http://${HOST}${path}"

  # %{time_total} is wall-clock seconds for the whole transfer.
  out=$(curl -s -o /dev/null -w '%{time_total} %{http_code}' --max-time 10 "$url" || echo "TIMEOUT 000")
  took=$(echo "$out" | awk '{print $1}')
  code=$(echo "$out" | awk '{print $2}')

  # awk-based comparison (POSIX shell can't do float math).
  ok=$(awk -v t="$took" -v b="$budget" 'BEGIN { print (t+0 <= b+0) ? "1" : "0" }')

  status="ok"
  if [ "$code" != "200" ]; then
    status="HTTP $code"
    fail=1
  elif [ "$ok" != "1" ]; then
    status="OVER BUDGET"
    fail=1
  fi

  printf '%-32s %10.3f %10.3f %s   (%s)\n' "$path" "$took" "$budget" "$status" "$label"
done

# Frontend load-time budget (requires Playwright)
if command -v npx &> /dev/null && [ -f "$(dirname "$0")/../frontend/tests/perf.spec.js" ]; then
  echo ""
  echo "=== Frontend Performance ==="
  cd "$(dirname "$0")/../frontend"
  BASE_URL="http://$HOST" npx playwright test tests/perf.spec.js --reporter=list || fail=1
  cd - > /dev/null
fi

if [ "$fail" -ne 0 ]; then
  echo
  echo "perf-check: FAIL"
  exit 1
fi

echo
echo "perf-check: PASS"
