# Mix env vars
ERL_CFLAGS ?= -I$(ERL_EI_INCLUDE_DIR)
ERL_LDFLAGS ?= -L$(ERL_EI_LIBDIR) -lei

# c-kzg-4844 paths
CKZG_ROOT = c_src/c-kzg-4844
CKZG_SRC = $(CKZG_ROOT)/src
BLST_ROOT = $(CKZG_ROOT)/blst

# We delegate blst build to its own script or build rules, 
# but a simple approach for NIFs is often to just include the blst .c files directly 
# or build it as a static lib first. c-kzg-4844 seems to expect libblst.a.

# Let's try to follow c-kzg-4844 Makefile's approach slightly but simplified for NIF:
# It defines CFLAGS and includes.

CFLAGS += -O3 -fPIC -Wall -Wextra -Wno-unused-parameter -Wno-missing-field-initializers
CFLAGS += -I$(ERL_EI_INCLUDE_DIR)
CFLAGS += -I$(CKZG_SRC) -I$(BLST_ROOT)/bindings

# BLST defines
CFLAGS += -D__BLST_PORTABLE__ 

# Sources
# In recent c-kzg versions, ckzg.c might include other files or be the main entry. 
# Duplicate symbols suggest we are compiling the same code twice.
# Let's try compiling only ckzg.c.

CKZG_SOURCES = \
	$(CKZG_SRC)/ckzg.c

NIF_SRC = c_src/kzg_nif.c

TYPE_SOURCES = $(CKZG_SOURCES) $(NIF_SRC)
OBJS = $(TYPE_SOURCES:.c=.o)

LIB = priv/kzg_nif.so
BLST_LIB = $(BLST_ROOT)/libblst.a

# Targets

all: $(BLST_LIB) $(LIB)

# Build BLST using its own build script if possible or makefile
# c-kzg-4844 usually has a rule to build blst.
$(BLST_LIB):
	@echo "Building BLST..."
	cd $(BLST_ROOT) && ./build.sh

# Linker flags
LDFLAGS += -shared

# macOS specific linker flags
ifeq ($(shell uname),Darwin)
	LDFLAGS += -undefined dynamic_lookup
endif

$(LIB): $(OBJS) $(BLST_LIB)
	@mkdir -p priv
	$(CC) $(ERL_LDFLAGS) $(LDFLAGS) -o $@ $(OBJS) $(BLST_LIB)

clean:
	rm -f $(LIB) $(OBJS)
	# cd $(CKZG_ROOT) && make clean
	cd $(BLST_ROOT) && rm -f libblst.a
