.DEFAULT_GOAL := help

SHELL := $(shell command -v bash)
.SHELLFLAGS := -eu -o pipefail -c

.PHONY: help install generate gen fmt fmt-check lint test check verify check-generated docs-check security security-images

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

install: ## Install project dependencies
	@status=0; for part in api frontend ml; do \
		printf '\n==> %s install\n' "$$part"; \
		$(MAKE) -C "$$part" install || status=1; \
	done; \
	for part in backend runner labd; do \
		printf '\n==> %s deps\n' "$$part"; \
		$(MAKE) -C "$$part" deps || status=1; \
	done; \
	exit "$$status"

generate: ## Generate shared contracts, Go and TypeScript code, and Python models
	$(MAKE) -C api bundle
	API_PREPARED=1 $(MAKE) -C backend generate
	API_PREPARED=1 $(MAKE) -C runner generate
	API_PREPARED=1 $(MAKE) -C labd generate
	API_PREPARED=1 $(MAKE) -C frontend generate
	API_PREPARED=1 $(MAKE) -C ml generate

gen: generate ## Alias for generate

fmt: ## Format all project parts
	@status=0; for part in api backend runner labd frontend ml; do \
		printf '\n==> %s fmt\n' "$$part"; \
		$(MAKE) -C "$$part" fmt || status=1; \
	done; exit "$$status"

fmt-check: ## Check formatting without changing files
	@status=0; for part in api backend runner labd frontend ml; do \
		printf '\n==> %s fmt-check\n' "$$part"; \
		$(MAKE) -C "$$part" fmt-check || status=1; \
	done; exit "$$status"

lint: ## Run configured linters
	@status=0; for part in api backend runner labd frontend ml; do \
		printf '\n==> %s lint\n' "$$part"; \
		$(MAKE) -C "$$part" lint || status=1; \
	done; exit "$$status"

test: ## Run unit and component tests
	@status=0; for part in backend runner labd frontend ml; do \
		printf '\n==> %s test\n' "$$part"; \
		$(MAKE) -C "$$part" test || status=1; \
	done; exit "$$status"

check: ## Run local checks for code, docs, deployment, and observability
	@status=0; for part in api backend runner labd frontend ml deploy observability; do \
		printf '\n==> %s check\n' "$$part"; \
		$(MAKE) -C "$$part" check || status=1; \
	done; \
	printf '\n==> docs-check\n'; \
	$(MAKE) docs-check || status=1; \
	exit "$$status"

verify: ## Run full checks, generated drift, and an isolated technical smoke
	$(MAKE) generate
	$(MAKE) check-generated
	$(MAKE) check
	$(MAKE) -C api check-toolchain
	$(MAKE) -C backend test-race
	$(MAKE) -C backend test-int
	$(MAKE) -C deploy smoke

check-generated: ## Fail when generated files differ from committed output
	@python3 scripts/check-generated.py

docs-check: ## Check documentation structure and local links
	@PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s scripts -p 'test_docs_check.py'
	@python3 scripts/docs-check.py

security: ## Run dependency, source, and secret checks
	$(MAKE) -C security check

security-images: ## Build and scan application images
	$(MAKE) -C security images
