export function readSidebarRepoAgentsDom(opts) {
    function normText(s) {
        return s
            .trim()
            .replace(/\s+/g, ' ')
            .replace(/\d+\s*(?:s|m|h|d|w)\b/gi, '')
            .replace(/\d+[smhdw]$/i, '')
            .toLowerCase();
    }
    function sectionHeadLabel(head) {
        const clone = head.cloneNode(true);
        clone
            .querySelectorAll('button, [role="button"], .ui-icon-button')
            .forEach((el) => el.remove());
        return normText((clone.textContent || '').replace(/\s+/g, ' '));
    }
    function normalizeRepoSection(name) {
        const t = normText(name.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() ?? '';
        if (suffixPart === pathLeaf || pathPart.endsWith(`/${suffixPart}`))
            return pathPart;
        return t;
    }
    function repoMatches(sectionName, want) {
        if (!want)
            return true;
        const a = normalizeRepoSection(sectionName);
        const b = normalizeRepoSection(want);
        if (a === b)
            return true;
        if (a.includes(b) || b.includes(a))
            return true;
        return false;
    }
    function cleanSidebarTitle(btn) {
        const label = btn.querySelector('.ui-sidebar-menu-button-label');
        let t = (label?.textContent || btn.textContent || '').trim().replace(/\s+/g, ' ');
        t = t
            .replace(/\d+\s*(?:s|m|h|d|w)\b/gi, '')
            .replace(/\d+[smhdw]$/i, '')
            .trim();
        return t.slice(0, 120);
    }
    function readBtn(btn) {
        const title = cleanSidebarTitle(btn);
        if (!title || /^more$/i.test(title) || /^less$/i.test(title))
            return null;
        let composerId = btn.getAttribute('data-composer-id') ||
            btn.closest('li')?.getAttribute('data-composer-id') ||
            btn.closest('[data-composer-id]')?.getAttribute('data-composer-id') ||
            '';
        if (!composerId) {
            const href = btn.closest('a')?.getAttribute('href') ||
                btn.querySelector('a')?.getAttribute('href') ||
                '';
            const uuid = href.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i);
            if (uuid)
                composerId = uuid[0];
        }
        if (!composerId)
            composerId = `title:${normText(title)}`;
        const active = btn.getAttribute('data-active') === 'true' ||
            btn.classList.contains('active') ||
            btn.closest('li')?.getAttribute('aria-selected') === 'true';
        return { composerId, title, active };
    }
    const wantRepo = normText(opts.repoName ?? '');
    const scroll = document.querySelector('[class*="glass-sidebar-scroll"]') ||
        document.querySelector('[class*="glass-sidebar-body"]') ||
        document.querySelector('[class*="glass-sidebar"]');
    const allAgents = [];
    if (!scroll)
        return { agents: allAgents };
    let sectionName = '';
    let sectionAgents = [];
    let matched = null;
    const rowSelector = '.glass-sidebar-agent-list-container li.ui-sidebar-menu-item > div.glass-sidebar-agent-menu-btn, li.ui-sidebar-menu-item > div.glass-sidebar-agent-menu-btn';
    for (const el of scroll.querySelectorAll(`.ui-sidebar-section-head, ${rowSelector}`)) {
        if (el.classList.contains('ui-sidebar-section-head')) {
            if (matched && sectionAgents.length)
                return matched;
            if (wantRepo && sectionName && repoMatches(sectionName, wantRepo) && sectionAgents.length) {
                matched = { repoName: sectionName, agents: sectionAgents };
            }
            sectionName = sectionHeadLabel(el);
            sectionAgents = [];
            continue;
        }
        const row = readBtn(el);
        if (!row)
            continue;
        allAgents.push(row);
        if (!wantRepo || repoMatches(sectionName, wantRepo)) {
            sectionAgents.push(row);
        }
    }
    if (wantRepo && sectionName && repoMatches(sectionName, wantRepo) && sectionAgents.length) {
        return { repoName: sectionName, agents: sectionAgents };
    }
    if (matched)
        return matched;
    return { agents: allAgents };
}
const PLACEHOLDER_TITLE = /^(new agent|new chat|untitled|чат|агент|без названия|новый агент|новый чат)$/i;
export function pickNewChatFromSidebarDiff(before, after) {
    const beforeIds = new Set(before.map((a) => a.composerId));
    const added = after.filter((a) => !beforeIds.has(a.composerId));
    if (added.length === 1) {
        return { composerId: added[0].composerId, title: added[0].title };
    }
    const addedPlaceholders = added.filter((a) => PLACEHOLDER_TITLE.test(a.title.trim()));
    if (addedPlaceholders.length === 1) {
        return {
            composerId: addedPlaceholders[0].composerId,
            title: addedPlaceholders[0].title,
        };
    }
    const active = after.find((a) => a.active);
    if (active && !beforeIds.has(active.composerId)) {
        return { composerId: active.composerId, title: active.title };
    }
    if (active && PLACEHOLDER_TITLE.test(active.title.trim())) {
        return { composerId: active.composerId, title: active.title };
    }
    return {};
}
