# Top-level Makefile – delegates build/clean/test to subdirectories

CC ?= gcc

SUBDIRS = engine client

VERSION ?= $(shell git describe --tags --always 2>/dev/null || echo "0.0.0")

.PHONY: all build clean test check format orchestrator run e2e package $(SUBDIRS)

all: build orchestrator

build: $(SUBDIRS)
	@echo "Build complete."

orchestrator: orchestrator.c
	$(CC) -Wall -Wextra -std=c11 -o looper orchestrator.c

GEN_TONE_BIN = /tmp/gen_tone

$(GEN_TONE_BIN): e2e/gen_tone.c
	$(CC) -o $@ $< -ljack -lm

$(SUBDIRS):
	$(MAKE) -C $@

run: orchestrator
	./looper

# Run unit tests for engine and client, and end-to-end tests
test:
	# FIXME re‑enable engine and client unit tests later
	$(MAKE) e2e

# Run end‑to‑end tests (installs npm dependencies if missing)
# Skip if any required tool is missing
REQUIRED_TOOLS = tmux sox jack_capture jack_wait node
e2e: build $(GEN_TONE_BIN)
	@missing="" ; \
	for cmd in $(REQUIRED_TOOLS); do \
		if ! command -v $$cmd >/dev/null 2>&1; then \
			missing="$$missing $$cmd"; \
		fi ; \
	done ; \
	if [ -n "$$missing" ]; then \
		echo "Skipping e2e tests (missing:$$missing)"; \
		exit 0; \
	fi ; \
	cd e2e && npm install --silent && npm test

# Create a distribution archive
package: build
	tar czf looper-$(VERSION).tar.gz \
		--transform 's,^,looper-$(VERSION)/,' \
		looper \
		README.md LICENSE 2>/dev/null; \
	echo "Created looper-$(VERSION).tar.gz"

clean:
	rm -f looper
	@for dir in $(SUBDIRS); do \
	    echo "Cleaning $$dir..."; \
	    $(MAKE) -C $$dir clean; \
	done

check:
	$(MAKE) -C engine check

format:
	$(MAKE) -C engine format
