# --- Mimic backend Makefile ------------------------------------------------
# Detects Docker / Podman automatically (NF-platform).

PY        ?= python3.12
VENV      ?= .venv
PIP       := $(VENV)/bin/pip
PYTHON    := $(VENV)/bin/python
PYTEST    := $(VENV)/bin/pytest
RUFF      := $(VENV)/bin/ruff
MYPY      := $(VENV)/bin/mypy
ALEMBIC   := $(VENV)/bin/alembic
FLASK     := $(VENV)/bin/flask

# Container runtime auto-detect: Docker (preferred) or Podman rootless.
CONTAINER ?= $(shell command -v docker 2>/dev/null || command -v podman 2>/dev/null)
COMPOSE   ?= $(shell command -v docker-compose 2>/dev/null || echo "$(CONTAINER) compose")

export FLASK_APP=mimic.app:create_app

.PHONY: help install lint fmt typecheck test test-int test-cov run \
        db-up db-down db-migrate db-revision db-seed db-dump db-restore \
        build clean

help:
	@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | \
	  awk 'BEGIN {FS=":.*?## "}; {printf "  \033[36m%-20s\033[0m %s\n", $$1, $$2}'

install: ## Create venv and install dev dependencies
	$(PY) -m venv $(VENV)
	$(PIP) install --upgrade pip wheel
	$(PIP) install -e ".[dev]"

lint: ## Ruff lint
	$(RUFF) check src tests

fmt: ## Ruff format
	$(RUFF) format src tests
	$(RUFF) check --fix src tests

typecheck: ## Mypy strict
	$(MYPY) src

test: ## Unit tests (SQLite)
	$(PYTEST) tests/unit -v

test-int: ## Integration tests (testcontainers Postgres)
	$(PYTEST) tests/integration -v -m integration

test-cov: ## Unit + integration with coverage report
	$(PYTEST) --cov=mimic --cov-report=term-missing --cov-report=html

run: ## Run Flask dev server
	$(FLASK) run --host 0.0.0.0 --port 5000 --debug

db-up: ## Start Postgres dev container
	$(COMPOSE) up -d postgres

db-down: ## Stop Postgres dev container
	$(COMPOSE) down

db-migrate: ## Apply migrations
	$(ALEMBIC) upgrade head

db-revision: ## Generate migration (msg=...)
	$(ALEMBIC) revision --autogenerate -m "$(msg)"

db-seed: ## Seed local dev data (TBD sprint 1)
	@echo "TBD sprint 1"

db-dump: ## Manual DB dump (NF-state, R-O1)
	$(VENV)/bin/mimic-cli db dump --out backups/mimic-$$(date +%Y%m%d-%H%M%S).sql

db-restore: ## Restore from dump (file=...)
	$(VENV)/bin/mimic-cli db restore --file $(file)

build: ## Build wheel
	$(PYTHON) -m build

clean:
	rm -rf $(VENV) .pytest_cache .mypy_cache .ruff_cache htmlcov dist build *.egg-info
