package main

import (
	"context"
	"errors"
	"fmt"
)

type guiBackendBootstrapDeps struct {
	ensureRunning     func() error
	waitReady         func(context.Context) error
	elevateInstall    func() error
	requiresElevation func(error) bool
}

func bootstrapMirageBackendForGUI(ctx context.Context, deps guiBackendBootstrapDeps) error {
	if ctx == nil {
		ctx = context.Background()
	}
	if deps.ensureRunning == nil {
		return errors.New("ensureRunning func is nil")
	}
	if deps.waitReady == nil {
		return errors.New("waitReady func is nil")
	}
	if deps.elevateInstall == nil {
		return errors.New("elevateInstall func is nil")
	}
	if deps.requiresElevation == nil {
		return errors.New("requiresElevation func is nil")
	}

	if err := deps.ensureRunning(); err != nil {
		if !deps.requiresElevation(err) {
			return fmt.Errorf("ensure mirage service running: %w", err)
		}
		if err := deps.elevateInstall(); err != nil {
			return fmt.Errorf("elevate mirage install: %w", err)
		}
	}

	if err := deps.waitReady(ctx); err != nil {
		return fmt.Errorf("wait for mirage backend ready: %w", err)
	}
	return nil
}
