.PHONY: help clean test_unit test_cov fmt lint pip_dev ci_test_unit_lint ci_clean_unit_lint ci_test_integration ci_clean_integration
.DEFAULT_GOAL := help

help:
	@fgrep -h "##" $(MAKEFILE_LIST) | fgrep -v fgrep | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}'

clean:  ## Clean environment
	rm -rf env .cache .pytest_cache .mypy_cache .ruff_cache pyunit.xml .coverage coverage.xml
	find . | grep -E '__pycache__|\.pyc|\.pyo$\' | xargs rm -rf

env pip_dev:  ## Prepare environment
	poetry install

fmt:  pip_dev  ## Run code formatters
	poetry run ruff check backfill tests --fix
	poetry run ruff format backfill tests

lint:  pip_dev  ## Lint
	poetry run ruff check backfill tests
	poetry run ruff format backfill tests --check
	poetry run mypy backfill tests
	poetry run pdpbackfill lint manifest --manifest-file-path=pdp_qa_refresh/manifest.json --check-keys-exist-locally

test_unit: env  ## Run unit tests
	poetry run py.test \
		--cov backfill tests/unit/ \
		--cov-report xml:coverage.xml \
		--cov-report html \
		--junitxml=pyunit.xml

test_integration: pip_dev
	poetry run pytest tests/integration/ \
		--cov backfill \
		--cov-report xml \
		--cov-report term \
		--junitxml=pyunit.xml

ci_test_unit_lint: ci_clean_unit_lint
	mkdir -p build
	chmod a+w build
	make docker_unit_lint

down_integration:
	docker compose down integration --remove-orphans

down_unit_lint:
	docker compose down unit-lint --remove-orphans

ci_clean_unit_lint: down_unit_lint
	rm -rf build

ci_test_integration: ci_clean_integration
	mkdir -p build
	chmod a+w build
	make docker_test_integration

ci_clean_integration: down_integration
	rm -rf build

docker_unit_lint:
	docker compose up \
		--build \
		--exit-code-from unit-lint \
		--abort-on-container-exit \
		--remove-orphans \
		unit-lint

docker_test_integration:
	docker compose up \
		--build \
		--exit-code-from integration \
		--abort-on-container-exit \
		--remove-orphans \
		integration

clean_wip_pdp:
	rm -rf wip_pdp

generate_models: clean_wip_pdp
	# Use Docker to generate models to WIP directory
	docker run --rm \
	-v ${PWD}:/local \
	-v ${PWD}/.openapi-generator-ignore:/local/wip_pdp/.openapi-generator-ignore \
	openapitools/openapi-generator-cli:v7.12.0 generate \
	--additional-properties=packageName=backfill.connectors.ows_pdp \
	-i https://qa-ows-pdp.theorchard.io/openapi.json \
	-g python \
	-o /local/wip_pdp

	# Move models from WIP directory to backfill package
	cp -r wip_pdp/.openapi-generator backfill/connectors/
	cp -r wip_pdp/backfill/connectors/ows_pdp/models backfill/connectors/ows_pdp/

	# Pre-emptively run formatter
	make fmt
