# Bantam (C++20 port) — POSIX-compatible Makefile.
# Targets: Linux, FreeBSD, macOS, Haiku (any POSIX make: bmake, gmake, smake).
# Dependencies: libcurl and GNU readline (found via standard include/lib
# paths) for HTTP and interactive line editing. JSON is handled natively in
# json.cpp (no extra or vendored dependency).
# If your headers/libs live in a non-standard prefix, override, e.g.:
#   make CPPFLAGS="-I/opt/include" LDLIBS="-L/opt/lib -lcurl -lreadline"
#
# 32-bit build: make 32bit
# Or: make CXXFLAGS="-std=c++20 -O2 -m32" LDFLAGS="-m32"
# Large file support on 32-bit: make CPPFLAGS="-D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE"

CXX = c++
STRIP = strip
CXXFLAGS = -std=c++20 -Wall -Wextra -Wpedantic -O2 -march=native -D_POSIX_C_SOURCE=200809L -D_DEFAULT_SOURCE
CPPFLAGS = -I/usr/local/include -I. -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE -D_XOPEN_SOURCE=700 -D_DARWIN_C_SOURCE
LDFLAGS =
LDLIBS = -L/usr/local/lib -lcurl -lreadline

# Location of the AddressSanitizer/UBSan runtime libraries plus a replacement
# libasan_preinit.o (so the runtime initializes before main()). On a normal
# system these ship with the compiler; override with
#   make debug ASANDIR=  (empty)  — the gcc driver finds them automatically.
ASANDIR = /tmp/asanlib

OBJS = main.o config.o util.o json.o llm.o tools.o session.o render.o editor.o

bantam: $(OBJS)
	$(CXX) $(CXXFLAGS) $(CPPFLAGS) $(LDFLAGS) -o bantam $(OBJS) $(LDLIBS)
	$(STRIP) bantam

main.o: main.cpp bantam.hpp
	$(CXX) $(CXXFLAGS) $(CPPFLAGS) -c main.cpp

config.o: config.cpp bantam.hpp
	$(CXX) $(CXXFLAGS) $(CPPFLAGS) -c config.cpp

util.o: util.cpp bantam.hpp
	$(CXX) $(CXXFLAGS) $(CPPFLAGS) -c util.cpp

json.o: json.cpp bantam.hpp
	$(CXX) $(CXXFLAGS) $(CPPFLAGS) -c json.cpp

llm.o: llm.cpp bantam.hpp
	$(CXX) $(CXXFLAGS) $(CPPFLAGS) -c llm.cpp

tools.o: tools.cpp bantam.hpp
	$(CXX) $(CXXFLAGS) $(CPPFLAGS) -c tools.cpp

session.o: session.cpp bantam.hpp
	$(CXX) $(CXXFLAGS) $(CPPFLAGS) -c session.cpp

render.o: render.cpp bantam.hpp
	$(CXX) $(CXXFLAGS) $(CPPFLAGS) -c render.cpp

editor.o: editor.cpp bantam.hpp
	$(CXX) $(CXXFLAGS) $(CPPFLAGS) -c editor.cpp

clean:
	rm -f $(OBJS) bantam bantam_asan

install: bantam
	install -m 0755 bantam $(DESTDIR)/usr/local/bin/bantam

# Debug build with AddressSanitizer + UndefinedBehaviorSanitizer.
# Rebuilds ./bantam — run `make clean && make` afterwards to restore the
# optimized build. ASANDIR points the gcc driver (-B) at the runtime libs and
# the replacement libasan_preinit.o, and sets an rpath so they load at run time.
debug:
	$(MAKE) CXXFLAGS="-std=c++20 -Wall -Wextra -Wpedantic -D_POSIX_C_SOURCE=200809L -D_DEFAULT_SOURCE -g -O0 -fsanitize=address,undefined -B$(ASANDIR) -Wl,-rpath,$(ASANDIR)" LDFLAGS="" STRIP=":" bantam

# 32-bit build target
# Usage: make 32bit
# This builds a 32-bit binary with large file support enabled.
32bit:
	$(MAKE) CXXFLAGS="$(CXXFLAGS) -m32" LDFLAGS="$(LDFLAGS) -m32" bantam

.PHONY: clean install debug 32bit
