# gui/Makefile — the Odin + raylib renderer (the interactive 3D universe map).
#
# This is the Odin sub-project. It is normally invoked from the repo root via
# `make run`, `make build`, etc. (which delegate here through the root
# Makefile), but it can also be driven directly with `make -C gui <target>`.
#
# `lib/` (third-party Odin deps) lives under `gui/lib`; the `bin/` / `build/`
# output dirs live at the repo root and are referenced through `$(ROOT)`.

ODIN         ?= odin
GDB          ?= gdb
ROOT         := ..
BIN          := $(ROOT)/bin
BINARY       := $(BIN)/desi_explorer
ODIN_FLAGS   := -collection:lib=lib/local
WASM_DEFINE  := RAYLIB_WASM_LIB=env.o

# Normalize GUI_ENV_FILE (given relative to the repo root) to an absolute path
# so the Odin process can open it regardless of its working directory.
# "override" is required because GUI_ENV_FILE is usually set on the command
# line (or passed as an env var to this sub-make), which would otherwise
# override any assignment made here.
ifdef GUI_ENV_FILE
ifneq ($(abspath $(GUI_ENV_FILE)),$(GUI_ENV_FILE))
override GUI_ENV_FILE := $(abspath $(ROOT)/$(GUI_ENV_FILE))
endif
endif
# "override" on a command-line variable silently drops it from the recipe
# environment; re-export it so the app can find its env file (run + gdb).
export GUI_ENV_FILE

.PHONY: help setup add-dep run build build-debug gdb build-web test clean fmt

help: ## List available targets
	@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | \
		awk 'BEGIN {FS = ":.*?## "}; {printf "  \033[36m%-18s\033[0m %s\n", $$1, $$2}'

setup: ## Prepare build environment (lib/local)
	@mkdir -p lib/local

add-dep: ## Add a dependency from Codeberg/GitHub/GitLab as a submodule (DEP=name)
ifndef DEP
	$(error Usage: make add-dep DEP=<dependency-name>)
endif
	@scripts/add_dep.sh "$(DEP)"

run: ## Run the native app
	@mkdir -p lib/local
	$(ODIN) run src $(ODIN_FLAGS)

build: ## Release build -> bin/desi_explorer
	@mkdir -p lib/local $(BIN)
	$(ODIN) build src $(ODIN_FLAGS) -o:speed -out:$(BINARY)

build-debug: ## Debug build -> bin/desi_explorer
	@mkdir -p lib/local $(BIN)
	$(ODIN) build src $(ODIN_FLAGS) -o:none -debug -out:$(BINARY)

gdb: build-debug ## Run the native app under gdb (type 'run', then 'bt' on a crash)
	$(GDB) -q --args $(BINARY) $(ARGS)

build-web: ## WebAssembly build -> build/web (needs emscripten)
	@scripts/build_web.sh

test: ## Run Odin unit tests
	@mkdir -p lib/local
	@if ls test/*.odin >/dev/null 2>&1; then \
		echo "== gui/test =="; \
		$(ODIN) test test $(ODIN_FLAGS); \
	fi
	@for dir in $$(find lib/local -name '*_test.odin' -exec dirname {} \; | sort -u); do \
		echo "== $$dir =="; \
		$(ODIN) test "$$dir" $(ODIN_FLAGS); \
	done

clean: ## Remove build artifacts
	rm -rf $(BIN) build

fmt: ## Format Odin sources with odinfmt
	odinfmt src
