PYTHON ?= python3
BASE_URL ?= http://localhost:8080
CA_FILE ?=
ACTION_SCRIPT ?=
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)

.PHONY: help init-secrets check validate test test-grade4 test-s3-failure test-reconcile test-upload-load load test-persistence test-failover test-failover-target

help:
	@echo "init-secrets: create local secrets; check: offline structure; test: public smoke; test-grade4: negatives/concurrency"
	@echo "test-s3-failure: stops/restarts local S3; test-reconcile: reconciliation fault injection"
	@echo "test-upload-load: >=10 concurrent uploads; load: synthetic writes"

init-secrets:
	sh scripts/init-secrets.sh

check:
	$(PYTHON) scripts/check_contract.py

validate:
	$(PYTHON) scripts/validate_openapi.py

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

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

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

test-reconcile:
	@docker compose run --rm -T --no-deps api python tests/reconcile_integration.py

test-upload-load:
	$(PYTHON) tests/upload_load.py --base-url "$(BASE_URL)" --concurrency 10 $(if $(OUTPUT),--output "$(OUTPUT)",)

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-failover-target:
	@test -n "$(TARGET_INSTANCE_ID)" || (echo "Set TARGET_INSTANCE_ID to an observed X-Instance-Id"; exit 2)
	@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable stop-one hook"; exit 2)
	$(PYTHON) tests/replica_failover.py --target-id "$(TARGET_INSTANCE_ID)" --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS) $(if $(OUTPUT),--output "$(OUTPUT)",)
