.PHONY: all build release debug install uninstall clean test check help ui

PREFIX ?= $(HOME)/.local
BINDIR ?= $(PREFIX)/bin

CARGO ?= cargo
CARGO_FLAGS ?=

# Check if Qt6 Qml is available for UI build
HAS_QT6_QML := $(shell pkg-config --exists Qt6Qml 2>/dev/null && echo yes || echo no)

all: release
ifeq ($(HAS_QT6_QML),yes)
all: ui
endif

build: release

release:
	$(CARGO) build --release $(CARGO_FLAGS)

debug:
	$(CARGO) build $(CARGO_FLAGS)

ui:
ifeq ($(HAS_QT6_QML),yes)
	@if [ ! -f ui/build/Makefile ]; then \
		cmake -S ui -B ui/build -DCMAKE_BUILD_TYPE=Release; \
	fi
	cmake --build ui/build -j
else
	@echo "Skipping UI build: Qt6 Qml not found"
endif

install: all
	install -d $(BINDIR)
	install -m 755 target/release/ork $(BINDIR)/ork
	install -m 755 target/release/ork-server $(BINDIR)/ork-server
ifeq ($(HAS_QT6_QML),yes)
	install -m 755 ui/build/bin/orkmode $(BINDIR)/orkmode
endif

uninstall:
	rm -f $(BINDIR)/ork
	rm -f $(BINDIR)/ork-server
	rm -f $(BINDIR)/orkmode

clean:
	$(CARGO) clean
	rm -rf ui/build

test:
	$(CARGO) test $(CARGO_FLAGS)

check:
	$(CARGO) check $(CARGO_FLAGS)
	$(CARGO) clippy $(CARGO_FLAGS) -- -D warnings

fmt:
	$(CARGO) fmt

fmt-check:
	$(CARGO) fmt -- --check

help:
	@echo "orkmode - org-mode implementation (CLI + server + GUI)"
	@echo ""
	@echo "Targets:"
	@echo "  all                  Build release (+ ui if Qt6 available)"
	@echo "  release              Build Rust binaries (ork, ork-server)"
	@echo "  ui                   Build Qt6/QML GUI (orkmode) [requires Qt6]"
	@echo "  debug                Build debug Rust binaries"
	@echo "  install              Install binaries to $(BINDIR)"
	@echo "  uninstall            Remove from $(BINDIR)"
	@echo "  clean                Remove build artifacts"
	@echo "  test                 Run tests"
	@echo "  check                Run cargo check and clippy"
	@echo "  fmt                  Format code"
	@echo "  fmt-check            Check formatting"
	@echo ""
	@echo "Variables:"
	@echo "  PREFIX               Installation prefix (default: ~/.local)"
	@echo "  CARGO                Cargo command (default: cargo)"
	@echo ""
	@echo "Requirements:"
	@echo "  Rust 1.70+, C compiler (tree-sitter)"
	@echo "  Qt 6.3+, CMake 3.21+ (optional, for ui target)"
	@echo ""
	@echo "Qt6 Qml detected: $(HAS_QT6_QML)"
