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

S := ./scripts

.PHONY: help setup apply rebuild update update-dry build check test clippy fmt run release status clean distclean

help: ## Show this help
	@echo "grok-build fork -- patch-based workflow"
	@echo
	@grep -hE '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) \
	  | awk 'BEGIN{FS=":.*?## "}{printf "  \033[36m%-12s\033[0m %s\n", $$1, $$2}'
	@echo
	@echo "Typical loop:"
	@echo "  make apply                        # work/ = upstream + patches/"
	@echo "  \$$EDITOR work/crates/.../foo.rs   # edit"
	@echo "  cd work && git commit -am '...'   # one commit == one patch"
	@echo "  make rebuild                      # write it back to patches/"

setup: ## Install the toolchain (rustup, dotslash/protoc)
	@$(S)/setup.sh

apply: ## Rebuild work/ from upstream.rev + patches/  (FORCE=1 to discard local changes)
	@FORCE=$(FORCE) $(S)/apply-patches.sh

rebuild: ## Export work/ commits back into patches/
	@$(S)/rebuild-patches.sh

update: ## Pin the newest upstream sync and forward-port patches
	@$(S)/update-upstream.sh

update-dry: ## Show what an update would pull in, changing nothing
	@$(S)/update-upstream.sh --dry-run

build: ## Build the xai-grok-pager debug binary
	@$(S)/build.sh

release: ## Build the optimised binary
	@$(S)/build.sh --release

check: ## Fast type-check without codegen
	@CARGO_CMD=check $(S)/build.sh

test: ## Run tests (PKG=<crate> to narrow, default: the version crate)
	@CARGO_CMD=test PKG=$(or $(PKG),xai-grok-version) $(S)/build.sh

clippy: ## Lint
	@CARGO_CMD=clippy $(S)/build.sh

fmt: ## Format the patched tree
	@cd work && cargo fmt --all

run: ## Build and launch the TUI
	@CARGO_CMD=run $(S)/build.sh

status: ## Show pin, patch count and work/ state
	@printf 'upstream.rev : %s\n' "$$(grep -vE '^\s*(#|$$)' upstream.rev | head -n1)"
	@printf 'patches      : %s file(s)\n' "$$(ls -1 patches/*.patch 2>/dev/null | wc -l | tr -d ' ')"
	@if [ -d work/.git ]; then \
	  printf 'work/        : %s commit(s) above base\n' "$$(git -C work rev-list --count base..HEAD 2>/dev/null || echo '?')"; \
	  git -C work log --oneline --no-decorate base..HEAD 2>/dev/null | sed 's/^/               /'; \
	  if [ -n "$$(git -C work status --porcelain)" ]; then echo '               (uncommitted changes present)'; fi; \
	else \
	  printf 'work/        : not created yet -- run make apply\n'; \
	fi

clean: ## Remove build output, keep the checkout
	@rm -rf work/target && echo "removed work/target"

distclean: ## Remove work/ and upstream/ entirely (patches/ is untouched)
	@rm -rf work upstream && echo "removed work/ and upstream/"
