.PHONY: help clean env pip_dev dev lint fmt openapi openapi-check test test_unit test_integration pip_test_integration up down shell ps logs ci_lint_and_test
.DEFAULT_GOAL := help

# define root project dir
ROOT_DIR:=$(shell dirname $(realpath $(firstword $(MAKEFILE_LIST))))

export APP_RUN_FROM_CLI = 1

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 .venv .cache .pytest_cache .mypy_cache .ruff_cache .coverage coverage.xml
	find . | grep -E '__pycache__|\.pyc|\.pyo$\' | xargs rm -rf

env pip_dev: ## Install dev requirements
	poetry env use python3.11
	poetry install

dev: ## Run dev
	poetry run python dev.py

lint: ## Run code linters
	poetry run black campaigns/ tests/ dev.py --check
	poetry run ruff check campaigns/ tests/ dev.py
	poetry run mypy campaigns/ tests/ dev.py

fmt: ## Run code formatters
	poetry run black campaigns/ tests/ dev.py
	poetry run ruff check campaigns/ tests/ dev.py --fix

openapi: ## Generate OpenAPI specification
	poetry run python manage.py api gen-spec

openapi-check: ## Check OpenAPI specification
	poetry run python manage.py api check-spec

test: ## Run unit tests
	poetry run pytest tests/unit/

test_unit: ## Run unit tests with coverage
	poetry run pytest -vv tests/unit/ \
		--cov campaigns/ \
		--cov-report xml \
		--cov-report term \
		--junitxml=pyunit.xml

tests/integration/env pip_test_integration: ## Prepare integration tests
	python3.8 -m venv tests/integration/.venv
	tests/integration/.venv/bin/pip install --upgrade pip
	tests/integration/.venv/bin/pip install -r tests/integration/requirements.txt

test_integration: tests/integration/env  ## Run integration tests
	tests/integration/.venv/bin/python -m pytest tests/integration/ --confcutdir=tests/integration/

test_integration_clean:  ## Clean integration tests
	rm -rf tests/integration/.venv

update_test_client:  ## Generate tests client
	cd tests/integration/ && poetry -C ../../ run openapi-python-client update --url=http://127.0.0.1:8000/openapi.json --meta=none --config=openapigen.yml --custom-template-path=templates

up: ## Compose docker app
	@docker-compose up -d --build --remove-orphans

down: ## Shutdown docker app
	@docker-compose down

shell sh: ## Spawn shell inside docker
	@docker-compose exec ows-campaigns /bin/sh

ps: ## List all processes
	@docker-compose ps

logs: ## View logs
	@docker-compose logs -f

ci_lint_and_test: clean  ## Run linters and unit tests inside docker
	POSTGRES_PORT=5039 docker-compose up \
		--exit-code-from lint-and-test \
		--abort-on-container-exit \
		--build \
		--remove-orphans \
		lint-and-test

ci_lint_and_test_clean: down  ## Shutdown docker linters and unit tests
