import type { Page } from "@/lib/store";

const WIKI_LINK_RE = /\[\[([^[\]]+)\]\]/g;

function stripHtml(input: string): string {
    return input.replace(/<[^>]+>/g, " ");
}

export function extractWikiLinkTitles(content: string): string[] {
    const text = stripHtml(content || "");
    const result: string[] = [];
    const seen = new Set<string>();

    let match: RegExpExecArray | null;
    while ((match = WIKI_LINK_RE.exec(text)) !== null) {
        const title = (match[1] || "").trim();
        if (!title || seen.has(title)) continue;
        seen.add(title);
        result.push(title);
    }

    return result;
}

export function getOutgoingLinks(page: Page, pages: Page[]): Page[] {
    const titles = extractWikiLinkTitles(page.content || "");
    if (titles.length === 0) return [];
    const titleSet = new Set(titles);
    return pages.filter((p) => p.id !== page.id && p.type === "file" && titleSet.has((p.title || "").trim()));
}

export function getUnresolvedLinkTitles(page: Page, pages: Page[]): string[] {
    const titles = extractWikiLinkTitles(page.content || "");
    if (titles.length === 0) return [];
    const existing = new Set(
        pages
            .filter((p) => p.type === "file")
            .map((p) => (p.title || "").trim())
            .filter(Boolean)
    );
    return titles.filter((title) => !existing.has(title));
}

export function getBacklinks(target: Page, pages: Page[]): Page[] {
    const targetTitle = (target.title || "").trim();
    if (!targetTitle) return [];
    return pages.filter((p) => {
        if (p.id === target.id || p.type !== "file") return false;
        const titles = extractWikiLinkTitles(p.content || "");
        return titles.includes(targetTitle);
    });
}
