"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.normalizeSearchText = normalizeSearchText;
exports.tokenizeSearchText = tokenizeSearchText;
exports.searchTextMatches = searchTextMatches;
exports.scoreSearchText = scoreSearchText;
function normalizeSearchText(value) {
    return value
        .toLowerCase()
        .replace(/[-_:/]+/gu, " ")
        .replace(/\s+/gu, " ")
        .trim();
}
function tokenizeSearchText(value) {
    return normalizeSearchText(value)
        .split(" ")
        .filter((token) => token.length > 0);
}
function searchTextMatches(item, query) {
    return scoreSearchText(item, query) > 0;
}
function scoreSearchText(item, query) {
    const normalizedQuery = normalizeSearchText(query);
    const tokens = tokenizeSearchText(query);
    if (normalizedQuery.length === 0 || tokens.length === 0) {
        return 0;
    }
    const id = normalizeSearchText(item.id);
    const title = normalizeSearchText(item.title ?? "");
    const description = normalizeSearchText(item.description ?? "");
    const topicTexts = (item.topics ?? []).flatMap((topic) => [
        normalizeSearchText(topic),
        normalizeSearchText(item.topicDescriptions?.get(topic) ?? ""),
    ]);
    const haystack = [id, title, description, ...topicTexts].join(" ");
    if (!tokens.every((token) => haystack.includes(token))) {
        return 0;
    }
    let score = 1;
    if (id === normalizedQuery) {
        score += 10_000;
    }
    if (topicTexts.some((topicText) => topicText === normalizedQuery)) {
        score += 6_000;
    }
    if (topicTexts.some((topicText) => topicText.includes(normalizedQuery))) {
        score += 4_000;
    }
    if (title === normalizedQuery && title !== id) {
        score += 1_500;
    }
    if (id.includes(normalizedQuery) || title.includes(normalizedQuery)) {
        score += 1_000;
    }
    if (description.includes(normalizedQuery)) {
        score += 500;
    }
    for (const token of tokens) {
        if (topicTexts.some((topicText) => topicText.includes(token))) {
            score += 120;
        }
        if (id.includes(token) || title.includes(token)) {
            score += 100;
        }
        if (description.includes(token)) {
            score += 50;
        }
    }
    return score;
}
