CC ?= gcc
CFLAGS ?= -std=c11 -Wall -Wextra -O2 -g
SD_DIR := vendor/sashidown
CPPFLAGS += -Iinclude -I$(SD_DIR)/include -D_XOPEN_SOURCE_EXTENDED
LDFLAGS += -L$(SD_DIR)
LDLIBS += -lsashidown -lm -lcurl -lncursesw -lpthread

SRC = \
	src/ctl_parse.c \
	src/os_compat.c \
	src/sandbox.c \
	src/session.c \
	src/tools/tools.c \
	src/llm_openai.c \
	src/agent_loop.c \
	src/agent_store.c \
	src/json_baseline.c \
	src/creds.c \
	src/mm_tool.c \
	src/models.c \
	src/tui.c \
	src/main.c

OBJ = $(SRC:.c=.o)

.PHONY: all clean check demo sashidown-lib cmake-gcc cmake-clang

all: sashidown-lib cst-agent

# Optional CMake entrypoints (same sources)
cmake-gcc:
	cmake -B build-gcc -DCMAKE_C_COMPILER=gcc -DCST_BUILD_TUI=ON
	cmake --build build-gcc
	ctest --test-dir build-gcc --output-on-failure

cmake-clang:
	cmake -B build-clang -DCMAKE_C_COMPILER=clang -DCST_BUILD_TUI=ON
	cmake --build build-clang

sashidown-lib:
	$(MAKE) -C $(SD_DIR) libsashidown.a

cst-agent: $(OBJ) $(SD_DIR)/libsashidown.a
	$(CC) $(CFLAGS) -o $@ $(OBJ) $(LDFLAGS) $(LDLIBS)

src/%.o: src/%.c include/ctl.h include/cst_agent.h
	$(CC) $(CFLAGS) $(CPPFLAGS) -c -o $@ $<

src/tools/%.o: src/tools/%.c include/ctl.h include/cst_agent.h
	$(CC) $(CFLAGS) $(CPPFLAGS) -c -o $@ $<

src/tui.o: src/tui.c include/cst_agent.h $(SD_DIR)/include/sashidown.h
	$(CC) $(CFLAGS) $(CPPFLAGS) -c -o $@ $<

tests/test_ctl_frontier: tests/test_ctl_frontier.c src/ctl_parse.c include/ctl.h
	$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ tests/test_ctl_frontier.c src/ctl_parse.c

tests/test_json_baseline: tests/test_json_baseline.c src/json_baseline.c include/cst_agent.h
	$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ tests/test_json_baseline.c src/json_baseline.c

tests/test_replay_starvation: tests/test_replay_starvation.c src/ctl_parse.c src/json_baseline.c
	$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ tests/test_replay_starvation.c src/ctl_parse.c src/json_baseline.c

tests/test_mm_tool: tests/test_mm_tool.c src/mm_tool.c include/mm_tool.h
	$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ tests/test_mm_tool.c src/mm_tool.c

check: tests/test_ctl_frontier tests/test_json_baseline tests/test_replay_starvation tests/test_mm_tool
	./tests/test_ctl_frontier
	./tests/test_json_baseline
	./tests/test_replay_starvation
	./tests/test_mm_tool

demo: cst-agent
	./cst-agent --demo-ctl --workspace .

clean:
	rm -f $(OBJ) cst-agent tests/test_ctl_frontier tests/test_json_baseline tests/test_replay_starvation tests/test_mm_tool
