SHELL := /bin/bash

ROOT     := $(abspath .)
VENDOR   := $(ROOT)/third_party/libghostty-vt
SOURCE   := $(VENDOR)/source
INSTALL  := $(VENDOR)/install
COMMIT   := $(shell cat $(VENDOR)/COMMIT)

.PHONY: deps deps-fetch deps-build clean-deps spike patterm test

# `make deps` fetches and builds libghostty-vt at the pinned commit.
# Re-runs are idempotent on success; touch $(VENDOR)/COMMIT to force a rebuild.
deps: $(INSTALL)/lib/libghostty-vt.a

$(SOURCE)/.git/HEAD:
	@echo ">> cloning ghostty-org/ghostty @ $(COMMIT)"
	@rm -rf $(SOURCE)
	@git clone --filter=blob:none https://github.com/ghostty-org/ghostty.git $(SOURCE)
	@cd $(SOURCE) && git checkout --detach $(COMMIT)

deps-fetch: $(SOURCE)/.git/HEAD

# Zig's `standardOptimizeOption` defaults to .Debug when no
# -Doptimize is passed, which makes libghostty-vt's CSI/SGR parser
# an order of magnitude slower — truecolor full-screen frames spend
# ~16-29 ms each in em.Write under Debug (see
# internal/app/bench_test.go BenchmarkEmulator_Write_*), which caps
# the full PTY-to-host pipeline at ~60 fps. ReleaseFast is the
# right default for the shipped artefact. Override with
# `make deps GHOSTTY_VT_OPTIMIZE=Debug` when you actually want a
# debug build of the upstream lib.
GHOSTTY_VT_OPTIMIZE ?= ReleaseFast

# Resolve zig via the project's mise pin (.mise.toml) when available,
# falling back to whatever's on PATH. mise keeps the zig version in
# lockstep with what the pinned ghostty commit requires; without it,
# contributors have to chase the version requirement themselves.
ZIG := $(shell command -v mise >/dev/null && mise which zig 2>/dev/null || command -v zig 2>/dev/null)

$(INSTALL)/lib/libghostty-vt.a: $(SOURCE)/.git/HEAD
	@if [ -z "$(ZIG)" ]; then \
		echo "ERROR: zig not available. Run \`mise install\` (see .mise.toml — needs zig 0.15.2) or install zig manually."; \
		exit 1; \
	fi
	@echo ">> building libghostty-vt with $(ZIG) (optimize=$(GHOSTTY_VT_OPTIMIZE))"
	@cd $(SOURCE) && $(ZIG) build -Demit-lib-vt -Doptimize=$(GHOSTTY_VT_OPTIMIZE) --prefix $(INSTALL)
	@test -f $(INSTALL)/lib/libghostty-vt.a || { echo "ERROR: expected static lib at $(INSTALL)/lib/libghostty-vt.a"; exit 1; }
	@echo ">> libghostty-vt installed under $(INSTALL)"

deps-build: $(INSTALL)/lib/libghostty-vt.a

clean-deps:
	rm -rf $(SOURCE) $(INSTALL)

VERSION ?= $(shell git describe --tags --always --dirty 2>/dev/null || echo dev)

spike: deps
	go build -o ./bin/spike ./cmd/spike

patterm: deps
	go build -ldflags "-X main.version=$(VERSION)" -o ./bin/patterm ./cmd/patterm

test: deps
	go test ./...
