#!/usr/bin/env bash
set -euo pipefail
show_help() {
  cat <<'HELP'
Usage: bin/reference [setup|test|serve|coverage]

Run the original Django reference for behavior comparisons.

Commands:
  setup       Install locked Python dependencies, create/migrate/claim the test
              database, and REPLACE its application data with the small fixture.
  test        Run the original pytest smoke tests.
  serve       Start Gunicorn (default command).
  coverage    Start the Django server with Python coverage enabled.

Requires Python 3.14, uv, PostgreSQL, and the built harness/harness binary.
Run bin/build first. Run setup before test, serve, or coverage.

Environment:
  PGDATABASE    Default: assignment_harness_django; must use assignment_harness_.
  PGHOST, PGPORT, PGUSER, PGPASSWORD    PostgreSQL connection settings.
  LISTEN_ADDR   Default: 127.0.0.1:18000.
  TMPDIR        Default: ~/codex-tmp.

Stop servers with Ctrl+C. Writes PID/coverage artifacts locally.
Examples:
  bin/reference setup
  bin/reference serve
  bin/reference test

Options:
  -h, --help    Show this help without performing work.
HELP
}
case "${1:-serve}" in
  -h|--help|help) show_help; exit 0 ;;
  setup|test|serve|coverage)
    if [[ "${2:-}" == --help || "${2:-}" == -h ]]; then show_help; exit 0; fi
    if (( $# > 1 )); then printf 'Unexpected argument; use bin/reference --help\n' >&2; exit 2; fi
    ;;
  *) printf 'Unknown command; use bin/reference --help\n' >&2; exit 2 ;;
esac
project_root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)
cd "$project_root"
export PGDATABASE="${PGDATABASE:-assignment_harness_django}"
export DJANGO_SETTINGS_MODULE=adapters.settings
export TMPDIR="${TMPDIR:-$HOME/codex-tmp}"
mkdir -p -- "$TMPDIR" .artifacts
case "${1:-serve}" in
  setup)
    uv sync --python 3.14 --group harness --locked
    # libpq environment handles host, port, role and credentials. No hardcoded password.
    harness/harness init-db --db "dbname=$PGDATABASE"
    .venv/bin/python manage.py migrate --noinput
    harness/harness claim --db "dbname=$PGDATABASE"
    harness/harness fixture --db "dbname=$PGDATABASE"
    ;;
  test) exec .venv/bin/pytest -q ;;
  serve)
    exec .venv/bin/gunicorn core.wsgi:application --bind "${LISTEN_ADDR:-127.0.0.1:18000}" \
      --workers 2 --threads 4 --timeout 180 --worker-tmp-dir "$TMPDIR" \
      --pid .artifacts/django.pid
    ;;
  coverage)
    exec .venv/bin/python -m coverage run --branch --source=blog manage.py runserver \
      "${LISTEN_ADDR:-127.0.0.1:18000}" --noreload
    ;;
  *) printf 'usage: bin/reference setup|test|serve|coverage\n' >&2; exit 2 ;;
esac
