.PHONY: build clean build-dev build-release

# Default target - optimized release build
all: build-release

# Development build (larger, with debug symbols)
build-dev:
	GOOS=darwin GOARCH=arm64 fyne package
	@echo "Copying additional resources to app bundle..."
	@mkdir -p EpochSilicon.app/Contents/Resources/rosettax87
	@mkdir -p EpochSilicon.app/Contents/Resources/winerosetta
	@cp -R rosettax87/* EpochSilicon.app/Contents/Resources/rosettax87/
	@cp -R winerosetta/* EpochSilicon.app/Contents/Resources/winerosetta/
	@cp -R Icon.png EpochSilicon.app/Contents/Resources/
	@echo "Development build complete!"

build: build-dev

build-release:
	@rm -rf ./EpochSilicon.app
	@echo "Building optimized release version..."
	CGO_ENABLED=1 GOOS=darwin GOARCH=arm64 go build \
		-ldflags="-s -w" \
		-trimpath \
		-tags=release \
		-o epochsilicon .
	@echo "Packaging with fyne..."
	GOOS=darwin GOARCH=arm64 fyne package --release --executable epochsilicon
	@echo "Copying additional resources to app bundle..."
	@mkdir -p EpochSilicon.app/Contents/Resources/rosettax87
	@mkdir -p EpochSilicon.app/Contents/Resources/winerosetta
	@cp -R rosettax87/* EpochSilicon.app/Contents/Resources/rosettax87/
	@cp -R winerosetta/* EpochSilicon.app/Contents/Resources/winerosetta/
	@cp -R Icon.png EpochSilicon.app/Contents/Resources/
	@echo "Stripping additional symbols..."
	strip -x EpochSilicon.app/Contents/MacOS/epochsilicon
	@echo "Optimized release build complete!"
	@echo "Binary size: $$(ls -lah EpochSilicon.app/Contents/MacOS/epochsilicon | awk '{print $$5}')"

# Clean build artifacts
clean:
	rm -rf EpochSilicon.app
	rm -f EpochSilicon.dmg
	rm -f EpochSilicon.zip
	rm -f epochsilicon

sign: build-release
	codesign --timestamp --options runtime -s "Developer ID Application: Evan Burkey (2TXG4AP658)" ./EpochSilicon.app/Contents/Resources/rosettax87/rosettax87
	codesign --timestamp --options runtime -s "Developer ID Application: Evan Burkey (2TXG4AP658)" ./EpochSilicon.app/Contents/Resources/rosettax87/libRuntimeRosettax87
	codesign --timestamp --options runtime -s "Developer ID Application: Evan Burkey (2TXG4AP658)" ./EpochSilicon.app
	@/usr/bin/ditto -c -k -rsrc --sequesterRsrc --keepParent ./EpochSilicon.app EpochSilicon.zip
	xcrun notarytool submit --keychain-profile "EpochSilicon" --wait ./EpochSilicon.zip
	xcrun stapler staple ./EpochSilicon.app

dmg: build-release sign
	echo "Preparing DMG staging directory..."
	@rm -rf dmg-staging
	@mkdir dmg-staging
	@/usr/bin/ditto --rsrc ./EpochSilicon.app dmg-staging/EpochSilicon.app
	@ln -s /Applications dmg-staging/Applications
	hdiutil create -volname EpochSilicon -srcfolder dmg-staging -ov -format UDZO EpochSilicon.dmg
	@rm -rf dmg-staging
	codesign --timestamp -i com.burkey.epochsilicon -s "Developer ID Application: Evan Burkey (2TXG4AP658)" ./EpochSilicon.dmg
	xcrun notarytool submit --keychain-profile "EpochSilicon" --wait ./EpochSilicon.dmg
	xcrun stapler staple ./EpochSilicon.dmg
