import { matchJsonlAgentForSidebarTitle, normalizeAgentTitle, } from './agent-title-match.js';
import { mergeSidebarRepoSections } from './sidebar-repo-section.js';
export { normalizeAgentTitle } from './agent-title-match.js';
/** Prefer Cursor DOM sidebar order/names; attach JSONL ids when titles match. */
export function mergeSidebarWithJsonl(sidebarRepos, jsonl, composerIdByTitle) {
    if (!sidebarRepos?.length)
        return { ...jsonl, listSource: 'jsonl' };
    const sidebar = mergeSidebarRepoSections(sidebarRepos);
    const byTitle = new Map();
    for (const repo of jsonl.repos) {
        for (const agent of repo.agents) {
            byTitle.set(normalizeAgentTitle(agent.title), agent);
            if (agent.preview)
                byTitle.set(normalizeAgentTitle(agent.preview), agent);
        }
    }
    const repos = sidebar.map((section) => ({
        id: section.id,
        name: section.name,
        path: section.path,
        ...(section.newChatSelectorPath
            ? { newChatSelectorPath: section.newChatSelectorPath }
            : {}),
        agents: section.agents.map((row) => {
            const fuzzy = matchJsonlAgentForSidebarTitle(row.title, jsonl, composerIdByTitle);
            if (fuzzy) {
                return {
                    ...fuzzy,
                    title: row.title,
                    isWorking: row.isWorking ?? fuzzy.isWorking,
                    hasUnread: row.hasUnread === true || fuzzy.hasUnread === true,
                    needsAttention: row.needsAttention === true || fuzzy.needsAttention === true,
                };
            }
            const match = byTitle.get(normalizeAgentTitle(row.title));
            if (match) {
                return {
                    ...match,
                    title: row.title,
                    isWorking: row.isWorking ?? match.isWorking,
                    hasUnread: row.hasUnread === true || match.hasUnread === true,
                    needsAttention: row.needsAttention === true || match.needsAttention === true,
                };
            }
            return {
                ...row,
                id: row.id || `title:${normalizeAgentTitle(row.title)}`,
            };
        }),
    }));
    return { repos, updatedAt: Date.now(), listSource: 'sidebar' };
}
