.PHONY: help requirements req clean env pip_dev dev lint fmt openapi test test_unit test_integration pip_test_integration up down shell ps logs
.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 .ruff_cache pyunit.xml .coverage coverage.xml
	find . | grep -E '__pycache__|\.pyc|\.pyo$\' | xargs rm -rf

env pip_dev: ## Install dev requirements
	uv sync --locked

dev: ## Run dev
	uv run uvicorn dmp.api.asgi:app --reload --port=8001

lint: ## Run code linters
	uv run ty check
	uv run ruff check
	uv run ruff format --check

fmt: ## Run code formatters
	uv run ruff check --fix
	uv run ruff format

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

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

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

test_unit: ## Run unit tests with coverage
	uv run pytest \
		--cov dmp tests/unit/ \
		--cov-report xml \
		--junitxml=pyunit.xml

tests/integration/env pip_test_integration: ## Prepare integration tests
	python3.11 -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

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

down: ## Shutdown docker app
	docker compose down

shell sh: ## Spawn shell inside docker
	docker compose exec ows-dmp /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
	POSTGRES_PORT=5032 SNOWFLAKE_PORT=403 docker compose run \
		--rm --build lint-and-test

ci_lint_and_test_clean: down  ## Shutdown docker linters and unit tests

sync_fivetran_tables_state:  ## Run sync fivetran tables state requests
	docker compose run --rm --build sync-fivetran-tables-state

sync_geonames_data:  ## Run sync GeoNames data
	docker compose run --rm --build sync-geonames-data
