SRCDIR := src
INCDIR := include
OBJDIR := obj
BINDIR := bin

# Core compiler config: we favor strict standards and high warnings for C11
CC := clang
CFLAGS := -std=c11 -Wall -Wextra -Wpedantic -Werror \
          -Wshadow -Wconversion -Wdouble-promotion \
          -Wformat=2 -Wundef -fno-common -I$(INCDIR)

TARGET := $(BINDIR)/ascii3d

SRCS := $(wildcard $(SRCDIR)/*.c)
OBJS := $(SRCS:$(SRCDIR)/%.c=$(OBJDIR)/%.o)
DEPS := $(OBJS:.o=.d)

# Linking libm for math logic
LDFLAGS := -lm

.PHONY: all debug release clean install uninstall help tui

all: release

# Standard LTO and extreme optimization flags for our main build
release: CFLAGS += -O3 -DNDEBUG -march=native -flto
release: LDFLAGS += -flto
release: $(TARGET)

# Build configuration suitable for gdb integration and memory sanity checking
debug: CFLAGS += -O0 -g3 -DDEBUG -fsanitize=address,undefined
debug: LDFLAGS += -fsanitize=address,undefined
debug: $(TARGET)

profile: CFLAGS += -O2 -g -pg
profile: LDFLAGS += -pg
profile: $(TARGET)

$(OBJDIR) $(BINDIR):
	@mkdir -p $@

$(TARGET): $(OBJS) | $(BINDIR)
	@echo "Linking $@..."
	@$(CC) $(OBJS) -o $@ $(LDFLAGS)
	@echo "Build complete: $@"

$(OBJDIR)/%.o: $(SRCDIR)/%.c | $(OBJDIR)
	@echo "Compiling $<..."
	@$(CC) $(CFLAGS) -MMD -MP -c $< -o $@

-include $(DEPS)

clean:
	@echo "Cleaning artifacts..."
	@rm -rf $(OBJDIR) $(BINDIR)

PREFIX ?= /usr/local
install: release
	@echo "Deploying to $(PREFIX)/bin..."
	@install -d $(PREFIX)/bin
	@install -m 755 $(TARGET) $(PREFIX)/bin/

uninstall:
	@rm -f $(PREFIX)/bin/ascii3d
	@echo "Removed $(PREFIX)/bin/ascii3d."

run: release
	@./$(TARGET)

demo: release
	@./$(TARGET) -a HELLO

analyze:
	@cppcheck --enable=all --std=c11 -I$(INCDIR) $(SRCDIR)/*.c

format:
	@clang-format -i $(SRCDIR)/*.c $(INCDIR)/*.h

help:
	@echo "ASCII 3D Renderer - Build System"
	@echo "================================"
	@echo "Targets: all (default), release, debug, profile, clean, install, uninstall, run, demo, analyze, format"
