PYTHON ?= python3
BASE_URL ?= http://localhost:8080
CA_FILE ?=
ACTION_SCRIPT ?=
COMPOSE ?= docker compose --env-file .env
VUS ?= 10
DURATION ?= 60s
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)

.PHONY: help check validate test load test-persistence test-failover \
	test-concurrency test-attachments test-upload-memory test-reconcile \
	test-private-bucket test-attachment-failover test-interrupted-upload \
	app-test app-build up down wait k6

help:
	@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API"
	@echo "test-concurrency: cross-replica idempotency race"
	@echo "test-attachments: graded negative upload/access cases"
	@echo "test-persistence/test-failover: explicit operator hooks"
	@echo "test-upload-memory: >=10 concurrent uploads with sampled API memory"
	@echo "test-reconcile: stale pending, orphan object and ready-attachment safety"
	@echo "test-private-bucket: anonymous denial and scoped S3 credential"
	@echo "test-attachment-failover: upload, stop serving replica, download elsewhere"
	@echo "test-interrupted-upload: half-sent upload leaves no row/object/temp file"
	@echo "up/down/wait: compose lifecycle; app-test/app-build: Go checks"

check:
	$(PYTHON) scripts/check_contract.py

validate:
	$(PYTHON) scripts/validate_openapi.py

test:
	$(PYTHON) tests/smoke.py --base-url "$(BASE_URL)" $(TLS_ARGS)

load:
	$(PYTHON) tests/load.py --base-url "$(BASE_URL)" $(TLS_ARGS)

test-persistence:
	@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable restart hook"; exit 2)
	$(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)

test-failover:
	@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable stop-one hook"; exit 2)
	$(PYTHON) tests/resilience.py --mode failover --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)

test-concurrency:
	$(PYTHON) tests/custom/idempotency.py --base-url "$(BASE_URL)" $(TLS_ARGS)

test-attachments:
	$(PYTHON) tests/custom/attachments.py --base-url "$(BASE_URL)" $(TLS_ARGS)

test-upload-memory:
	$(PYTHON) scripts/measure-upload-memory.py

test-reconcile:
	./scripts/verify-reconcile.sh

test-private-bucket:
	./scripts/check-private-bucket.sh

test-attachment-failover:
	./scripts/verify-attachment-failover.sh

test-interrupted-upload:
	./scripts/verify-interrupted-upload.sh

app-test:
	cd app && go test ./...

app-build:
	cd app && go build ./...

up:
	$(COMPOSE) up -d --build

down:
	$(COMPOSE) down

wait:
	@echo "waiting for $(BASE_URL)/health/ready"
	@until curl -fsS "$(BASE_URL)/health/ready" >/dev/null; do sleep 1; done
	@echo "ready"

k6:
	$(COMPOSE) --profile load run --rm k6 run -e VUS=$(VUS) -e DURATION=$(DURATION) --summary-export /results/last.json /scripts/messages.js
