.PHONY: all auto native docker clean

# Configuration
SRC = ch1115.chip.c
OUT = ch1115.chip.wasm

# Check if wokwi-cli exists in PATH
WOKWI_CLI := $(shell command -v wokwi-cli 2> /dev/null)

HOST_UID := $(shell id -u)
HOST_GID := $(shell id -g)

# Default target runs the auto-detection
all: auto

auto:
ifeq ($(WOKWI_CLI),)
	@echo "wokwi-cli not found in PATH. Falling back to Docker build..."
	$(MAKE) docker
else
	@echo "Found wokwi-cli at $(WOKWI_CLI). Using native build..."
	$(MAKE) native
endif

native:
	wokwi-cli chip compile $(SRC) -o $(OUT)

docker:
	docker run --rm -v $(CURDIR):/workspace -w /workspace ubuntu:latest \
		bash -c "apt-get update && apt-get install -y --no-install-recommends curl ca-certificates && \
		curl -L https://wokwi.com/ci/install.sh | sh && \
		~/.wokwi/bin/wokwi-cli chip compile $(SRC) -o $(OUT) && \
		chown $(HOST_UID):$(HOST_GID) $(OUT)"

clean:
	rm -f $(OUT)