package builder

import (
	"fmt"
	"os"
	"path/filepath"
	"strings"
)

func (h *Handler) buildDarwinAppBundle(outDir, title, runnerPath string, p BuildPlatform) error {
	appName := sanitizeFileName(strings.TrimSuffix(filepath.Base(title), filepath.Ext(title))) + ".app"
	if appName == ".app" {
		appName = "Movie.app"
	}
	appDir := filepath.Join(outDir, appName)
	macosDir := filepath.Join(appDir, "Contents", "MacOS")
	if err := os.MkdirAll(macosDir, 0755); err != nil {
		return err
	}
	dest := filepath.Join(macosDir, "runner")
	if err := copyFile(runnerPath, dest); err != nil {
		return err
	}
	_ = os.Chmod(dest, 0755)
	name := strings.TrimSuffix(filepath.Base(title), filepath.Ext(title))
	plist := fmt.Sprintf(`<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict>
<key>CFBundleName</key><string>%s</string>
<key>CFBundleExecutable</key><string>runner</string>
<key>CFBundleIdentifier</key><string>com.aetherforge.%s</string>
<key>LSUIElement</key><true/>
</dict></plist>`, name, sanitizeFileName(title))
	return os.WriteFile(filepath.Join(appDir, "Contents", "Info.plist"), []byte(plist), 0644)
}
