.PHONY: build build-chrome build-firefox watch watch-firefox help

# Default target
help:
	@echo "Available targets:"
	@echo "  make build         - Build for Firefox (default)"
	@echo "  make build-chrome  - Build for Chrome"
	@echo "  make build-firefox - Build for Firefox"
	@echo "  make watch         - Watch for changes and rebuild Firefox (Press Ctrl+C to stop)"

# Build for Firefox (default)
build: build-firefox

# Build for Chrome
build-chrome:
	@echo "Building extension for Chrome..."
	@cp manifest.chrome.json manifest.json
	@mkdir -p web-ext-artifacts/chrome
	@VERSION=$$(grep '"version"' manifest.json | head -1 | sed 's/.*"version": *"\([^"]*\)".*/\1/'); \
	zip -r web-ext-artifacts/chrome/bookmark-sync-chrome-$$VERSION.zip . \
		-x "*.git*" \
		-x "web-ext-artifacts/*" \
		-x "manifest.firefox.json" \
		-x "manifest.chrome.json" \
		-x "Makefile" \
		-x ".cursorrules" \
		-x "*.md" \
		> /dev/null 2>&1 || true; \
	echo "Chrome build complete: web-ext-artifacts/chrome/bookmark-sync-chrome-$$VERSION.zip"

# Build for Firefox
build-firefox:
	@echo "Building extension for Firefox..."
	@cp manifest.firefox.json manifest.json
	@VERSION=$$(grep '"version"' manifest.json | head -1 | sed 's/.*"version": *"\([^"]*\)".*/\1/'); \
	mkdir -p web-ext-artifacts/firefox; \
	web-ext build --overwrite-dest --artifacts-dir=web-ext-artifacts/firefox 2>/dev/null || \
	web-ext build --overwrite-dest 2>/dev/null; \
	find web-ext-artifacts -maxdepth 2 -name "bookmark-sync-$$VERSION.zip" -type f -exec sh -c 'mv "$$1" "$$(dirname $$1)/bookmark-sync-firefox-$$VERSION.zip"' _ {} \; 2>/dev/null || \
	find web-ext-artifacts -maxdepth 2 -name "bookmark-sync-*.zip" -type f | head -1 | xargs -I {} sh -c 'mv "{}" "$$(dirname {})/bookmark-sync-firefox-$$VERSION.zip"' 2>/dev/null || true; \
	echo "Firefox build complete: web-ext-artifacts/firefox/bookmark-sync-firefox-$$VERSION.zip"

# Watch for changes and rebuild Firefox
watch: watch-firefox

watch-firefox:
	@echo "Watching for changes... (Press Ctrl+C to stop)"
	@which inotifywait > /dev/null || (echo "Error: inotifywait not found. Install inotify-tools package." && exit 1)
	@while true; do \
		inotifywait -r -e modify,create,delete,move \
			--exclude 'web-ext-artifacts|\.git' \
			. > /dev/null 2>&1; \
		if [ $$? -eq 0 ]; then \
			echo "Change detected, rebuilding Firefox..."; \
			$(MAKE) build-firefox; \
		fi; \
	done

