# All shipped binaries and the package path each is built from. Both tools live
# under cmd/; the module root ships no binary of its own.
BINARIES := agentpr watchpr agentws agentvault agentreview agentgh
DIST    := dist
VERSION := $(shell git describe --tags --always --dirty 2>/dev/null || echo dev)
GOFLAGS := -ldflags="-s -w -X main.version=$(VERSION)"
OS      ?= $(shell go env GOOS)
ARCH    ?= $(shell go env GOARCH)

# The Go package path for a binary. Both tools live under cmd/. Usable inside a
# shell for-loop over $(BINARIES).
pkgpath  = ./cmd/$$b

.PHONY: all build test lint pre-commit fmt clean install completions rpm patch minor major

all: build

# Each main package needs its own -o, so they are built individually rather
# than with a single ./... invocation.
build:
	@for b in $(BINARIES); do \
		echo "building $$b"; \
		CGO_ENABLED=0 GOOS=$(OS) GOARCH=$(ARCH) go build $(GOFLAGS) -o $(DIST)/$$b $(pkgpath) || exit 1; \
	done

test:
	go test -v ./...

lint:
	golangci-lint run ./...

pre-commit:
	pre-commit run --all-files

fmt:
	gofmt -w .

clean:
	rm -rf $(DIST) $(BINARIES) completions

install:
	go install $(GOFLAGS) ./...

# Generate bash/zsh/fish completions for every binary into completions/.
completions:
	./scripts/completions.sh

# Snapshot release: raw binaries plus the RPM in dist/, unsigned.
rpm:
	GOTOOLCHAIN=auto go run github.com/goreleaser/goreleaser/v2@v2.20.2 release --snapshot --clean --skip=sign

DEFAULT_BRANCH ?= main

# Draft the release with generated notes, then push the tag; the release
# workflow attaches assets to the draft and publishes it.
patch minor major:
	@git fetch --quiet --tags origin $(DEFAULT_BRANCH)
	@test "$$(git branch --show-current)" = "$(DEFAULT_BRANCH)" || { echo "ERROR: not on $(DEFAULT_BRANCH)"; exit 1; }
	@test -z "$$(git status --porcelain)" || { echo "ERROR: working tree not clean"; exit 1; }
	@test "$$(git rev-parse HEAD)" = "$$(git rev-parse origin/$(DEFAULT_BRANCH))" || { echo "ERROR: HEAD is not origin/$(DEFAULT_BRANCH)"; exit 1; }
	@LATEST=$$(git tag --list 'v*' --sort=-v:refname | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+$$' | head -1); \
	NEW=$$(echo "$${LATEST:-v0.0.0}" | sed 's/^v//' | awk -F. -v b=$@ '{ \
		if (b == "major") print "v" ($$1+1) ".0.0"; \
		else if (b == "minor") print "v" $$1 "." ($$2+1) ".0"; \
		else print "v" $$1 "." $$2 "." ($$3+1) }'); \
	SHA=$$(git rev-parse HEAD); \
	gh release create "$$NEW" --draft --target "$$SHA" --generate-notes --title "$$NEW" || exit 1; \
	git push origin "$$SHA:refs/tags/$$NEW" || { gh release delete "$$NEW" --yes; exit 1; }
