SHELL := /bin/bash
SCRIPT_DIR := scripts
OPA := tools/opa

.PHONY: help install check fmt lint test build publish changeset version

help:
	@echo "Targets:"
	@echo "  install     Install pinned OPA binary into tools/"
	@echo "  check       Rego fmt + regal lint (if present) + schema-check + tests"
	@echo "  fmt         Format all .rego files with opa fmt"
	@echo "  lint        Run regal lint (requires regal on PATH)"
	@echo "  test        Run opa test for every rule and gate"
	@echo "  build       Build OPA bundles into dist/"
	@echo "  publish     Publish bundles to Gitea generic registry (needs GITEA_TOKEN)"
	@echo "  changeset   Create a changeset for a new version"
	@echo "  version     Apply changesets to bump package versions"

install:
	$(SCRIPT_DIR)/install-opa.sh

check:
	$(SCRIPT_DIR)/check.sh

fmt:
	$(OPA) fmt -w policies

lint:
	[ -z "$$(command -v regal)" ] || regal lint policies --format github

test:
	@for d in policies/rules/*/; do \
		name="$$(basename "$$d")"; \
		echo "== test $$name"; \
		$(OPA) test "$$d/policy.rego" "$$d/policy_test.rego" "$$d/scenarios.json" || exit 1; \
	done
	@rules=""; \
	for d in policies/rules/*/; do rules="$$rules $$d/policy.rego"; done; \
	echo "== test deploy-gate"; \
	$(OPA) test policies/gates/deploy-gate/gate_test.rego policies/gates/deploy-gate/scenarios.json $$rules

build:
	$(SCRIPT_DIR)/build.sh

publish:
	$(SCRIPT_DIR)/publish.sh

changeset:
	npx changeset

version:
	npx changeset version