# Makefile for demo-epb. Intentionally small so the demo
# builds on any POSIX system without external build tools (CMake, SCons).

CC      ?= cc
CFLAGS  ?= -std=c99 -Wall -Wextra -Werror -Wpedantic \
           -Wcast-align -Wcast-qual -Wconversion -Wshadow \
           -Wstrict-prototypes -Wmissing-prototypes
COVFLAGS = --coverage -O0 -g

SRC_DIR  = src
TEST_DIR = tests/unit
BUILD    = build

SRCS    = $(SRC_DIR)/switch_debouncer.c \
          $(SRC_DIR)/actuator_driver.c \
          $(SRC_DIR)/apply_controller.c \
          $(SRC_DIR)/safety_manager.c
OBJS    = $(SRCS:%.c=$(BUILD)/%.o)

TESTS   = test_switch_debouncer test_actuator_driver test_apply_controller \
          test_safety_manager
TEST_BINS = $(TESTS:%=$(BUILD)/%)

.PHONY: all test coverage clean misra static docs test-report landing-page

all: $(TEST_BINS)

landing-page:
	python3 tools/generate_landing_page.py

docs:
	@which doxygen >/dev/null 2>&1 || { echo "doxygen not installed (brew/apt install doxygen)"; exit 1; }
	doxygen Doxyfile
	@echo "Doxygen HTML: $(BUILD)/api-doc/html/index.html"

test-report: $(TEST_BINS)
	@$(MAKE) -s test > $(BUILD)/test-output.txt 2>&1 || true
	python3 tools/generate_test_report.py

$(BUILD)/%.o: %.c
	@mkdir -p $(dir $@)
	$(CC) $(CFLAGS) $(COVFLAGS) -I$(SRC_DIR) -c $< -o $@

$(BUILD)/test_%: $(TEST_DIR)/test_%.c $(OBJS)
	@mkdir -p $(dir $@)
	$(CC) $(CFLAGS) $(COVFLAGS) -I$(SRC_DIR) -Itests $< $(OBJS) -o $@

test: $(TEST_BINS)
	@echo "==========================================="
	@echo "Running unit tests"
	@echo "==========================================="
	@fail=0; \
	for t in $(TEST_BINS); do \
	  echo ""; \
	  $$t || fail=1; \
	done; \
	exit $$fail

coverage: test
	@which lcov >/dev/null 2>&1 || { echo "lcov not installed (brew install lcov)"; exit 1; }
	lcov --capture --directory $(BUILD) --output-file $(BUILD)/coverage.info
	lcov --remove $(BUILD)/coverage.info '/usr/*' 'tests/*' --output-file $(BUILD)/coverage.clean.info
	genhtml $(BUILD)/coverage.clean.info --output-directory $(BUILD)/coverage-html
	@echo "Coverage HTML: $(BUILD)/coverage-html/index.html"

misra:
	@which cppcheck >/dev/null 2>&1 || { echo "cppcheck not installed (brew install cppcheck)"; exit 1; }
	cppcheck --enable=all --inconclusive --error-exitcode=1 \
	  --suppress=missingIncludeSystem \
	  --suppress=unusedFunction \
	  --addon=misra \
	  -I$(SRC_DIR) $(SRC_DIR)

static:
	@which cppcheck >/dev/null 2>&1 || { echo "cppcheck not installed"; exit 1; }
	cppcheck --enable=warning,style,performance,portability \
	  --error-exitcode=1 \
	  --suppress=missingIncludeSystem \
	  -I$(SRC_DIR) $(SRC_DIR)

clean:
	rm -rf $(BUILD)
