PROJECT_NAME := rt
VERSION := 1.0.0
PREFIX ?= /usr/local
BUILDDIR := build
MESON := meson
NINJA := ninja

BUILD_TYPE ?= release
MESON_OPTS := --buildtype=$(BUILD_TYPE)

ifeq ($(BUILD_TYPE),debug)
	MESON_OPTS += -Denable_debug_logging=true
endif

SOURCES := $(wildcard src/*.c)
HEADERS := $(wildcard src/*.h)

.PHONY: all build setup clean distclean install uninstall run debug release
.PHONY: check test lint format help dist package deps

all: build

setup: $(BUILDDIR)/build.ninja

$(BUILDDIR)/build.ninja: meson.build meson_options.txt
	@echo "==> Configuring build system..."
	@$(MESON) setup $(BUILDDIR) --prefix=$(PREFIX) $(MESON_OPTS) --wipe 2>/dev/null || \
		$(MESON) setup $(BUILDDIR) --prefix=$(PREFIX) $(MESON_OPTS)

build: setup
	@echo "==> Building $(PROJECT_NAME)..."
	@$(MESON) compile -C $(BUILDDIR)
	@echo "==> Build complete: $(BUILDDIR)/$(PROJECT_NAME)"

release:
	@$(MAKE) BUILD_TYPE=release build

debug:
	@$(MAKE) BUILD_TYPE=debug build

run: build
	@echo "==> Running $(PROJECT_NAME)..."
	@$(BUILDDIR)/$(PROJECT_NAME)

install: build
	@echo "==> Installing $(PROJECT_NAME) to $(PREFIX)..."
	@$(MESON) install -C $(BUILDDIR)
	@echo "==> Installation complete"

uninstall:
	@echo "==> Uninstalling $(PROJECT_NAME)..."
	@if [ -f $(BUILDDIR)/meson-logs/install-log.txt ]; then \
		cat $(BUILDDIR)/meson-logs/install-log.txt | xargs rm -f; \
		echo "==> Uninstallation complete"; \
	else \
		echo "==> No installation log found"; \
	fi

clean:
	@echo "==> Cleaning build artifacts..."
	@if [ -d $(BUILDDIR) ]; then \
		$(MESON) compile -C $(BUILDDIR) --clean 2>/dev/null || true; \
	fi
	@echo "==> Clean complete"

distclean:
	@echo "==> Removing build directory..."
	@rm -rf $(BUILDDIR)
	@echo "==> Distclean complete"

rebuild: distclean build

check: build
	@echo "==> Running checks..."
	@if command -v cppcheck >/dev/null 2>&1; then \
		cppcheck --enable=all --suppress=missingIncludeSystem \
			--suppress=unusedFunction --error-exitcode=1 src/; \
	else \
		echo "==> cppcheck not found, skipping static analysis"; \
	fi

test: build
	@echo "==> Running tests..."
	@if [ -f $(BUILDDIR)/test_runner ]; then \
		$(BUILDDIR)/test_runner; \
	else \
		echo "==> No tests configured"; \
	fi

lint: $(SOURCES) $(HEADERS)
	@echo "==> Linting source files..."
	@if command -v clang-tidy >/dev/null 2>&1; then \
		clang-tidy $(SOURCES) -- -I/usr/include/gtk-4.0 \
			-I/usr/include/glib-2.0 -I/usr/include/pango-1.0 \
			-I/usr/include/vte-2.91-gtk4 \
			$$(pkg-config --cflags gtk4 vte-2.91-gtk4 2>/dev/null); \
	else \
		echo "==> clang-tidy not found, skipping lint"; \
	fi

format:
	@echo "==> Formatting source files..."
	@if command -v clang-format >/dev/null 2>&1; then \
		clang-format -i $(SOURCES) $(HEADERS); \
		echo "==> Formatting complete"; \
	else \
		echo "==> clang-format not found"; \
	fi

format-check:
	@echo "==> Checking code formatting..."
	@if command -v clang-format >/dev/null 2>&1; then \
		clang-format --dry-run --Werror $(SOURCES) $(HEADERS); \
	else \
		echo "==> clang-format not found"; \
	fi

deps:
	@echo "==> Checking dependencies..."
	@echo "Required packages:"
	@echo "  - gtk4 >= 4.10"
	@echo "  - vte-2.91-gtk4 >= 0.76"
	@echo "  - freetype2 >= 2.10"
	@echo "  - pango >= 1.50"
	@echo "  - cairo >= 1.16"
	@echo ""
	@echo "Debian/Ubuntu:"
	@echo "  sudo apt install libgtk-4-dev libvte-2.91-gtk4-dev \\"
	@echo "    libfreetype-dev libpango1.0-dev libcairo2-dev meson ninja-build"
	@echo ""
	@echo "Fedora:"
	@echo "  sudo dnf install gtk4-devel vte291-gtk4-devel \\"
	@echo "    freetype-devel pango-devel cairo-devel meson ninja-build"
	@echo ""
	@echo "Arch:"
	@echo "  sudo pacman -S gtk4 vte4 freetype2 pango cairo meson ninja"
	@echo ""
	@echo "==> Verifying installed dependencies..."
	@pkg-config --exists gtk4 && echo "  [OK] gtk4" || echo "  [MISSING] gtk4"
	@pkg-config --exists vte-2.91-gtk4 && echo "  [OK] vte-2.91-gtk4" || echo "  [MISSING] vte-2.91-gtk4"
	@pkg-config --exists freetype2 && echo "  [OK] freetype2" || echo "  [MISSING] freetype2"
	@pkg-config --exists pango && echo "  [OK] pango" || echo "  [MISSING] pango"
	@pkg-config --exists cairo && echo "  [OK] cairo" || echo "  [MISSING] cairo"

dist: distclean
	@echo "==> Creating distribution archive..."
	@mkdir -p dist
	@tar --transform 's,^,$(PROJECT_NAME)-$(VERSION)/,' \
		-czvf dist/$(PROJECT_NAME)-$(VERSION).tar.gz \
		--exclude='dist' --exclude='.git' --exclude='build' \
		--exclude='*.o' --exclude='*~' \
		Makefile meson.build meson_options.txt README.md LICENSE \
		src/ data/ config/
	@echo "==> Created dist/$(PROJECT_NAME)-$(VERSION).tar.gz"

package-deb: build
	@echo "==> Creating Debian package..."
	@mkdir -p pkg/DEBIAN pkg/usr/bin pkg/usr/share/applications pkg/usr/share/icons/hicolor/scalable/apps
	@cp $(BUILDDIR)/$(PROJECT_NAME) pkg/usr/bin/
	@cp data/rt.desktop pkg/usr/share/applications/
	@cp data/rt.svg pkg/usr/share/icons/hicolor/scalable/apps/
	@echo "Package: $(PROJECT_NAME)" > pkg/DEBIAN/control
	@echo "Version: $(VERSION)" >> pkg/DEBIAN/control
	@echo "Section: x11" >> pkg/DEBIAN/control
	@echo "Priority: optional" >> pkg/DEBIAN/control
	@echo "Architecture: amd64" >> pkg/DEBIAN/control
	@echo "Depends: libgtk-4-1, libvte-2.91-gtk4-0" >> pkg/DEBIAN/control
	@echo "Maintainer: RT Terminal <rt@example.com>" >> pkg/DEBIAN/control
	@echo "Description: Fast enterprise-grade terminal emulator" >> pkg/DEBIAN/control
	@echo " RT is a terminal emulator with excellent text rendering," >> pkg/DEBIAN/control
	@echo " high-DPI support, and full ANSI escape sequence handling." >> pkg/DEBIAN/control
	@dpkg-deb --build pkg $(PROJECT_NAME)_$(VERSION)_amd64.deb
	@rm -rf pkg
	@echo "==> Created $(PROJECT_NAME)_$(VERSION)_amd64.deb"

valgrind: debug
	@echo "==> Running with Valgrind..."
	@valgrind --leak-check=full --show-leak-kinds=all \
		--track-origins=yes --verbose \
		$(BUILDDIR)/$(PROJECT_NAME) 2>&1 | tee valgrind.log

sanitize:
	@echo "==> Building with AddressSanitizer..."
	@CFLAGS="-fsanitize=address -fno-omit-frame-pointer" \
		$(MAKE) BUILD_TYPE=debug distclean build

size: build
	@echo "==> Binary size analysis..."
	@size $(BUILDDIR)/$(PROJECT_NAME)
	@echo ""
	@ls -lh $(BUILDDIR)/$(PROJECT_NAME)

strip: build
	@echo "==> Stripping debug symbols..."
	@strip $(BUILDDIR)/$(PROJECT_NAME)
	@ls -lh $(BUILDDIR)/$(PROJECT_NAME)

loc:
	@echo "==> Lines of code..."
	@if command -v cloc >/dev/null 2>&1; then \
		cloc src/ --by-file; \
	else \
		wc -l $(SOURCES) $(HEADERS) | tail -1; \
	fi

help:
	@echo "$(PROJECT_NAME) v$(VERSION) - Build System"
	@echo ""
	@echo "Usage: make [target] [OPTIONS]"
	@echo ""
	@echo "Build targets:"
	@echo "  all          Build the project (default)"
	@echo "  build        Build with current settings"
	@echo "  release      Build optimized release version"
	@echo "  debug        Build with debug symbols"
	@echo "  rebuild      Clean and rebuild"
	@echo ""
	@echo "Run targets:"
	@echo "  run          Build and run the application"
	@echo "  valgrind     Run with memory leak detection"
	@echo ""
	@echo "Install targets:"
	@echo "  install      Install to PREFIX (default: /usr/local)"
	@echo "  uninstall    Remove installed files"
	@echo ""
	@echo "Clean targets:"
	@echo "  clean        Remove build artifacts"
	@echo "  distclean    Remove build directory entirely"
	@echo ""
	@echo "Quality targets:"
	@echo "  check        Run static analysis (cppcheck)"
	@echo "  lint         Run linter (clang-tidy)"
	@echo "  test         Run test suite"
	@echo "  format       Format source code (clang-format)"
	@echo "  format-check Check code formatting"
	@echo "  sanitize     Build with AddressSanitizer"
	@echo ""
	@echo "Package targets:"
	@echo "  dist         Create source distribution tarball"
	@echo "  package-deb  Create Debian package"
	@echo ""
	@echo "Info targets:"
	@echo "  deps         Show and check dependencies"
	@echo "  size         Show binary size"
	@echo "  strip        Strip debug symbols from binary"
	@echo "  loc          Count lines of code"
	@echo "  help         Show this help"
	@echo ""
	@echo "Options:"
	@echo "  PREFIX=/path     Installation prefix (default: /usr/local)"
	@echo "  BUILD_TYPE=type  Build type: release|debug (default: release)"
	@echo ""
	@echo "Examples:"
	@echo "  make                      # Build release version"
	@echo "  make debug run            # Build debug and run"
	@echo "  make PREFIX=/usr install  # Install to /usr"
	@echo "  make BUILD_TYPE=debug     # Build debug version"
