.PHONY: help clean dev worker worker_fan_fanout worker_fan_collect_spotify_smf worker_fan_collect_spotify_songwhip flower lint fmt test test_unit up down shell sh ps logs install
.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
	rm -rf .venv .cache .pytest_cache .ruff_cache pyunit.xml .coverage coverage.xml
	find . | grep -E '__pycache__|\.pyc|\.pyo$\' | xargs rm -rf

dev: ## Run dev
	uv run uvicorn app.api.main:app --reload --port=8000

worker: ## Run all workers (fanout + all per-client fan_collect)
	$(MAKE) worker_fan_fanout &
	$(MAKE) worker_fan_collect_spotify_smf &
	$(MAKE) worker_fan_collect_spotify_songwhip &
	wait

worker_fan_fanout: ## Run fan_fanout worker (reads fans, dispatches batches)
	uv run celery -A app worker --pool=threads --concurrency=1 -Q resonance.fan_fanout -l info -n fanout@%h

worker_fan_collect_spotify_smf: ## Run fan_collect worker for spotify_smf
	uv run celery -A app worker --pool=threads --concurrency=15 -Q resonance.fan_collect.spotify_smf -l info -n smf@%h

worker_fan_collect_spotify_songwhip: ## Run fan_collect worker for spotify_songwhip
	uv run celery -A app worker --pool=threads --concurrency=3 -Q resonance.fan_collect.spotify_songwhip -l info -n songwhip@%h

flower: ## Run Flower — Celery monitoring UI (http://localhost:5555)
	uv run celery -A app --broker=$(shell grep REDIS_URL .env | cut -d= -f2) flower --port=5555

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

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

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

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

ps: ## List all processes
	docker compose ps

logs: ## View logs
	docker compose logs -f
