#!/usr/bin/env bash
# Pull the published backend image and run it (+ a throwaway DB) for the frontend's
# integration tests, or for local dev. The frontend's api_client then makes real HTTP
# to it instead of importing backend source.
#
#   scripts/backend-for-tests.sh up     # pull + start, wait until healthy, print base URL
#   scripts/backend-for-tests.sh down   # stop + remove (incl. the throwaway db volume)
#   scripts/backend-for-tests.sh url    # print the base URL (no lifecycle change)
#
# Which backend build: THERMOGRAPH_BACKEND_TEST_TAG. Unset, it is DERIVED from this
# checkout (see below) rather than defaulted to a hardcoded tag -- set a sha-<12hex>
# to pin one. Host port: BACKEND_TEST_HOST_PORT (default 18137).
set -euo pipefail
cd "$(dirname "$0")/.."

export POSTGRES_PASSWORD="${POSTGRES_PASSWORD:-testing}"
export BACKEND_TEST_HOST_PORT="${BACKEND_TEST_HOST_PORT:-18137}"
BASE_URL="http://127.0.0.1:${BACKEND_TEST_HOST_PORT}"
COMPOSE=(docker compose -f docker-compose.test.yml)

# Derive the backend image tag the SAME way build-push.yml and deploy.yml do:
# keyed to the last commit that touched backend/, not the branch tip. That is the
# image actually published for this checkout's backend tree, so the harness follows
# the tree instead of drifting behind a pin (this file previously defaulted to the
# split-era v0.0.2-split-ci tag under a retired image path).
#
# Exported before ANY compose call -- docker-compose.test.yml requires the variable
# (`:?`), so `down` and `url` need it set too, not just `up`.
#
# `:/backend/` is a repo-ROOT-relative pathspec: a bare `backend/` would resolve
# against this script's cwd (frontend/) and silently match nothing, yielding an
# empty sha and a confusing error instead of the right tag.
if [ -z "${THERMOGRAPH_BACKEND_TEST_TAG:-}" ]; then
  domain_sha="$(git log -1 --format=%H -- ':/backend/' 2>/dev/null || true)"
  if [ -z "$domain_sha" ]; then
    echo "!! could not derive a backend image tag from git (no backend/ history here?)." >&2
    echo "   Set THERMOGRAPH_BACKEND_TEST_TAG=sha-<12hex> explicitly." >&2
    exit 2
  fi
  THERMOGRAPH_BACKEND_TEST_TAG="sha-${domain_sha:0:12}"
fi
export THERMOGRAPH_BACKEND_TEST_TAG

case "${1:-up}" in
  up)
    echo "==> pulling backend image (${THERMOGRAPH_BACKEND_TEST_TAG})" >&2
    if ! "${COMPOSE[@]}" pull backend >&2; then
      echo "!! no published backend image for ${THERMOGRAPH_BACKEND_TEST_TAG}." >&2
      echo "   That tag is keyed to the last commit touching backend/ -- if those" >&2
      echo "   commits are local-only, build-push.yml has not published it yet." >&2
      echo "   Pin a published build: THERMOGRAPH_BACKEND_TEST_TAG=sha-<12hex> $0 up" >&2
      exit 1
    fi
    echo "==> starting backend + db" >&2
    "${COMPOSE[@]}" up -d >&2
    echo "==> waiting for backend /healthz (up to 90s)" >&2
    for _ in $(seq 1 45); do
      curl -fsS -o /dev/null "$BASE_URL/healthz" 2>/dev/null && { echo "$BASE_URL"; exit 0; }
      sleep 2
    done
    echo "!! backend never became healthy" >&2
    "${COMPOSE[@]}" logs --tail=40 backend >&2
    exit 1
    ;;
  down)
    "${COMPOSE[@]}" down -v --remove-orphans >/dev/null 2>&1 || true
    echo "==> backend stopped" >&2
    ;;
  url)
    echo "$BASE_URL"
    ;;
  *)
    echo "usage: $0 {up|down|url}" >&2; exit 2 ;;
esac
