package rewindplan

import (
	"sort"
	"strings"
	"time"
)

func AgentPlanForID(agentPlans map[string]*AgentPlan, agentID string) *AgentPlan {
	trimmedAgentID := strings.TrimSpace(agentID)
	if existing := agentPlans[trimmedAgentID]; existing != nil {
		return existing
	}
	next := &AgentPlan{}
	agentPlans[trimmedAgentID] = next
	return next
}

func FirstTouchPrecedes(candidateGlobalSeq int64, candidateAt time.Time, current *AgentPlan) bool {
	if current.FirstTouchGlobalSeq > 0 && candidateGlobalSeq > 0 {
		return candidateGlobalSeq < current.FirstTouchGlobalSeq
	}
	return candidateAt.Before(current.FirstTouchAt)
}

func SameStringSlice(left []string, right []string) bool {
	if len(left) != len(right) {
		return false
	}
	for i := range left {
		if strings.TrimSpace(left[i]) != strings.TrimSpace(right[i]) {
			return false
		}
	}
	return true
}

func SortAgentPlans(plans []AgentPlan) {
	sort.Slice(plans, func(i, j int) bool {
		left := plans[i]
		right := plans[j]
		if left.FirstTouchGlobalSeq != right.FirstTouchGlobalSeq {
			return left.FirstTouchGlobalSeq < right.FirstTouchGlobalSeq
		}
		if !left.FirstTouchAt.Equal(right.FirstTouchAt) {
			return left.FirstTouchAt.Before(right.FirstTouchAt)
		}
		if left.FirstTouchMessageID != right.FirstTouchMessageID {
			return left.FirstTouchMessageID < right.FirstTouchMessageID
		}
		return left.AgentID < right.AgentID
	})
}

func NormalizeNonEmptyStrings(values []string) []string {
	if len(values) == 0 {
		return nil
	}

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