package darwin

import (
	"errors"
	"path/filepath"

	"github.com/Eriyc/rules_wails/pkg/wails3kit/updates"
	"github.com/Eriyc/rules_wails/pkg/wails3kit/updates/platform"
)

func New() updates.PlatformInstaller {
	return platform.New(DetectInstallRoot)
}

func DetectInstallRoot(app updates.AppDescriptor) (updates.InstallRoot, error) {
	if app.ExecutablePath == "" {
		return updates.InstallRoot{}, errors.New("missing executable path")
	}

	current := filepath.Dir(app.ExecutablePath)
	for {
		if filepath.Ext(current) == ".app" {
			return updates.InstallRoot{Path: current}, nil
		}
		parent := filepath.Dir(current)
		if parent == current {
			return updates.InstallRoot{}, errors.New("unable to locate .app bundle")
		}
		current = parent
	}
}
