# Dev/test helpers. The Postgres stack exists only so the test suite can run
# against a real server; see CONTRIBUTING.md.

COMPOSE ?= docker compose
PYTEST ?= uv run --no-sync pytest
PYTEST_ARGS ?= -q --no-cov

# FFB_TEST_DATABASE_URL and friends come from .env when it exists. A value
# already in the environment (CI points it at a service container) wins.
ENV_TEST_DATABASE_URL := $(FFB_TEST_DATABASE_URL)
-include .env
ifneq ($(ENV_TEST_DATABASE_URL),)
FFB_TEST_DATABASE_URL := $(ENV_TEST_DATABASE_URL)
endif

.PHONY: help pg-up pg-down pg-logs pg-psql pg-reset test test-pg test-all lint

help:
	@echo "pg-up     start Postgres + pgvector and wait until healthy"
	@echo "pg-down   stop it (the data volume is kept)"
	@echo "pg-reset  stop it and delete the data volume"
	@echo "pg-logs   follow its logs"
	@echo "pg-psql   psql into the test database"
	@echo "test      test suite on SQLite only (Postgres cases skip)"
	@echo "test-pg   test suite with the Postgres cases enabled (needs pg-up)"
	@echo "test-all  both"
	@echo "lint      ruff"

# First run: copy the example and give it a random password.
.env:
	@pw=$$(openssl rand -hex 16); sed "s/change-me/$$pw/g" .env.example > .env
	@echo "wrote .env from .env.example"

pg-up: .env
	$(COMPOSE) up -d --wait ffb-postgres
	$(COMPOSE) logs --tail=20 ffb-postgres

pg-down:
	$(COMPOSE) down

pg-reset:
	$(COMPOSE) down -v

pg-logs:
	$(COMPOSE) logs -f ffb-postgres

pg-psql:
	$(COMPOSE) exec ffb-postgres psql -U "$(FFB_PG_USER)" -d "$(FFB_PG_DB)"

test:
	env -u FFB_TEST_DATABASE_URL $(PYTEST) $(PYTEST_ARGS)

test-pg: .env
	@test -n "$(FFB_TEST_DATABASE_URL)" || { echo "FFB_TEST_DATABASE_URL is not set (environment or .env)"; exit 1; }
	@echo "$(PYTEST) $(PYTEST_ARGS)  (Postgres cases enabled)"
	@FFB_TEST_DATABASE_URL="$(FFB_TEST_DATABASE_URL)" $(PYTEST) $(PYTEST_ARGS)

test-all: test test-pg

lint:
	uv run --no-sync ruff check src/ examples/ tests/_compat.py tests/_databases.py \
		tests/unit/test_test_databases.py tests/unit/test_instrumentation.py \
		tests/unit/test_embeddings.py tests/unit/test_backfill.py
