.PHONY: setup deps fmt fmt-check vet test build run start check docker-build docker-run clean help

RELATE_VERSION ?= v1.5.0
FFI_DIR := relate-ffi-x86_64-unknown-linux-gnu
FFI_ARCHIVE := /tmp/relate-ffi-$(RELATE_VERSION).tar.gz
BIN := bin/okf-relate
ARGS ?= help

setup:
	@if [ ! -f "$(FFI_DIR)/librelate_ffi.so" ]; then \
		mkdir -p "$(FFI_DIR)"; \
		curl -fsSL "https://github.com/relatedb/relate/releases/download/$(RELATE_VERSION)/relate-ffi-x86_64-unknown-linux-gnu.tar.gz" -o "$(FFI_ARCHIVE)"; \
		tar -xzf "$(FFI_ARCHIVE)" -C "$(FFI_DIR)" --strip-components=1; \
	fi

deps: setup
	go mod download

fmt:
	gofmt -w $$(find cmd internal -type f -name '*.go')

fmt-check:
	@files="$$(gofmt -l .)"; if [ -n "$$files" ]; then printf "Files need gofmt:\n%s\n" "$$files"; exit 1; fi

vet:
	go vet ./...

test:
	go test -count=1 ./...

build: setup
	mkdir -p bin
	CGO_LDFLAGS="-L$(CURDIR)/$(FFI_DIR)" LD_LIBRARY_PATH="$(CURDIR)/$(FFI_DIR)" go build -o "$(BIN)" ./cmd/okf-relate

run: setup
	CGO_LDFLAGS="-L$(CURDIR)/$(FFI_DIR)" LD_LIBRARY_PATH="$(CURDIR)/$(FFI_DIR)" go run ./cmd/okf-relate $(ARGS)

start: run

check: fmt-check vet test

docker-build:
	docker build -f Containerfile -t okf-relate .

docker-run: docker-build
	docker run --rm --mount type=volume,source=okf-relate-data,target=/app/graph okf-relate

clean:
	rm -f "$(BIN)"

help:
	@printf "Targets:\n"
	@printf "  make setup       Download the Relate native FFI library\n"
	@printf "  make deps        Download dependencies\n"
	@printf "  make fmt         Format Go source\n"
	@printf "  make fmt-check   Check Go formatting\n"
	@printf "  make vet         Run go vet\n"
	@printf "  make test        Run Go tests\n"
	@printf "  make build       Build the application\n"
	@printf "  make run ARGS=\"mcp --bundle docs --port 8080\"  Run the CLI locally\n"
	@printf "  make start       Start the application (alias for make run)\n"
	@printf "  make check       Run format, vet, and test checks\n"
	@printf "  make docker-build Build the production container\n"
	@printf "  make docker-run  Build and run with persistent graph data\n"
