package cmd

import (
	"fmt"
	"time"

	"github.com/tidbcloud/AgentTeam/desktop/internal/daemon"
)

func waitForHealthyRunningDaemon(timeout time.Duration) (*daemon.Status, error) {
	status := daemonStatus()
	if status != nil && status.Running && status.Healthy {
		return status, nil
	}
	if timeout <= 0 {
		return nil, fmt.Errorf("daemon did not become healthy within %s", timeout)
	}

	deadline := time.NewTimer(timeout)
	defer deadline.Stop()
	ticker := time.NewTicker(300 * time.Millisecond)
	defer ticker.Stop()
	for {
		select {
		case <-deadline.C:
			return nil, fmt.Errorf("daemon did not become healthy within %s", timeout)
		case <-ticker.C:
			status := daemonStatus()
			if status != nil && status.Running && status.Healthy {
				return status, nil
			}
		}
	}
}
