CC ?= gcc
CFLAGS = -Wall -Wextra -O2 -I../../../target

UNAME_S := $(shell uname -s)
ifeq ($(UNAME_S),Darwin)
    LIB_EXT = dylib
    LDFLAGS = -L../../../target/release -lentropyk_ffi
else ifeq ($(UNAME_S),Linux)
    LIB_EXT = so
    LDFLAGS = -L../../../target/release -lentropyk_ffi -Wl,-rpath,'$$ORIGIN/../../../target/release'
else
    LIB_EXT = dll
    LDFLAGS = -L../../../target/release -lentropyk_ffi
endif

TESTS = test_lifecycle test_errors test_solve test_latency test_memory

.PHONY: all clean run valgrind

all: $(TESTS)

$(TESTS): %: %.c ../../../target/entropyk.h ../../../target/release/libentropyk_ffi.$(LIB_EXT)
	$(CC) $(CFLAGS) -o $@ $< $(LDFLAGS)

../../../target/entropyk.h ../../../target/release/libentropyk_ffi.$(LIB_EXT):
	cd ../../.. && cargo build --release -p entropyk-c

run: $(TESTS)
	@echo "Running all tests..."
	@for test in $(TESTS); do \
		echo "\n=== $$test ==="; \
		./$$test || exit 1; \
	done
	@echo "\nAll tests PASSED"

valgrind: $(TESTS)
	@echo "Running valgrind memory checks..."
	@for test in $(TESTS); do \
		echo "\n=== $$test (valgrind) ==="; \
		valgrind --leak-check=full --error-exitcode=1 ./$$test || exit 1; \
	done
	@echo "\nAll valgrind checks PASSED"

clean:
	rm -f $(TESTS)
