.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
.PHONY: docker_unit_lint docker_test_integration down_unit_lint down_integration docker_m2m_lint docker_sync
.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

test_unit: pip_dev  ## Run unit tests
	poetry run pytest tests/unit/ \
		--cov m2mconfig \
		--cov-report xml \
		--cov-report term \
		--junitxml=pyunit.xml

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

test_cov: pip_dev  ## Run unit and integration tests with coverage
	poetry run pytest tests/ \
		--cov m2mconfig \
		--cov-report term-missing

lint: pip_dev  ## Run code linters
	poetry run mypy m2mconfig tests
	poetry run ruff m2mconfig tests scripts
	poetry run ruff format m2mconfig tests scripts --check

fmt:  pip_dev ## Run code formatters
	poetry run ruff m2mconfig tests scripts --fix
	poetry run ruff format m2mconfig tests scripts

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

down_integration:
	docker compose down integration --remove-orphans

down_unit_lint:
	docker compose down unit-lint --remove-orphans
	docker compose down m2m-json-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

up_greetings:
	docker compose up \
		--build \
		--abort-on-container-exit \
		--remove-orphans \
		greetings

docker_m2m_lint:
	docker compose up \
		--build \
		--abort-on-container-exit \
		--remove-orphans \
		m2m-json-lint

docker_sync:
	docker compose \
		-f docker-compose-deploy.yml \
		run m2mconfig sync $(ALL_OR_ONE) \
		$(ENV) $(ENTRY) \
		$(DRY_RUN) $(OVERWRITE_SECRET)
