PROJECT_NAME := contracts
DOCKER_COMPOSE := docker compose --project-name $(PROJECT_NAME)

.PHONY: clean clean_all env env_dev env_integration \
	lint lint_fix format format_fix test test_integration run \
	docker_test docker_test_up docker_test_down \
	docker_test_integration docker_test_integration_up docker_test_integration_down \
	docker_down

clean:
	@echo "Cleaning up..."
	@find . -type d -name "__pycache__" -exec rm -rf {} + 2>/dev/null || true
	@find . -type d -name ".pytest_cache" -exec rm -rf {} + 2>/dev/null || true
	@find . -type d -name ".ruff_cache" -exec rm -rf {} + 2>/dev/null || true
	@find . -type f -name "*.pyc" -delete 2>/dev/null || true
	@find . -type f -name "*.pyo" -delete 2>/dev/null || true
	@rm -rf -- build dist *.egg-info .cache .coverage coverage.xml
	@echo "Done!"

clean_all: clean
	@echo "Removing virtual environment..."
	@rm -rf .venv
	@echo "Done!"

env: ## Install default dependencies
	@uv sync --frozen

env_dev: ## Install default and dev dependencies
	@uv sync --group dev --frozen

env_integration: ## Install default, dev, and integration dependencies
	@uv sync --group integration --frozen

format: env_dev ## Run the formatter to check
	@echo "Checking formatting..."
	@uv run --no-sync -- ruff format --check --diff

format_fix: env_dev ## Run the formatter to fix
	@echo "Fixing formatting..."
	@uv run --no-sync -- ruff format

lint: env_dev ## Run the linter to check
	@echo "Running linter..."
	@uv run --no-sync -- ruff check

lint_fix: env_dev ## Run the linter to fix
	@echo "Fixing linting..."
	@uv run --no-sync -- ruff check --fix

###############
### Testing ###
###############

test: env_dev ## Run unit tests
	uv run --no-sync -- pytest tests/unit -v

test_integration: env_integration ## Run integration tests (mock HTTP)
	uv run --no-sync -- pytest tests/integration -v

run: env ## Dry-run with sample data (safe — no API calls)
	uv run --no-sync -- python src/cli.py \
		--input templates/template.csv \
		--config config.json \
		--limit 5

##############
### Docker ###
##############

docker_test: docker_test_down docker_test_up

docker_test_up:
	$(DOCKER_COMPOSE) up \
		--exit-code-from unit-lint \
		--abort-on-container-exit \
		--build unit-lint

docker_test_down:
	$(DOCKER_COMPOSE) down unit-lint --volumes --remove-orphans

docker_test_integration: docker_test_integration_down docker_test_integration_up

docker_test_integration_up:
	$(DOCKER_COMPOSE) up \
		--exit-code-from test-integration \
		--abort-on-container-exit \
		--build test-integration

docker_test_integration_down:
	$(DOCKER_COMPOSE) down test-integration --volumes --remove-orphans

docker_down: docker_test_down docker_test_integration_down
