package dispatcher

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

// KnowledgeBaseSyncer resolves an agent's accessible MeshX KB source repos and
// mounts them as local worktrees under the agent workspace's kb/managed tree.
type KnowledgeBaseSyncer interface {
	SyncAgent(ctx context.Context, agentID, scopeKey string) (SkillLookupState, error)
}

func (d *knowledgeBaseService) SetKnowledgeBaseSyncer(syncer KnowledgeBaseSyncer) {
	if syncer == nil {
		return
	}
	d.knowledgeBaseSyncerMu.Lock()
	d.knowledgeBaseSyncer = syncer
	d.knowledgeBaseSyncerMu.Unlock()
}

func (d *knowledgeBaseService) RefreshKnowledgeBaseAccess(ctx context.Context, agentIDs []string) {
	for _, agentID := range agentIDs {
		agentID = strings.TrimSpace(agentID)
		if agentID == "" {
			continue
		}
		d.refreshAgentKnowledgeBaseAccess(ctx, agentID)
	}
}

func (d *knowledgeBaseService) refreshAgentKnowledgeBaseAccess(ctx context.Context, agentID string) {
	d.knowledgeBaseSyncerMu.RLock()
	syncer := d.knowledgeBaseSyncer
	d.knowledgeBaseSyncerMu.RUnlock()
	if syncer == nil {
		return
	}
	scopeKey, ok := d.computeAgentTeamAgentScopeKey(agentID)
	if !ok {
		return
	}
	state, err := syncer.SyncAgent(ctx, agentID, scopeKey)
	if err != nil {
		slog.WarnContext(ctx, "KB access refresh: sync failed", "agent_id", agentID, "state", skillStateLabel(state), "error", err)
		return
	}
	if state == SkillLookupUnknown {
		slog.InfoContext(ctx, "KB access refresh: lookup unknown; preserving local KB worktrees", "agent_id", agentID)
	}
}
