KVCS_EFC_DIR  ?= ../../kvcs-efc
KVCS_C_DIR    ?= ../C
PKG_CONFIG_PATH := $(abspath $(KVCS_C_DIR)):$(PKG_CONFIG_PATH)
export PKG_CONFIG_PATH
EFC_BUILD_DIR := $(abspath $(KVCS_EFC_DIR)/build)
SHELL := /bin/bash

# Static libkvcs.a by default; KVCS_DYNAMIC=1 links libkvcs.so (same knob as Rust build.rs).
# E2E always needs the `e2e` tag; fold kvcs_dynamic in when requested (a single
# -tags flag — a second -tags would override, not merge).
E2E_TAGS := e2e
ifeq ($(KVCS_DYNAMIC),1)
GO_TAGS := -tags kvcs_dynamic
E2E_TAGS := e2e,kvcs_dynamic
endif

.PHONY: build unittest coverage e2e clean help

build: ## Compile the package (KVCS_DYNAMIC=1 for dynamic link)
	go build $(GO_TAGS) ./...

unittest: ## Run ALL unit tests with mock library (dynamic link so mock swaps in)
	LD_LIBRARY_PATH=$(EFC_BUILD_DIR) go test -tags kvcs_dynamic -v . ./tests/unittest/...

coverage: ## Run ALL unit tests with mock library, produce cobertura + junit
	@set -o pipefail; \
	LD_LIBRARY_PATH=$(EFC_BUILD_DIR) \
		go test -tags kvcs_dynamic -v -coverprofile=coverage.out -covermode=atomic -coverpkg=./... . ./tests/unittest/... > test-output.txt 2>&1; \
	STATUS=$$?; \
	cat test-output.txt; \
	go-junit-report -set-exit-code < test-output.txt > report.xml; \
	rm -f test-output.txt; \
	gocover-cobertura < coverage.out > coverage.xml 2>/dev/null || true; \
	exit $$STATUS

E2E_BINARY  ?= kvcs_e2e_test
E2E_COMPOSE ?= ../../kvcs-test/runtimes/data-plane-e2e/docker-compose.yaml

e2e: $(E2E_BINARY) ## Build E2E binary, run inside EFC container (volume-mounted)
	docker compose -f $(E2E_COMPOSE) exec kvcs-efc-1 \
		/kvcs-efc-rt/kvcs-sdk/go/$(E2E_BINARY) -test.v -test.run TestE2E -test.timeout 60s

$(E2E_BINARY): $(wildcard tests/e2e_test/*.go)
	CGO_ENABLED=1 go test -tags $(E2E_TAGS) -c -o $@ ./tests/e2e_test/...

clean: ## Clean build artifacts and test cache
	rm -f kvcs_e2e_test
	go clean -testcache

help: ## Show this help
	@grep -E '^[a-z].*:.*##' $(MAKEFILE_LIST) | sed 's/:.*## /\t/' | sort
