package message

import (
	"sort"
	"strings"
)

type AgentUnreadThread struct {
	ThreadID          string
	ChannelType       string
	ChannelName       string
	ParentChannelType string
	ParentChannelName string
	LastReadSeq       int64
	UnreadCount       int
}

func MergeAgentUnreadThreads(groups ...[]AgentUnreadThread) []AgentUnreadThread {
	if len(groups) == 0 {
		return nil
	}

	merged := make(map[string]AgentUnreadThread)
	for _, threads := range groups {
		for _, thread := range threads {
			key := strings.TrimSpace(thread.ThreadID)
			if key == "" {
				continue
			}
			current, exists := merged[key]
			if !exists {
				merged[key] = thread
				continue
			}
			current.UnreadCount += thread.UnreadCount
			if current.ChannelType == "" {
				current.ChannelType = thread.ChannelType
			}
			if current.ChannelName == "" {
				current.ChannelName = thread.ChannelName
			}
			if current.ParentChannelType == "" {
				current.ParentChannelType = thread.ParentChannelType
			}
			if current.ParentChannelName == "" {
				current.ParentChannelName = thread.ParentChannelName
			}
			if current.LastReadSeq == 0 && thread.LastReadSeq > 0 {
				current.LastReadSeq = thread.LastReadSeq
			}
			merged[key] = current
		}
	}

	threads := make([]AgentUnreadThread, 0, len(merged))
	for _, thread := range merged {
		threads = append(threads, thread)
	}
	sort.Slice(threads, func(left int, right int) bool {
		return threads[left].ThreadID < threads[right].ThreadID
	})
	return threads
}

func BuildAgentUnreadSummary(threads []AgentUnreadThread) map[string]int {
	if len(threads) == 0 {
		return nil
	}

	summary := make(map[string]int, len(threads))
	for _, thread := range threads {
		if thread.UnreadCount <= 0 {
			continue
		}
		label := FormatAgentUnreadSummaryLabel(thread)
		if strings.TrimSpace(label) == "" {
			continue
		}
		summary[label] += thread.UnreadCount
	}
	if len(summary) == 0 {
		return nil
	}
	return summary
}

func FormatAgentUnreadSummaryLabel(thread AgentUnreadThread) string {
	switch thread.ChannelType {
	case "dm":
		if strings.TrimSpace(thread.ChannelName) == "" {
			return ""
		}
		return "DM:@" + thread.ChannelName
	case "thread":
		shortID := strings.TrimPrefix(strings.TrimSpace(thread.ChannelName), "thread-")
		if shortID == "" {
			return ""
		}
		if thread.ParentChannelType == "dm" {
			if strings.TrimSpace(thread.ParentChannelName) == "" {
				return ""
			}
			return "DM:@" + thread.ParentChannelName + ":" + shortID
		}
		if strings.TrimSpace(thread.ParentChannelName) == "" {
			return ""
		}
		return "#" + thread.ParentChannelName + ":" + shortID
	default:
		if strings.TrimSpace(thread.ChannelName) == "" {
			return ""
		}
		return "#" + thread.ChannelName
	}
}
