import { parseHtmlDocument } from "../../html-document.js";
import { decodeHtmlEntities, normalizeCandidate } from "./cleaner.js";
import { pickFirstText, safeHostname } from "./utils.js";
const ALLOWED_TEXT_TAGS = new Set(["title"]);
export function extractMetadataFromHtml(html, url) {
    const parsed = parseHtmlDocument(html);
    const { document } = parsed;
    try {
        const title = pickFirstText([
            pickMetaContent(document, [
                { attribute: "property", value: "og:title" },
                { attribute: "name", value: "og:title" },
                { attribute: "name", value: "twitter:title" },
            ]),
            extractTagText(document, "title"),
        ]);
        const description = pickFirstText([
            pickMetaContent(document, [
                { attribute: "property", value: "og:description" },
                { attribute: "name", value: "description" },
                { attribute: "name", value: "twitter:description" },
            ]),
        ]);
        const siteName = pickFirstText([
            pickMetaContent(document, [
                { attribute: "property", value: "og:site_name" },
                { attribute: "name", value: "application-name" },
            ]),
            safeHostname(url),
        ]);
        return { title, description, siteName };
    }
    finally {
        parsed.close();
    }
}
export function extractMetadataFromFirecrawl(metadata) {
    return {
        title: pickFirstText([metadataString(metadata, "title"), metadataString(metadata, "ogTitle")]),
        description: pickFirstText([
            metadataString(metadata, "description"),
            metadataString(metadata, "ogDescription"),
        ]),
        siteName: pickFirstText([
            metadataString(metadata, "siteName"),
            metadataString(metadata, "ogSiteName"),
        ]),
    };
}
function pickMetaContent(document, selectors) {
    for (const selector of selectors) {
        const meta = document.querySelector(`meta[${selector.attribute}="${selector.value}"]`);
        if (!meta)
            continue;
        const value = meta.getAttribute("content") ?? meta.getAttribute("value") ?? "";
        const normalized = normalizeCandidate(decodeHtmlEntities(value));
        if (normalized) {
            return normalized;
        }
    }
    return null;
}
function extractTagText(document, tagName) {
    const normalizedTag = tagName.trim().toLowerCase();
    if (!ALLOWED_TEXT_TAGS.has(normalizedTag)) {
        return null;
    }
    const element = document.querySelector(normalizedTag);
    if (!element)
        return null;
    const text = decodeHtmlEntities(element.textContent ?? "");
    return normalizeCandidate(text);
}
function metadataString(metadata, key) {
    if (!metadata) {
        return null;
    }
    const value = metadata[key];
    return typeof value === "string" ? normalizeCandidate(value) : null;
}
//# sourceMappingURL=parsers.js.map