CXX ?= g++
CXXSTD = -std=c++23
WARN = -Wall -Wextra
CXXFLAGS ?= $(CXXSTD) $(WARN) -O2 -I../../moloapp/src
BUILD = build
VERSION = $(shell cat VERSION)
BIN = $(BUILD)/detz
GEN_INC = $(BUILD)/gen
VERSION_HPP = $(GEN_INC)/version.hpp
ALL_SRCS = $(shell find src -name '*.cpp')
ALL_OBJS = $(patsubst %.cpp,$(BUILD)/%.o,$(ALL_SRCS))
MAIN_SRC = main.cpp
MAIN_OBJ = $(BUILD)/main.o

all: $(BIN)

$(VERSION_HPP): VERSION
	@mkdir -p $(GEN_INC)
	@sed 's/@VERSION@/$(VERSION)/' src/cli/version.hpp.in > $@

$(BUILD)/%.o: %.cpp $(VERSION_HPP)
	@mkdir -p $(dir $@)
	$(CXX) $(CXXFLAGS) -I$(GEN_INC) $(foreach d,$(shell find src -type d),-I$d) -c $< -o $@

$(BUILD)/main.o: main.cpp $(VERSION_HPP)
	@mkdir -p $(BUILD)
	$(CXX) $(CXXFLAGS) -I$(GEN_INC) $(foreach d,$(shell find src -type d),-I$d) -c main.cpp -o $@

$(BIN): $(MAIN_OBJ) $(ALL_OBJS)
	$(CXX) $(CXXFLAGS) $(MAIN_OBJ) $(ALL_OBJS) -lsqlite3 -lcurl -o $@

static: $(MAIN_OBJ) $(ALL_OBJS)
	$(CXX) $(CXXFLAGS) -pthread -static $(MAIN_OBJ) $(ALL_OBJS) third_party/curl/libcurl.a third_party/sqlite/libsqlite3.a -lssl -lcrypto third_party/jitterentropy/libjitterentropy.a -lzstd -lz -lnghttp2 -lpsl -lbrotlidec -lidn2 -lrtmp -o build/detz-static
$(BUILD)/store_test: tests/store_test.cpp src/store/store.cpp
	@mkdir -p $(BUILD)
	$(CXX) $(CXXFLAGS) -Isrc/store tests/store_test.cpp src/store/store.cpp -lsqlite3 -lcurl -o $@

$(BUILD)/detz_test: tests/test_main.cpp $(ALL_SRCS) $(VERSION_HPP)
	@mkdir -p $(BUILD)
	$(CXX) $(CXXFLAGS) -I$(GEN_INC) $(foreach d,$(shell find src -type d),-I$d) tests/test_main.cpp $(ALL_SRCS) -lsqlite3 -lcurl -o $@

lint:
	$(CXX) $(CXXSTD) $(WARN) -Werror -fsyntax-only main.cpp -I$(GEN_INC) $(foreach d,$(shell find src -type d),-I$d) || true

version-bump:
	tools/version-bump.sh $(PART)

changelog:
	tools/changelog.sh "$(MSG)"

tag:
	tools/tag.sh

release:
	PART=$(PART) MSG="$(MSG)" tools/release.sh

release-dry:
	PART=$(PART) MSG="$(MSG)" sh -n tools/release.sh && echo "release dry-run OK"

docs:
	@test -f README.md && test -f SPEC.md && test -f workflow.md && test -f versioning.md && test -f docs/agent.md && test -f docs/tui.md && test -f docs/mcp.md && test -f docs/cap.md && echo "docs OK"

clean:
	rm -rf $(BUILD)

-include src/*/*.mk
