import { request } from 'undici';
import { slugify } from './slugify.js';
import { t } from '../i18n/translate.js';
const SITEMAP_URL = 'https://docs-v2.thinkingdata.cn/te-doc/5.0/zh-CN.json';
const DOCS_PAGE_BASE = 'https://docs-v2.thinkingdata.cn/?version=v5.0&lan=zh-CN&code=';
export async function fetchSitemap() {
    const { body, statusCode } = await request(SITEMAP_URL);
    if (statusCode !== 200)
        throw new Error(t('error.sitemap_fetch_failed', { statusCode }));
    return (await body.json());
}
export function filterInstallationSubtree(nodes) {
    const root = nodes.find((n) => n.code === 'installation_menu');
    if (!root)
        throw new Error(t('error.installation_menu_not_found'));
    const byToken = new Map();
    for (const n of nodes)
        byToken.set(n.wikiToken, n);
    const inSubtree = new Set([root.wikiToken]);
    let changed = true;
    while (changed) {
        changed = false;
        for (const n of nodes) {
            if (!inSubtree.has(n.wikiToken) && inSubtree.has(n.parentWikiToken)) {
                inSubtree.add(n.wikiToken);
                changed = true;
            }
        }
    }
    const pages = [];
    for (const n of nodes) {
        if (!inSubtree.has(n.wikiToken) || n.wikiToken === root.wikiToken)
            continue;
        if (n.type !== 'docx')
            continue;
        const segs = [];
        let cur = n;
        while (cur && cur.wikiToken !== root.wikiToken) {
            segs.unshift(slugify(cur.name, cur.wikiToken));
            cur = cur.parentWikiToken ? byToken.get(cur.parentWikiToken) : undefined;
        }
        pages.push({
            wikiToken: n.wikiToken,
            code: n.code,
            name: n.name,
            updateTime: n.updateTime,
            parentWikiToken: n.parentWikiToken,
            pathSegments: segs,
            outPath: `wiki/te-docs/raw/${segs.join('/')}.md`,
            sourceUrl: `${DOCS_PAGE_BASE}${encodeURIComponent(n.code)}`,
        });
    }
    // Disambiguate duplicate outPaths: keep first occurrence unchanged,
    // append -<wikiToken.slice(0,6)> before .md for subsequent duplicates.
    const byPath = new Map();
    for (const p of pages)
        byPath.set(p.outPath, (byPath.get(p.outPath) ?? 0) + 1);
    const seen = new Set();
    for (const p of pages) {
        if ((byPath.get(p.outPath) ?? 0) > 1 && seen.has(p.outPath)) {
            const suffix = `-${p.wikiToken.slice(0, 6)}`;
            const newOut = p.outPath.replace(/\.md$/, `${suffix}.md`);
            const lastSeg = p.pathSegments[p.pathSegments.length - 1] + suffix;
            p.pathSegments = [...p.pathSegments.slice(0, -1), lastSeg];
            p.outPath = newOut;
        }
        else {
            seen.add(p.outPath);
        }
    }
    return pages;
}
