.PHONY: help format lint fmt up down ps logs execute restart test run
.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}'

format:
	uv sync --group test
	uv run ruff check src tests *.py --fix
	uv run ruff format src tests *.py

lint: ## Run code linters
	uv sync --group test
	uv run ruff check src tests *.py --diff
	uv run ruff format src tests *.py --check --diff
	uv run mypy src/ tests/ config.py

up:  ## Start container
	docker compose up --build -d function

down: ## Shutdown docker src
	docker compose down

ps: ## List all processes
	docker compose ps

logs: ## View logs
	docker compose logs -f

execute: ## Execute function
	curl --request POST \
	  --url http://localhost:9000/2015-03-31/functions/function/invocations \
	  --header 'Content-Type: application/json' \
	  --data @tests/sample_event.json

restart:  ## Load changes
	docker compose restart function

test:  ## Lint and test
	docker compose up --build lint-and-test

run:  ## Run dev script with params (EVENT_ID=334631 TARGET_ID=1064 PERIOD_ID=322)
	uv sync --python 3.13 --group test
	@START=$$(date +%s); stdbuf -oL -eL uv run python -u dev.py \
	  --abacus_event_id=$${EVENT_ID:-334631} \
	  --target_id=$${TARGET_ID:-1064} \
	  --statement_period_id=$${PERIOD_ID:-322} 2>&1 \
	  | stdbuf -oL grep '^{.*}' \
	  | while IFS= read -r line; do \
	      NOW=$$(date +%s); \
	      REL=$$((NOW-START)); \
	      echo "$$line" | jq --color-output '.' | awk -v t=$$REL '{print "[" t "s] " $$0}' \
	      | GREP_COLOR='1;31' grep --color=always 'ERROR\|$$'; \
	  done
