# Makefile for AVL Heap Library and Tests
#
# Usage:
#   make          - Build everything
#   make lib      - Build static library only
#   make test     - Build and run tests
#   make clean    - Remove all build artifacts

CC = gcc
CFLAGS = -Wall -Wextra -O2 -std=c17
LDFLAGS = -lm

# Output files
LIB = libavlheap.a
TEST_EXEC = test_avl

# Source files
LIB_SRC = avl_heap.c
LIB_OBJ = avl_heap.o
TEST_SRC = test_avl_heap.c
HEADERS = avl_heap.h

# Default target
all: $(LIB) $(TEST_EXEC)

# Build static library
$(LIB): $(LIB_OBJ)
	ar rcs $@ $^
	@echo "Library built: $(LIB)"

$(LIB_OBJ): $(LIB_SRC) $(HEADERS)
	$(CC) $(CFLAGS) -c $< -o $@

# Build test executable (linking directly with object file)
$(TEST_EXEC): $(TEST_SRC) $(LIB_OBJ)
	$(CC) $(CFLAGS) -o $@ $(TEST_SRC) $(LIB_OBJ) $(LDFLAGS)
	@echo "Test executable built: $(TEST_EXEC)"

# Alternative: Build test using the static library
test_with_lib: $(TEST_SRC) $(LIB)
	$(CC) $(CFLAGS) -o $(TEST_EXEC) $(TEST_SRC) -L. -lavlheap $(LDFLAGS)

# Build library only
lib: $(LIB)

# Build and run tests
test: $(TEST_EXEC)
	@echo ""
	@echo "Running tests..."
	@echo "================"
	./$(TEST_EXEC)

# Clean build artifacts
clean:
	rm -f $(LIB_OBJ) $(LIB) $(TEST_EXEC)
	@echo "Cleaned build artifacts"

# Phony targets
.PHONY: all lib test clean test_with_lib

# Help target
help:
	@echo "AVL Heap Library Build System"
	@echo "============================="
	@echo ""
	@echo "Targets:"
	@echo "  make          - Build library and tests"
	@echo "  make lib      - Build static library only"
	@echo "  make test     - Build and run tests"
	@echo "  make clean    - Remove build artifacts"
	@echo ""
	@echo "Files:"
	@echo "  Library:      $(LIB)"
	@echo "  Test:         $(TEST_EXEC)"
	@echo "  Header:       $(HEADERS)"
