# Use Qt on PATH unless an SDK is explicitly selected.
# Override with: make run QT_HOME=/path/to/Qt/6.10.3/gcc_64
QT_HOME ?=
CARGO ?= cargo

ifneq ($(strip $(QT_HOME)),)
export PATH := $(QT_HOME)/bin:$(PATH)
export LD_LIBRARY_PATH := $(QT_HOME)/lib$(if $(LD_LIBRARY_PATH),:$(LD_LIBRARY_PATH))
endif

.DEFAULT_GOAL := run
.PHONY: run build release test test-core test-qml check help qt-check

run: qt-check
	$(CARGO) run --locked

build: qt-check
	$(CARGO) build --locked

release: qt-check
	$(CARGO) build --locked --release

test: qt-check
	$(CARGO) test --locked

test-core:
	$(CARGO) test --locked --no-default-features

test-qml: qt-check
	QT_QPA_PLATFORM=offscreen QT_QUICK_BACKEND=software qmltestrunner -input tests/qml -import tests/imports

check: qt-check
	$(CARGO) clippy --locked --all-targets -- -D warnings
	$(CARGO) fmt --check

qt-check:
	@if [ -n "$(QT_HOME)" ] && [ ! -x "$(QT_HOME)/bin/qmake" ]; then \
		printf '%s\n' "No qmake found under QT_HOME=$(QT_HOME). Select a Qt 6.10+ SDK." >&2; \
		exit 1; \
	fi
	@command -v qmake >/dev/null || { \
		printf '%s\n' 'Qt 6.10+ is required. Use make run QT_HOME=/path/to/Qt/6.10.3/gcc_64.' >&2; \
		exit 1; \
	}
	@version=$$(qmake -query QT_VERSION) && \
		printf '%s\n' "$$version" | awk -F. '{ exit !($$1 == 6 && $$2 >= 10) }' || { \
		printf '%s\n' "Qt 6.10+ is required; detected '$$version'. Set QT_HOME to a compatible SDK." >&2; \
		exit 1; \
	}

help:
	@printf '%s\n' \
		'make run        Build and launch the native UI (default)' \
		'make build      Build the debug executable' \
		'make release    Build the release executable' \
		'make test       Run Rust and native startup tests' \
		'make test-core  Run Qt-independent Rust tests' \
		'make test-qml   Run offscreen QML interaction tests' \
		'make check      Run Clippy and formatting checks' \
		'Override SDK: make run QT_HOME=/path/to/Qt/6.10.3/gcc_64' \
		'Use Qt on PATH: make run QT_HOME='
