# Define a directory for dependencies in the user's home folder
DEPS_DIR := $(HOME)/VoiceInk-Dependencies

# Signing identity for `make local`. Default is ad-hoc ("-"), which changes
# every build and resets TCC permission grants. Override with a stable
# identity (e.g. an Apple Development certificate) to keep grants:
#   make local SIGN_IDENTITY="Apple Development: Your Name (TEAMID)"
SIGN_IDENTITY ?= -
# whisper.cpp ref to build — pinned so a rebuild never compiles untested
# upstream master under the daily-driver app. Matches the currently-built
# snapshot (CMakeLists project VERSION 1.8.2).
WHISPER_REF ?= v1.8.2
WHISPER_CPP_DIR := $(DEPS_DIR)/whisper.cpp
FRAMEWORK_PATH := $(WHISPER_CPP_DIR)/build-apple/whisper.xcframework
# Public source uses a portable local build cache.
LOCAL_DERIVED_DATA ?= $(CURDIR)/.local-build
OWC_VOLUME ?= /Volumes/VoiceInk Build Cache

.PHONY: all clean distclean whisper setup build local resign check healthcheck help dev run

# Default target
all: check build

# Development workflow
dev: build run

# Prerequisites
check:
	@echo "Checking prerequisites..."
	@command -v git >/dev/null 2>&1 || { echo "git is not installed"; exit 1; }
	@command -v xcodebuild >/dev/null 2>&1 || { echo "xcodebuild is not installed (need Xcode)"; exit 1; }
	@command -v swift >/dev/null 2>&1 || { echo "swift is not installed"; exit 1; }
	@echo "Prerequisites OK"

healthcheck: check

# Build process
whisper:
	@mkdir -p $(DEPS_DIR)
	@if [ ! -d "$(FRAMEWORK_PATH)" ]; then \
		echo "Building whisper.xcframework in $(DEPS_DIR)..."; \
		if [ ! -d "$(WHISPER_CPP_DIR)" ]; then \
			git clone --branch $(WHISPER_REF) --depth 1 https://github.com/ggerganov/whisper.cpp.git $(WHISPER_CPP_DIR); \
		else \
			(cd $(WHISPER_CPP_DIR) && git fetch --tags && git checkout $(WHISPER_REF)); \
		fi; \
		cd $(WHISPER_CPP_DIR) && ./build-xcframework.sh; \
	else \
		echo "whisper.xcframework already built in $(DEPS_DIR), skipping build"; \
	fi

setup: whisper
	@echo "Whisper framework is ready at $(FRAMEWORK_PATH)"
	@echo "Please ensure your Xcode project references the framework from this new location."

# Debug builds carry the same LOCAL_BUILD guard as `local`: without it the
# app compiles with Sparkle live against upstream's appcast and would offer
# to replace this fork with the upstream release (see CLAUDE.md). Same flags
# as `local`, minus the ~/Downloads copy.
build: setup
	@echo "Build cache: $(LOCAL_DERIVED_DATA)"
	xcodebuild -project VoiceInk.xcodeproj -scheme VoiceInk -configuration Debug \
		-derivedDataPath "$(LOCAL_DERIVED_DATA)" \
		-xcconfig LocalBuild.xcconfig \
		CODE_SIGN_IDENTITY="$(SIGN_IDENTITY)" \
		CODE_SIGNING_REQUIRED=NO \
		CODE_SIGNING_ALLOWED=YES \
		DEVELOPMENT_TEAM="" \
		CODE_SIGN_ENTITLEMENTS="$(CURDIR)/VoiceInk/VoiceInk.local.entitlements" \
		SWIFT_ACTIVE_COMPILATION_CONDITIONS='$$(inherited) LOCAL_BUILD' \
		build

# Build for local use without Apple Developer certificate
local: check setup
	@echo "Building VoiceInk for local use (no Apple Developer certificate required)..."
	@echo "Build cache: $(LOCAL_DERIVED_DATA)"
	xcodebuild -project VoiceInk.xcodeproj -scheme VoiceInk -configuration Debug \
		-derivedDataPath "$(LOCAL_DERIVED_DATA)" \
		-xcconfig LocalBuild.xcconfig \
		CODE_SIGN_IDENTITY="$(SIGN_IDENTITY)" \
		CODE_SIGNING_REQUIRED=NO \
		CODE_SIGNING_ALLOWED=YES \
		DEVELOPMENT_TEAM="" \
		CODE_SIGN_ENTITLEMENTS="$(CURDIR)/VoiceInk/VoiceInk.local.entitlements" \
		SWIFT_ACTIVE_COMPILATION_CONDITIONS='$$(inherited) LOCAL_BUILD' \
		build
	@APP_PATH="$(LOCAL_DERIVED_DATA)/Build/Products/Debug/VoiceInk.app" && \
	if [ -d "$$APP_PATH" ]; then \
		echo "Copying VoiceInk.app to ~/Downloads..."; \
		rm -rf "$$HOME/Downloads/VoiceInk.app"; \
		ditto "$$APP_PATH" "$$HOME/Downloads/VoiceInk.app"; \
		xattr -cr "$$HOME/Downloads/VoiceInk.app"; \
		echo ""; \
		echo "Build complete! App saved to: ~/Downloads/VoiceInk.app"; \
		echo "Run with: open ~/Downloads/VoiceInk.app"; \
		echo ""; \
		echo "Limitations of local builds:"; \
		echo "  - No iCloud dictionary sync"; \
		echo "  - No automatic updates (pull new code and rebuild to update)"; \
	else \
		echo "Error: Could not find built VoiceInk.app at $$APP_PATH"; \
		exit 1; \
	fi

# Re-sign ~/Downloads/VoiceInk.app with a stable identity so macOS TCC
# permission grants (mic, accessibility, screen recording) survive rebuilds.
# xcodebuild with CODE_SIGNING_REQUIRED=NO silently falls back to ad-hoc,
# so this runs as a separate post-build step:
#   make local resign SIGN_IDENTITY="Apple Development: Your Name (TEAMID)"
resign:
	@test -d "$$HOME/Downloads/VoiceInk.app" || { echo "No app at ~/Downloads/VoiceInk.app — run make local first"; exit 1; }
	@test "$(SIGN_IDENTITY)" != "-" || { echo "Set SIGN_IDENTITY to a stable identity"; exit 1; }
	find "$$HOME/Downloads/VoiceInk.app/Contents/Frameworks" -maxdepth 1 -name "*.framework" -exec codesign --force --deep --sign "$(SIGN_IDENTITY)" --timestamp=none {} \;
	codesign --force --sign "$(SIGN_IDENTITY)" --timestamp=none "$$HOME/Downloads/VoiceInk.app/Contents/MacOS/"*.dylib
	codesign --force --sign "$(SIGN_IDENTITY)" --entitlements "$(CURDIR)/VoiceInk/VoiceInk.local.entitlements" --timestamp=none "$$HOME/Downloads/VoiceInk.app"
	codesign --verify --deep --strict "$$HOME/Downloads/VoiceInk.app"
	@echo "Re-signed with: $(SIGN_IDENTITY)"

# Run application
run:
	@if [ -d "$$HOME/Downloads/VoiceInk.app" ]; then \
		echo "Opening ~/Downloads/VoiceInk.app..."; \
		open "$$HOME/Downloads/VoiceInk.app"; \
	else \
		APP_PATH="$(LOCAL_DERIVED_DATA)/Build/Products/Debug/VoiceInk.app"; \
		if [ ! -d "$$APP_PATH" ]; then \
			echo "Looking for VoiceInk.app in legacy DerivedData..."; \
			APP_PATH=$$(find "$$HOME/Library/Developer/Xcode/DerivedData" -name "VoiceInk.app" -type d 2>/dev/null | head -1); \
		fi; \
		if [ -d "$$APP_PATH" ]; then \
			echo "Found app at: $$APP_PATH"; \
			open "$$APP_PATH"; \
		else \
			echo "VoiceInk.app not found. Please run 'make build' or 'make local' first."; \
			exit 1; \
		fi; \
	fi

# Cleanup: build outputs only — keeps the whisper.cpp checkout+build in
# $(DEPS_DIR), which takes a long time to rebuild.
clean:
	@echo "Cleaning build artifacts..."
	@target="$(LOCAL_DERIVED_DATA)"; \
	if [ -e "$$target" ] || [ -L "$$target" ]; then \
		[ -d "$$target" ] && [ ! -L "$$target" ] || { echo "Refusing to clean a file or symlink: $$target"; exit 1; }; \
		target=$$(cd "$$target" && pwd -P) || exit 1; \
		repository=$$(pwd -P); \
		case "$$target" in \
			"$$repository/.local-build"|"$(OWC_VOLUME)/dev-cache/voiceink/local-build") ;; \
			"$$repository"|"$$repository"/*|/|/Volumes|"$(HOME)"|"$(OWC_VOLUME)") \
				echo "Refusing to clean protected directory: $$target"; exit 1 ;; \
			*) workspace=$$(/usr/libexec/PlistBuddy -c 'Print :WorkspacePath' "$$target/info.plist" 2>/dev/null); \
				case "$$workspace" in "$$repository/VoiceInk.xcodeproj"|"$$repository/VoiceInk.xcodeproj/"*) ;; \
					*) echo "Refusing to clean unrecognized build cache: $$target"; exit 1 ;; esac; \
				[ ! -e "$$target/.git" ] || { echo "Refusing to clean a source checkout: $$target"; exit 1; } ;; \
		esac; \
		rm -rf "$$target"; \
	fi
	@rm -rf "$(FRAMEWORK_PATH)"
	@echo "Clean complete"

# Full dependency removal: next build re-clones and rebuilds whisper.cpp
distclean: clean
	@rm -rf $(DEPS_DIR)
	@echo "Removed $(DEPS_DIR)"

# Help
help:
	@echo "Available targets:"
	@echo "  check/healthcheck  Check if required CLI tools are installed"
	@echo "  whisper            Clone and build whisper.cpp XCFramework"
	@echo "  setup              Copy whisper XCFramework to VoiceInk project"
	@echo "  build              Build the VoiceInk Xcode project"
	@echo "  local              Build for local use (no Apple Developer certificate needed)"
	@echo "  run                Launch the built VoiceInk app"
	@echo "  dev                Build and run the app (for development)"
	@echo "  all                Run full build process (default)"
	@echo "  clean              Remove local build output and the built whisper framework"
	@echo "  distclean          Also remove the whisper.cpp checkout in $(DEPS_DIR)"
	@echo "  help               Show this help message"
