# Compiler
CC = x86_64-w64-mingw32-gcc

# Base flags
CFLAGS = -Wall -w -IInclude
LFLAGS = -liphlpapi -lnetapi32 -lwininet -lws2_32 -lwinhttp -lbcrypt -lgdi32 -luser32 -lshlwapi -lversion -lcrypt32 -lncrypt -lole32 -lshell32 -lntdll -mwindows
LFLAGS_CONSOLE = -liphlpapi -lnetapi32 -lwininet -lws2_32 -lwinhttp -lbcrypt -lgdi32 -luser32 -lshlwapi -lversion -lcrypt32 -lncrypt -lole32 -lshell32 -lntdll

# Debug parameters (can be overridden from command line)
# DEBUG_LEVEL: none=0, errors=1, warnings=2, info=3, all=4
# DEBUG_OUTPUT: console=0, file=1
DEBUG_LEVEL ?= 0
DEBUG_OUTPUT ?= 0

# Convert DEBUG_LEVEL string to number if needed
ifeq ($(DEBUG_LEVEL),none)
    DEBUG_LEVEL_NUM = 0
else ifeq ($(DEBUG_LEVEL),errors)
    DEBUG_LEVEL_NUM = 1
else ifeq ($(DEBUG_LEVEL),warnings)
    DEBUG_LEVEL_NUM = 2
else ifeq ($(DEBUG_LEVEL),info)
    DEBUG_LEVEL_NUM = 3
else ifeq ($(DEBUG_LEVEL),all)
    DEBUG_LEVEL_NUM = 4
else
    # Assume it's already a number
    DEBUG_LEVEL_NUM = $(DEBUG_LEVEL)
endif

# Convert DEBUG_OUTPUT string to number if needed
ifeq ($(DEBUG_OUTPUT),console)
    DEBUG_OUTPUT_NUM = 0
else ifeq ($(DEBUG_OUTPUT),file)
    DEBUG_OUTPUT_NUM = 1
else
    # Assume it's already a number
    DEBUG_OUTPUT_NUM = $(DEBUG_OUTPUT)
endif

# Command enable flags (passed from builder.py)
COMMAND_FLAGS ?=

# Debug flags based on level
DEBUG_FLAGS = -DDEBUG_SOCKS -g
ifeq ($(DEBUG_LEVEL_NUM),0)
    # No debug
    DEBUG_FLAGS =
else
    # Debug enabled - add defines for debug level and output
    # DEBUG_LEVEL: 0=NONE, 1=ERR, 2=WRN, 3=INF, 4=ALL
    # DEBUG_OUTPUT: 0=CONSOLE, 1=FILE
    DEBUG_FLAGS += -DDEBUG_LEVEL=$(DEBUG_LEVEL_NUM)
    DEBUG_FLAGS += -DDEBUG_OUTPUT=$(DEBUG_OUTPUT_NUM)
endif

# Directories
SRC_FILES := *.c
BUILD_DIR = build

# Ensure build directory exists
$(shell mkdir -p $(BUILD_DIR))

# Build Targets
all: exe dll
debug: debug_exe debug_dll

exe: $(BUILD_DIR)/cazalla.exe
dll: $(BUILD_DIR)/cazalla.dll
debug_exe: $(BUILD_DIR)/cazalla-debug.exe
debug_dll: $(BUILD_DIR)/cazalla-debug.dll

# Executable Target
$(BUILD_DIR)/cazalla.exe: $(SRC_FILES)
	$(CC) $^ -o $@ $(CFLAGS) -s -D_EXE $(COMMAND_FLAGS) $(LFLAGS)

$(BUILD_DIR)/cazalla-debug.exe: $(SRC_FILES)
	$(CC) $^ -o $@ $(CFLAGS) -D_EXE $(COMMAND_FLAGS) $(LFLAGS_CONSOLE) $(DEBUG_FLAGS)

# DLL Target
$(BUILD_DIR)/cazalla.dll: $(SRC_FILES)
	$(CC) $^ -o $@ -shared -D_DLL $(CFLAGS) -s $(COMMAND_FLAGS) $(LFLAGS)

$(BUILD_DIR)/cazalla-debug.dll: $(SRC_FILES)
	$(CC) $^ -o $@ -shared -D_DLL $(CFLAGS) $(COMMAND_FLAGS) $(LFLAGS) $(DEBUG_FLAGS)

# Clean up
clean:
	rm -rf $(BUILD_DIR)
