/**
 * Markdown 처리 유틸리티
 */

/**
 * Markdown 텍스트에서 [[WikiLink]] 및 [Label](/docs/ID) 패턴을 찾아 제목과 ID를 추출합니다.
 */
export function extractWikiLinks(content: string): { titles: string[], ids: string[] } {
    const titles = new Set<string>();
    const ids = new Set<string>();

    // 1. Match [[Title]] or [[Title|Label]]
    const wikiRegex = /\[\[([^\]]+)\]\]/g;
    let match;
    while ((match = wikiRegex.exec(content)) !== null) {
        const linkText = match[1];
        const title = linkText.split('|')[0].trim();
        if (title) titles.add(title);
    }

    // 2. Match [Label](/docs/ID)
    const mdRegex = /\[([^\]]+)\]\(\/docs\/([^)]+)\)/g;
    while ((match = mdRegex.exec(content)) !== null) {
        const label = match[1];
        const id = match[2];

        if (id.startsWith('new-')) {
            try {
                const title = decodeURIComponent(id.replace(/^new-/, ''));
                if (title) titles.add(title);
            } catch (e) {
                if (label) titles.add(label);
            }
        } else {
            // It's an existing doc ID.
            if (id) ids.add(id);
            // CRITICAL FIX: Add label to titles so 'outgoingLinks' is populated and backlinks queries succeed
            if (label) titles.add(label);
        }
    }

    return {
        titles: Array.from(titles),
        ids: Array.from(ids)
    };
}

/**
 * Unlinked Mentions 조회를 위한 텍스트 토크나이징
 * 간단하게 공백, 문장 부호 기준으로 단어 추출 후 중복 제거
 */
export function tokenizeContent(content: string): string[] {
    if (!content) return [];

    // 특수문자 제거 및 공백 기준 분리
    // 한글, 영문, 숫자 포함
    const words = content
        .toLowerCase()
        .replace(/[^\w\sㄱ-ㅎ가-힣]/g, ' ')
        .split(/\s+/)
        .filter(word => word.length >= 2); // 1글자 단어(조사 등)는 제외 고려

    return Array.from(new Set(words));
}
