SHELL := /bin/bash
.PHONY: build serve clone-kernel clone-engine clone-wasm clone-web clone-viewer

# ══ The public BIMR repositories ══
# The forge hosting them — switch here (e.g. the official release lives at
# https://gitaec.org/rvba).
FORGE              := https://gitaec.org/rvba

BIMR_KERNEL        := bimr-kernel
BIMR_KERNEL_REMOTE := $(FORGE)/bimr-kernel.git
BIMR_ENGINE        := bimr-engine
BIMR_ENGINE_REMOTE := $(FORGE)/bimr-engine.git
BIMR_WASM          := bimr-wasm
BIMR_WASM_REMOTE   := $(FORGE)/bimr-wasm.git
BIMR_WEB           := bimr-web
BIMR_WEB_REMOTE    := $(FORGE)/bimr-web.git
IFC5_SRC           := bimr-viewer-ifcx/src
IFC5_REMOTE        := $(FORGE)/bimr-viewer-ifcx.git
IFC5_BRANCH        := bimr

# Prerequisites: Rust (with the wasm32 target), Node.js + pnpm on PATH,
# wasm-bindgen CLI and wasm-opt.
WASM_BINDGEN       := $(HOME)/.cargo/bin/wasm-bindgen
WASM_OPT           := $(shell command -v wasm-opt 2>/dev/null || ls -d $(HOME)/.cache/.wasm-pack/wasm-opt-*/bin/wasm-opt 2>/dev/null | head -1)
WASM_BINDGEN_VERSION := 0.2.114

build: clone-kernel clone-engine clone-wasm clone-web clone-viewer
	cargo build --release --manifest-path $(BIMR_ENGINE)/Cargo.toml
	@test -f $(WASM_BINDGEN) || cargo install wasm-bindgen-cli --version $(WASM_BINDGEN_VERSION)
	@test -n "$(WASM_OPT)" || (echo "wasm-opt not found — see bimr-factory Makefile install-wasm-opt" >&2; exit 1)
	cargo build --release --target wasm32-unknown-unknown --manifest-path $(BIMR_WASM)/Cargo.toml
	$(WASM_BINDGEN) --target web --out-dir $(BIMR_WASM)/pkg \
		$(BIMR_WASM)/target/wasm32-unknown-unknown/release/bimr_wasm.wasm
	$(WASM_OPT) -O $(BIMR_WASM)/pkg/bimr_wasm_bg.wasm -o $(BIMR_WASM)/pkg/bimr_wasm_bg.wasm
	$(MAKE) -C $(BIMR_WEB) build-web
	@echo "→ $(BIMR_ENGINE)/target/release/bimr-cli"
	@echo "→ $(BIMR_WASM)/pkg/"
	@echo "→ $(BIMR_WEB)/dist/"

serve: clone-web clone-engine clone-wasm clone-viewer build
	@echo "→ http://localhost:5173/editor/"
	$(MAKE) -C $(BIMR_WEB) serve

# ══ Clones ══

clone-kernel:
	@test -d $(BIMR_KERNEL) || git clone $(BIMR_KERNEL_REMOTE) $(BIMR_KERNEL)
	@git -C $(BIMR_KERNEL) pull --ff-only 2>/dev/null || true

clone-engine:
	@test -d $(BIMR_ENGINE) || git clone $(BIMR_ENGINE_REMOTE) $(BIMR_ENGINE)
	@git -C $(BIMR_ENGINE) pull --ff-only 2>/dev/null || true

clone-wasm:
	@test -d $(BIMR_WASM) || git clone $(BIMR_WASM_REMOTE) $(BIMR_WASM)
	@git -C $(BIMR_WASM) pull --ff-only 2>/dev/null || true

clone-web:
	@test -d $(BIMR_WEB) || git clone $(BIMR_WEB_REMOTE) $(BIMR_WEB)
	@git -C $(BIMR_WEB) pull --ff-only 2>/dev/null || true

clone-viewer:
	@test -d bimr-viewer-ifcx || \
	git clone --branch $(IFC5_BRANCH) $(IFC5_REMOTE) bimr-viewer-ifcx
