.PHONY: help clean env pip_dev dev lint fmt openapi test test_unit test_integration pip_test_integration up down shell ps logs docker_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 install

dev: ## Run dev
	poetry run uvicorn location.api.main:app --reload

lint: ## Run code linters
	poetry run mypy location tests
	poetry run ruff check location tests
	poetry run ruff format location tests --check

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

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

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

test_unit: ## Run unit tests with coverage
	poetry run pytest \
		--cov location tests/unit/ \
		--cov-report xml \
		--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

binaries:  ## Download ip2location binaries
	./scripts/download-bin.sh

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-location /bin/sh

ps: ## List all processes
	docker compose ps

logs: ## View logs
	docker compose logs -f

ci_lint_and_test:  ## Run linters and unit tests inside docker
	docker compose run --rm --build lint-and-test


ci_lint_and_test_clean: down  ## Shutdown docker linters and unit tests
