# Makefile for uni-json examples
#
# Copyright (C) 2025 VDev Project
# MIT-licensed.

# Programs
CC := gcc
CFLAGS := -Wall -Wextra -g -O2 -I../include

# Directories
UNI_JSON_DIR := ..
BUILD_DIR := build

# Files
SIMPLE_SRC := simple.c
CBINDINGS_SRC := c_bindings.c
SIMPLE_OBJ := $(BUILD_DIR)/simple.o
CBINDINGS_OBJ := $(BUILD_DIR)/c_bindings.o
SIMPLE_TARGET := $(BUILD_DIR)/simple

# Find uni-json library
UNI_JSON_LIB := $(UNI_JSON_DIR)/bin/libuni-json.a
UNI_JSON_SO := $(UNI_JSON_DIR)/bin/libuni-json.so

.PHONY: all clean

all: $(SIMPLE_TARGET)

# Create build directory
$(BUILD_DIR):
	mkdir -p $@

# Build uni-json library if needed
$(UNI_JSON_LIB):
	$(MAKE) -C $(UNI_JSON_DIR) bin/libuni-json.a

# Compile C bindings
$(CBINDINGS_OBJ): $(CBINDINGS_SRC) | $(BUILD_DIR)
	$(CC) $(CFLAGS) -c $< -o $@

# Compile simple example
$(SIMPLE_OBJ): $(SIMPLE_SRC) | $(BUILD_DIR)
	$(CC) $(CFLAGS) -c $< -o $@

# Link final executable
$(SIMPLE_TARGET): $(SIMPLE_OBJ) $(CBINDINGS_OBJ) $(UNI_JSON_LIB) | $(BUILD_DIR)
	$(CC) $(CFLAGS) -o $@ $(SIMPLE_OBJ) $(CBINDINGS_OBJ) $(UNI_JSON_LIB) -lm

# Alternative: Use shared library
$(SIMPLE_TARGET)-shared: $(SIMPLE_OBJ) $(CBINDINGS_OBJ) $(UNI_JSON_SO) | $(BUILD_DIR)
	$(CC) $(CFLAGS) -o $@ $(SIMPLE_OBJ) $(CBINDINGS_OBJ) -L$(UNI_JSON_DIR)/bin -luni-json -lm

clean:
	rm -rf $(BUILD_DIR)

# Run the example
run: $(SIMPLE_TARGET)
	./$(SIMPLE_TARGET)

# Install dependencies (build uni-json library)
deps:
	$(MAKE) -C $(UNI_JSON_DIR) bin/libuni-json.a

help:
	@echo "Available targets:"
	@echo "  all          - Build the simple example"
	@echo "  clean        - Remove build files"
	@echo "  run          - Build and run the example"
	@echo "  deps         - Build uni-json library dependency"
	@echo "  help         - Show this help message"
