SHELL := /usr/bin/env bash
.DEFAULT_GOAL := help

GO ?= go
GO_TOOL := $(GO) tool
API_DIR := $(abspath ../api)
ROOT_DIR := $(abspath ..)
API_PREPARED ?= 0
QUALITY_REQUIREMENTS ?= requirements-quality.txt
QUALITY_VENV ?= $(CURDIR)/.venv-quality
QUALITY_PYTHON ?= $(QUALITY_VENV)/bin/python
QUALITY_STAMP := $(QUALITY_VENV)/.deps.stamp
BOOTSTRAP_PYTHON ?= python3

##@ Build and run

.PHONY: build
build: ## Build the application binary
	@mkdir -p bin
	$(GO) build -buildvcs=false -trimpath -o bin/app ./cmd/app

.PHONY: run
run: ## Run the application with the current environment
	$(GO) run ./cmd/app

.PHONY: migrate-status migrate-up migrate-down-one
migrate-status: ## Show embedded migration status for the database in DATABASE_URL
	$(GO) run ./cmd/migrate status

migrate-up: ## Apply pending embedded migrations to the database in DATABASE_URL
	$(GO) run ./cmd/migrate up

migrate-down-one: ## Roll back the latest applied migration in the database in DATABASE_URL
	$(GO) run ./cmd/migrate down-one

.PHONY: mail-retry mail-retry-build
mail-retry: ## Inspect or authorize an audited unknown mail retry (set ARGS)
	$(GO) run ./cmd/mail-retry $(ARGS)

mail-retry-build: ## Build the local mail retry operator command
	@mkdir -p bin
	$(GO) build -buildvcs=false -trimpath -o bin/mail-retry ./cmd/mail-retry

.PHONY: deps install install-tools
deps: ## Download pinned Go module dependencies
	$(GO) mod download

install install-tools: deps ## Install module-pinned Go tools without global changes
	@$(GO) version
	@$(GO_TOOL) ogen --version
	@$(GO_TOOL) sqlc version
	@$(GO_TOOL) golangci-lint version

.PHONY: tidy
tidy: ## Tidy application and tool dependencies
	$(GO) mod tidy

.PHONY: clean
clean: ## Remove local build and test artifacts
	rm -rf bin coverage.out coverage.html

##@ Code generation

.PHONY: generate gen
generate gen: ## Regenerate API, SQL, and dependency-injection code in dependency order
	@if [ "$(API_PREPARED)" != "1" ]; then $(MAKE) -C "$(API_DIR)" bundle; fi
	$(MAKE) --no-print-directory gen-openapi API_PREPARED=1
	$(MAKE) --no-print-directory gen-ml API_PREPARED=1
	$(MAKE) --no-print-directory gen-sqlc
	$(MAKE) --no-print-directory gen-wire
	$(MAKE) --no-print-directory mocks

.PHONY: gen-openapi
gen-openapi: ## Generate the public Ogen server adapter
	@if [ "$(API_PREPARED)" != "1" ]; then $(MAKE) -C "$(API_DIR)" bundle; fi
	$(GO_TOOL) ogen -config codegen/ogen.yml --target internal/adapter/primary/http/api --package api --clean ../api/core/openapi.bundle.yml

.PHONY: gen-ml
gen-ml: ## Generate the internal ML service client
	@if [ "$(API_PREPARED)" != "1" ]; then $(MAKE) -C "$(API_DIR)" bundle; fi
	$(GO_TOOL) ogen -config codegen/ogen-ml.yml --target internal/adapter/secondary/ml/api --package api --clean ../api/ml/openapi.bundle.yml

.PHONY: gen-sqlc
gen-sqlc: ## Generate PostgreSQL query code from migrations and queries
	$(GO_TOOL) sqlc generate -f codegen/sqlc.yml

.PHONY: gen-wire
gen-wire: ## Generate the compile-time dependency graph
	$(GO_TOOL) wire ./internal/bootstrap/...

.PHONY: mocks
mocks: ## Generate configured mocks when interfaces are selected
	@if grep -Eq '^[[:space:]]*packages:[[:space:]]*\{\}[[:space:]]*(#.*)?$$' codegen/mockery.yml; then \
		echo 'mockery: no interfaces selected in codegen/mockery.yml'; \
	else \
		$(GO_TOOL) mockery --config codegen/mockery.yml; \
	fi

.PHONY: check-ogen-compat
check-ogen-compat: ## Verify OpenAPI 3.2 features and API error, pagination, and retry conventions with ogen
	@set -euo pipefail; mkdir -p bin; temporary_dir=$$(mktemp -d "$(CURDIR)/bin/ogen-compat.XXXXXX"); trap 'rm -rf "$$temporary_dir"' EXIT; \
	$(GO_TOOL) ogen -config codegen/ogen-compat.yml --target "$$temporary_dir" --package compat --clean ../api/testdata/openapi-3.2.0.yml; \
	cp testdata/ogen_compat_test.go "$$temporary_dir/ogen_compat_test.go"; \
	$(GO) test "./$${temporary_dir#$(CURDIR)/}"

.PHONY: check-generated
check-generated: ## Check tracked generated output against generator inputs
	python3 "$(ROOT_DIR)/scripts/check-generated.py"

##@ Format, lint, and test

.PHONY: fmt
fmt: ## Format Go sources
	$(GO_TOOL) golangci-lint fmt ./...

.PHONY: fmt-check
fmt-check: ## Check Go formatting without modifying files
	@unformatted=$$(gofmt -l $$(find . -name '*.go' -type f)); \
	if [ -n "$$unformatted" ]; then printf '%s\n' "$$unformatted"; exit 1; fi
	@formatter_diff=$$($(GO_TOOL) golangci-lint fmt --diff ./...); \
	if [ -n "$$formatter_diff" ]; then printf '%s\n' "$$formatter_diff"; exit 1; fi

.PHONY: lint lint-go lint-sql lint-fix
lint: ## Run Go and SQL linters
	$(MAKE) --no-print-directory lint-go
	$(MAKE) --no-print-directory lint-sql

lint-go: ## Run golangci-lint on all backend packages
	$(GO_TOOL) golangci-lint run ./...

lint-sql: $(QUALITY_STAMP) ## Lint migrations and sqlc queries
	$(QUALITY_PYTHON) -m sqlfluff lint --config .sqlfluff db/migrations db/queries

lint-fix: $(QUALITY_STAMP) ## Apply safe Go lint fixes and SQL formatting to queries only
	$(GO_TOOL) golangci-lint run --fix ./...
	$(QUALITY_PYTHON) -m sqlfluff fix --config .sqlfluff db/queries

$(QUALITY_STAMP): $(QUALITY_REQUIREMENTS)
	$(BOOTSTRAP_PYTHON) -m venv "$(QUALITY_VENV)"
	"$(QUALITY_PYTHON)" -m pip install --disable-pip-version-check -r "$(QUALITY_REQUIREMENTS)"
	@touch "$(QUALITY_STAMP)"

.PHONY: install-quality-python-deps
install-quality-python-deps: $(QUALITY_STAMP) ## Install pinned SQL quality tools locally

.PHONY: test test-fast test-race test-int test-int-list test-int-compile test-scripts
test: ## Run backend unit tests with the race detector
	$(GO) test -race -count=1 ./...

test-fast: ## Run backend unit tests without race instrumentation
	$(GO) test ./...

test-race: test ## Alias for the race-enabled unit suite

test-int: ## Run integration tests, optionally selected by TEST_SHARD_INDEX and TEST_SHARD_TOTAL
	$(BOOTSTRAP_PYTHON) scripts/run-integration-suite.py --go "$(GO)"

test-int-list: ## Discover and list the selected integration tests without starting containers
	$(BOOTSTRAP_PYTHON) scripts/run-integration-suite.py --go "$(GO)" --list

test-scripts: ## Check integration shard coverage, selection, and failure propagation
	$(BOOTSTRAP_PYTHON) -B -m unittest discover -s scripts -p 'test_*.py'

test-int-compile: ## Compile infrastructure integration tests without starting containers
	$(GO) test -tags=integration -run '^$$' ./integration_test/...

.PHONY: verify check
check: ## Run local formatting, build, unit, and lint checks in order
	$(MAKE) --no-print-directory fmt-check
	$(MAKE) --no-print-directory build
	$(MAKE) --no-print-directory test-fast
	$(MAKE) --no-print-directory test-scripts
	$(MAKE) --no-print-directory lint

verify: ## Run code, test, tooling, and generated-drift checks in order
	$(MAKE) --no-print-directory generate
	$(MAKE) --no-print-directory check
	$(MAKE) --no-print-directory check-ogen-compat
	$(MAKE) --no-print-directory check-generated

##@ Help

.PHONY: help
help: ## Show available targets
	@awk 'BEGIN{FS=":.*##"; printf "\nUsage:\n  make -C backend <target>\n"} /^[a-zA-Z0-9_-]+:.*##/ {printf "  %-22s %s\n", $$1, $$2} /^##@/ {printf "\n%s\n", substr($$0, 5)}' $(MAKEFILE_LIST)
