import { computed, type Ref } from 'vue';
import type { Agent } from './agents';

export function useMessageGrouping(
    messages: Ref<any[]>,
    visibleCount: Ref<number>,
    selectedAgent: Ref<string>,
    allAgents: Ref<Agent[]>,
    sessionKey?: Ref<string>,
) {
    const VISIBLE_PAGE = 50;

    const visibleMsgs = computed(() => {
        const all = messages.value;
        const start = Math.max(0, all.length - visibleCount.value);
        return all.slice(start).map((m, i) => ({ ...m, _sourceIndex: start + i }));
    });
    const hasMore = computed(() => messages.value.length > visibleCount.value);

    function loadMore() {
        visibleCount.value += VISIBLE_PAGE;
    }

    function getFormattedAgentName(agentId: string | null): string {
        if (!agentId) return 'Unknown';
        const agent = allAgents.value.find(a => a.id === agentId);
        return agent ? agent.name : agentId;
    }

    function shouldShowHeadline(index: number, msgsArr: any[]): boolean {
        if (index === 0) return true;
        const current = msgsArr[index];
        const prev = msgsArr[index - 1];

        // Ignore transitions to/from null agentId (user messages)
        // Only show headlines for actual agent switches or session changes
        if (!current.agentId || !prev.agentId) {
            return current.sessionId !== prev.sessionId;
        }

        return current.agentId !== prev.agentId || current.sessionId !== prev.sessionId;
    }

    function formatHeadlineText(agentName: string): string {
        const key = sessionKey?.value;
        return key ? `${agentName} · ${key}` : agentName;
    }

    function getHeadline(index: number, msgsArr: any[]): { text: string; kind: 'agent' | 'new-session' } {
        const current = msgsArr[index];
        const targetAgentId = current.agentId || selectedAgent.value;
        const agentName = getFormattedAgentName(targetAgentId);

        if (index === 0) return { text: formatHeadlineText(agentName), kind: 'agent' };
        const prev = msgsArr[index - 1];
        if (current.agentId !== prev.agentId) return { text: formatHeadlineText(agentName), kind: 'agent' };
        if (current.sessionId !== prev.sessionId) return { text: 'New Session', kind: 'new-session' };
        return { text: formatHeadlineText(agentName), kind: 'agent' };
    }

    const groupedVisibleMsgs = computed(() => {
        const raw = visibleMsgs.value;
        const result: any[] = [];
        let currentGroup: any = null;

        for (let i = 0; i < raw.length; i++) {
            const msg = raw[i];

            if (shouldShowHeadline(i, raw)) {
                if (currentGroup) { result.push(currentGroup); currentGroup = null; }
                const { text, kind } = getHeadline(i, raw);
                result.push({
                    role: 'system',
                    type: 'headline',
                    content: text,
                    headlineKind: kind,
                    agentId: msg.agentId,
                    sessionId: msg.sessionId,
                    position: 'header', // Header appears before agent block
                });
            }

            if (msg.role === 'system' && msg.type !== 'no_session') {
                if (!currentGroup) {
                    currentGroup = { role: 'system_group', messages: [msg], agentId: msg.agentId, sessionId: msg.sessionId };
                } else {
                    currentGroup.messages.push(msg);
                }
            } else {
                if (currentGroup) { result.push(currentGroup); currentGroup = null; }
                result.push(msg);

                // Footer headline: only once, at the very end of the list
                const effectiveAgentId = msg.agentId || selectedAgent.value;
                if (effectiveAgentId && i === raw.length - 1) {
                    const agentName = getFormattedAgentName(effectiveAgentId);
                    result.push({
                        role: 'system',
                        type: 'headline',
                        content: formatHeadlineText(agentName),
                        headlineKind: 'agent',
                        agentId: effectiveAgentId,
                        sessionId: msg.sessionId,
                        position: 'footer',
                    });
                }
            }
        }

        if (currentGroup) result.push(currentGroup);
        return result;
    });

    return {
        visibleMsgs,
        groupedVisibleMsgs,
        hasMore,
        loadMore,
        getFormattedAgentName,
    };
}
