.PHONY: help env pip_dev lint fmt lint_models fmt_models ci_lint_and_test
.DEFAULT_GOAL := help

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

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

clean: ## Clean environment
	uv run dbt clean
	rm -rf .venv .cache logs
	find . | grep -E '__pycache__|\.pyc|\.pyo$\' | xargs rm -rf

packages: ## Add additional DBT packages
	uv run dbt deps

env pip_dev: ## Install dev requirements
	uv sync

lint: ## Run sql linter
	uv run sqlfluff lint .

fmt: ## Run sql formatter
	uv run sqlfluff fix .

lint_models: $(path) ## Run sql linter for specified location
	uv run sqlfluff lint $(path)

fmt_models: $(path) ## Run sql formatter for specified location
	uv run sqlfluff fix $(path)

yml_models: $(path) ## Generate models.yml file based on the files present in the path
	SQL_FILES=$$(find $(path) -maxdepth 1 -type f -name '*.sql' | sed 's:.*/::' | sed 's/\.[^.]*$$//' | awk '{printf "\"%s\",", $$0}' | sed 's/,$$//'); \
	uv run dbt --quiet run-operation generate_model_yaml --args '{"model_names": ['$$SQL_FILES']}' > $(path)/models.yml

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

dbt_test:  ## Run only dbt test inside docker
	docker compose run --rm --build dbt-test
