CXX = g++
CXXFLAGS = -std=c++17 -Wall -Wextra -O2
LDFLAGS = -lssl -lcrypto -lpthread -lutil

TARGET = ptyhost
SOURCES = main.cpp

# Check if -m64 is supported
M64_SUPPORTED := $(shell $(CXX) -m64 -E - </dev/null >/dev/null 2>&1 && echo yes)

# Detect architecture
ARCH := $(shell uname -m)

# Architecture-specific flags
ifeq ($(findstring x86_64,$(ARCH)),x86_64)
    # x86_64 architecture
    AMD64_CXXFLAGS = -march=x86-64
    AMD64_TARGET_NAME = $(TARGET).amd64
else ifeq ($(findstring arm,$(ARCH)),arm)
    # ARM architecture
    ARM_CXXFLAGS = -march=native
    AMD64_TARGET_NAME = $(TARGET).arm64
else
    # Default to native architecture
    AMD64_CXXFLAGS = -march=native
    AMD64_TARGET_NAME = $(TARGET).$(ARCH)
endif

# Check if websocketpp is available via pkg-config
WEBSOCKETPP_AVAILABLE := $(shell pkg-config --exists websocketpp 2>/dev/null && echo yes)

ifeq ($(WEBSOCKETPP_AVAILABLE),yes)
    CXXFLAGS += $(shell pkg-config --cflags websocketpp)
else
    # Fallback: assume headers are in standard locations
    CXXFLAGS += -I/usr/include/websocketpp -I/usr/local/include/websocketpp
endif

# Check for nlohmann/json
JSON_AVAILABLE := $(shell pkg-config --exists nlohmann_json 2>/dev/null && echo yes)

ifeq ($(JSON_AVAILABLE),yes)
    CXXFLAGS += $(shell pkg-config --cflags nlohmann_json)
else
    # Fallback: assume headers are in standard locations or use single header
    CXXFLAGS += -I/usr/include/nlohmann -I/usr/local/include/nlohmann
endif

$(TARGET): $(SOURCES)
	@echo "Building $(TARGET)..."
	@echo "Note: This requires websocketpp and nlohmann/json libraries"
	@echo "Install with: sudo apt-get install libwebsocketpp-dev nlohmann-json3-dev libssl-dev"
	$(CXX) $(CXXFLAGS) -o $@ $^ $(LDFLAGS)

# AMD64 specific target (name is kept for backward compatibility)
amd64: $(SOURCES)
	@echo "Building $(TARGET) optimized for current architecture..."
	$(CXX) $(CXXFLAGS) $(AMD64_CXXFLAGS) -o $(AMD64_TARGET_NAME) $^ $(LDFLAGS)

clean:
	rm -f $(TARGET) $(TARGET).amd64

install-deps:
	@echo "Installing dependencies..."
	sudo apt-get update
	sudo apt-get install -y libwebsocketpp-dev nlohmann-json3-dev libssl-dev build-essential

.PHONY: clean install-deps amd64