package webagent

import (
	"context"
	"strings"
	"time"

	"github.com/tidbcloud/AgentTeam/internal/api"
	"github.com/tidbcloud/AgentTeam/internal/store/agent"
)

const maxRuntimeSnapshotAgentIDs = agent.MaxAgentRuntimeSnapshotIDs

type RuntimeSnapshotStore interface {
	AgentRuntimeSnapshotsForWorkspace(ctx context.Context, userID, workspaceID string, agentIDs []string) ([]agent.AgentRuntimeSnapshot, error)
}

func (handler *RuntimeHandler) emitAgentStoppingIfRunning(workspaceID string, ownerUserID string, agent agent.AgentView) {
	if handler.realtime == nil || !shouldEmitAgentStopping(handler.runtime, agent) {
		return
	}
	handler.realtime.EmitAgentActivity(workspaceID, ownerUserID, agent.AgentID, "stopping", "")
}

func shouldEmitAgentStopping(runtime Runtime, agent agent.AgentView) bool {
	if runtime != nil {
		machineID := strings.TrimSpace(agent.MachineID)
		agentID := strings.TrimSpace(agent.AgentID)
		if machineID != "" && agentID != "" {
			return runtime.AgentRuntimeRunning(machineID, agentID)
		}
		return false
	}
	return strings.TrimSpace(agent.Status) == "active"
}

func normalizeRequestedAgentIDs(agentIDs []string) []string {
	normalized := make([]string, 0, len(agentIDs))
	seen := make(map[string]struct{}, len(agentIDs))
	for _, agentID := range agentIDs {
		trimmed := strings.TrimSpace(agentID)
		if trimmed == "" {
			continue
		}
		if _, exists := seen[trimmed]; exists {
			continue
		}
		seen[trimmed] = struct{}{}
		normalized = append(normalized, trimmed)
	}
	return normalized
}

func normalizeLookupIDs(values []string) ([]string, bool) {
	normalized := make([]string, 0, len(values))
	seen := make(map[string]struct{}, len(values))
	for _, value := range values {
		value = strings.TrimSpace(value)
		if value == "" || len(value) > 255 {
			return nil, false
		}
		if _, exists := seen[value]; exists {
			continue
		}
		seen[value] = struct{}{}
		normalized = append(normalized, value)
	}
	return normalized, true
}

func applyRuntimeSnapshotState(snapshots []agent.AgentRuntimeSnapshot, runtime RuntimeSnapshotRuntime, now time.Time) {
	api.OverlayAgentRuntimeSnapshots(snapshots, runtime, now)
}
