BINARY  := nib
MODULE  := github.com/lerko/nib
GOFLAGS := -trimpath

.PHONY: build dev watch test lint fmt vet clean run cert help

## —— Build ——————————————————————————————————

build: ## Build production binary
	go build $(GOFLAGS) -o $(BINARY) .

dev: ## Build and run with default serve
	go run . serve

watch: ## Live-reload dev server (requires air)
	air

## —— Quality ————————————————————————————————

test: ## Run all tests
	go test ./...

test-v: ## Run all tests (verbose)
	go test -v ./...

test-cover: ## Run tests with coverage report
	go test -coverprofile=coverage.out ./...
	go tool cover -func=coverage.out
	@rm -f coverage.out

lint: vet fmt-check ## Run all linters

vet: ## Run go vet
	go vet ./...

fmt: ## Format all Go files
	gofmt -w .

fmt-check: ## Check formatting (fails if unformatted)
	@test -z "$$(gofmt -l .)" || (echo "unformatted files:" && gofmt -l . && exit 1)

## —— Utility ————————————————————————————————

cert: ## Generate self-signed dev TLS cert (certs/)
	@mkdir -p certs
	openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 \
		-nodes -keyout certs/dev.key -out certs/dev.crt -days 365 \
		-subj "/CN=localhost"
	@echo "  certs/dev.crt and certs/dev.key ready"
	@echo "  usage: make run ARGS=\"serve --tls-cert certs/dev.crt --tls-key certs/dev.key\""

clean: ## Remove build artifacts
	rm -f $(BINARY) coverage.out

run: build ## Build then run with args (usage: make run ARGS="serve")
	./$(BINARY) $(ARGS)

tidy: ## Tidy and verify module dependencies
	go mod tidy
	go mod verify

## —— Help ———————————————————————————————————

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

.DEFAULT_GOAL := help
