# mcp-core - MCP 2.0 stdio server library (protocol rev 2026-07-28).
# See SPEC.md. Build: make ; Test: make test

CC      ?= cc
CSTD    = -std=c17
WARN    = -Wall -Wextra -Werror
DBG     = -g -fno-omit-frame-pointer -fsanitize=address,undefined

PREFIX ?= $(if $(filter 0,$(shell id -u)),/usr/local,$(HOME)/.local)
LIBDIR  = $(DESTDIR)$(PREFIX)/lib
INCDIR  = $(DESTDIR)$(PREFIX)/include/mcpcore

SRC     = src/core/mcpcore.c
VENDORSRC = vendor/cJSON/cJSON.c
COREOBJ = $(SRC:.c=.o)
CJSON_OBJ = vendor/cJSON/cJSON.o

CPPFLAGS += -Isrc -Isrc/core -Ivendor/cJSON -Ivendor/unity/src \
            -D_POSIX_C_SOURCE=200809L -DUNITY_INCLUDE_DOUBLE
CFLAGS   += $(CSTD) $(WARN) $(DBG) $(CPPFLAGS)

LIB      = bin/libmcpcore.a
TESTBIN  = bin/test-mcpcore

.PHONY: all test clean install uninstall zip

all: $(LIB)

bin:
	mkdir -p bin

%.o: %.c
	$(CC) $(CFLAGS) -c $< -o $@

vendor/cJSON/cJSON.o: vendor/cJSON/cJSON.c
	$(CC) $(CFLAGS) -c $< -o $@

$(LIB): $(COREOBJ) $(CJSON_OBJ) | bin
	ar rcs $@.tmp $(COREOBJ) $(CJSON_OBJ)
	mv -f $@.tmp $@

test: $(TESTBIN)
	ASAN_OPTIONS=detect_leaks=0 ./$(TESTBIN)

$(TESTBIN): tests/test_main.c $(wildcard tests/*.c) $(COREOBJ) $(CJSON_OBJ) \
            vendor/unity/src/unity.c | bin
	$(CC) $(CFLAGS) tests/test_main.c vendor/unity/src/unity.c \
		$(COREOBJ) $(CJSON_OBJ) -o $@.tmp
	test -x $@.tmp
	mv -f $@.tmp $@

clean:
	rm -f $(COREOBJ) $(CJSON_OBJ) $(LIB) $(TESTBIN)
	rm -rf bin

install: $(LIB)
	mkdir -p $(LIBDIR) $(INCDIR)
	cp $(LIB) $(LIBDIR)/
	cp src/core/mcpcore.h $(INCDIR)/

uninstall:
	rm -f $(LIBDIR)/libmcpcore.a
	rm -rf $(INCDIR)

# Release zip: git archive from HEAD after a forced clean; project folder
# as archive prefix; build artifacts excluded (bin/ and the .o files are
# tracked, so they need explicit excludes). Output: ../mcp-core.zip
# (override with ZIP_OUT=).
ZIP_OUT ?= ../mcp-core.zip

zip: clean
	git archive -o $(ZIP_OUT) --prefix=mcp-core/ HEAD -- . \
		':(exclude)bin' \
		':(exclude)src/core/mcpcore.o' \
		':(exclude)vendor/cJSON/cJSON.o'
