/**
 * Cursor Agents sidebar sometimes renders the same folder twice, e.g.
 * `var/www/cursorconnect, cursorconnect` (label row) vs `var/www/cursorconnect`.
 * App list should show one repo group.
 */
export function normalizeSidebarRepoSectionName(name) {
    const t = name.trim().replace(/\s+/g, ' ');
    const commaIdx = t.indexOf(',');
    if (commaIdx <= 0)
        return t;
    const pathPart = t.slice(0, commaIdx).trim();
    const suffixPart = t.slice(commaIdx + 1).trim();
    if (!pathPart || !suffixPart)
        return t;
    const pathLeaf = pathPart.split('/').filter(Boolean).pop()?.toLowerCase() ?? '';
    const suffixNorm = suffixPart.toLowerCase().replace(/\s+/g, '');
    const pathLeafNorm = pathLeaf.replace(/\s+/g, '');
    if (suffixNorm === pathLeafNorm ||
        pathPart.toLowerCase().endsWith(`/${suffixNorm}`) ||
        pathPart.toLowerCase() === suffixNorm) {
        return pathPart;
    }
    return t;
}
export function sidebarRepoSectionKey(name) {
    return normalizeSidebarRepoSectionName(name).toLowerCase();
}
export function repoSectionNamesMatch(a, b) {
    return sidebarRepoSectionKey(a) === sidebarRepoSectionKey(b);
}
/** Merge duplicate sidebar repo headers into one `RepoGroup` (preserve agent order). */
export function mergeSidebarRepoSections(repos) {
    const out = [];
    const indexByKey = new Map();
    for (const repo of repos) {
        const name = normalizeSidebarRepoSectionName(repo.name);
        const key = sidebarRepoSectionKey(name);
        const existingIdx = indexByKey.get(key);
        if (existingIdx === undefined) {
            indexByKey.set(key, out.length);
            out.push({
                ...repo,
                id: name,
                name,
                agents: [...repo.agents],
            });
            continue;
        }
        const existing = out[existingIdx];
        existing.agents.push(...repo.agents);
        if (!existing.newChatSelectorPath && repo.newChatSelectorPath) {
            existing.newChatSelectorPath = repo.newChatSelectorPath;
        }
        if (!existing.path && repo.path)
            existing.path = repo.path;
    }
    return out;
}
