package wire

import (
	"context"
	"log/slog"
	"strings"
	"time"

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

// refreshKnowledgeBaseAccessForSyncedAgents triggers KB repository worktree sync for all
// agents in the server catalog. It is best-effort and stays off the control plane.
func (c *Protocol) refreshKnowledgeBaseAccessForSyncedAgents(agents []types.MachineAgentInfo, contexts ...context.Context) {
	ids := make([]string, 0, len(agents))
	for _, ag := range agents {
		if id := strings.TrimSpace(ag.ID); id != "" {
			ids = append(ids, id)
		}
	}
	if len(ids) == 0 {
		return
	}
	if refresher, ok := c.disp.(knowledgeBaseAccessRefresher); ok {
		ctx := firstConnectionTaskContext(contexts)
		ctx, cancel := context.WithTimeout(ctx, 60*time.Second)
		defer cancel()
		slog.Info("AgentTeam: pre-cloning KB repositories for synced agents",
			"channel", c.id, "agent_count", len(ids))
		refresher.RefreshKnowledgeBaseAccess(ctx, ids)
	}
}
