# Makefile padrao dos repositorios Solierrr.
# Igual em todos os repos: so o bloco "especifico deste repositorio" muda.
# Requer: make e sh (Git Bash no Windows). Para `make vault`: Infisical CLI e `infisical login`.

# ---- especifico deste repositorio ----
VAULT_FOLDERS ?= /service-urls
INSTALL_CMD   ?= uv sync --frozen --extra dev
DEV_CMD       ?=
BUILD_CMD     ?= uv build
TEST_CMD      ?= uv run pytest
LINT_CMD      ?= uv run ruff check . && uv run ruff format --check .
FORMAT_CMD    ?= uv run ruff format .
CLEAN_PATHS   ?= .venv dist .pytest_cache .ruff_cache
DOCTOR_TOOLS  ?= git python uv

# ---- padrao (nao editar por repositorio) ----
INFISICAL_PROJECT_ID ?= 2296d19c-5f3b-41e1-afa3-fcde39966a71
ENV ?= local
OUT ?= .env
# Git Bash converteria '/vite' em 'C:/Program Files/Git/vite' ao chamar o CLI. A variavel vale so para o
# CLI: exporta-la para o make quebraria o mvnw, o gradlew e outras ferramentas que precisam da conversao.
ifeq ($(OS),Windows_NT)
INFISICAL ?= MSYS_NO_PATHCONV=1 infisical.cmd
else
INFISICAL ?= infisical
endif

.DEFAULT_GOAL := help
.PHONY: help verify-vault vault env dev install build test lint format clean doctor ci

help: ## Show the available commands
	@awk 'BEGIN {FS = ":.*## "; printf "Usage: make <target>\n\n"} /^[a-zA-Z0-9_-]+:.*## / {printf "  %-18s %s\n", $$1, $$2}' $(MAKEFILE_LIST)

verify-vault: ## Check that the Infisical CLI is installed and authenticated
	@$(INFISICAL) --version >/dev/null 2>&1 || { echo "Infisical CLI not installed. Install it (https://infisical.com/docs/cli/overview) and retry."; exit 1; }
	@$(INFISICAL) user get token --silent >/dev/null 2>&1 || { echo "No active Infisical session. Run 'infisical login' and retry."; exit 1; }
	@echo "OK: Infisical authenticated."

vault: verify-vault ## Write OUT (default .env) from Infisical; ENV=local|qa|prod (default local)
	@case "$(ENV)" in local|qa|prod) ;; *) echo "Invalid ENV '$(ENV)'. Use local, qa or prod (example: make vault ENV=qa)."; exit 1;; esac
	@test -n "$(strip $(VAULT_FOLDERS))" || { echo "vault: VAULT_FOLDERS is not configured for this repository"; exit 1; }
	@tmp=$$(mktemp) || exit 1; \
	echo "# Generated by make vault - env=$(ENV) folders=$(VAULT_FOLDERS)" > "$$tmp"; \
	for folder in $(VAULT_FOLDERS); do \
		echo "Extracting $$folder (env=$(ENV))..."; \
		out=$$($(INFISICAL) export --env=$(ENV) --path=$$folder --format=dotenv --projectId=$(INFISICAL_PROJECT_ID) --silent 2>&1) \
			|| { echo "Failed to extract '$$folder' (env=$(ENV)). Check access, environment and path in Infisical."; rm -f "$$tmp"; exit 1; }; \
		if echo "$$out" | grep -q 'serving secrets from last successful fetch'; then \
			echo "Infisical could not reach the server for '$$folder' and returned cached data. $(OUT) was not changed."; rm -f "$$tmp"; exit 1; fi; \
		vars=$$(echo "$$out" | grep -E '^[[:space:]]*(export[[:space:]]+)?[^#[:space:]][^=]*='); \
		if [ -z "$$vars" ]; then \
			echo "No secrets returned for '$$folder' (env=$(ENV)). $(OUT) was not changed."; rm -f "$$tmp"; exit 1; fi; \
		printf '\n# --- %s ---\n%s\n' "$$folder" "$$vars" >> "$$tmp"; \
	done; \
	mv "$$tmp" "$(OUT)" && echo "OK: $(OUT) written (env=$(ENV))."

env: vault ## Alias for vault

dev: ## Start the dev server
	$(if $(strip $(DEV_CMD)),set -e; $(DEV_CMD),@echo "dev: not configured for this repository")

install: ## Install dependencies
	$(if $(strip $(INSTALL_CMD)),set -e; $(INSTALL_CMD),@echo "install: not configured for this repository")

build: ## Build the project
	$(if $(strip $(BUILD_CMD)),set -e; $(BUILD_CMD),@echo "build: not configured for this repository")

test: ## Run the tests
	$(if $(strip $(TEST_CMD)),set -e; $(TEST_CMD),@echo "test: not configured for this repository")

lint: ## Run the linter
	$(if $(strip $(LINT_CMD)),set -e; $(LINT_CMD),@echo "lint: not configured for this repository")

format: ## Format the code
	$(if $(strip $(FORMAT_CMD)),set -e; $(FORMAT_CMD),@echo "format: not configured for this repository")

clean: ## Remove build outputs (CLEAN_PATHS)
	$(if $(strip $(CLEAN_PATHS)),rm -rf $(CLEAN_PATHS),@echo "clean: not configured for this repository")

doctor: ## Check that the tools this repository needs are available
	@missing=0; \
	for tool in make $(DOCTOR_TOOLS); do \
		if command -v $$tool >/dev/null 2>&1; then echo "ok       $$tool"; else echo "MISSING  $$tool"; missing=1; fi; \
	done; \
	if $(INFISICAL) --version >/dev/null 2>&1; then \
		if $(INFISICAL) user get token --silent >/dev/null 2>&1; then echo "ok       infisical (logged in)"; else echo "WARN     infisical installed but not logged in (run 'infisical login')"; fi; \
	else echo "WARN     infisical not installed (only needed for 'make vault')"; fi; \
	exit $$missing

ci: lint test build ## Run lint, test and build in pipeline order
