export function getHistorySearchItems(entries, query, limit = 9) {
    const normalized = query.trim().toLowerCase();
    const ranked = [];
    entries.forEach((entry, index) => {
        const text = entry.trim();
        if (!text)
            return;
        const lower = text.toLowerCase();
        const match = rankHistoryEntry(lower, normalized);
        if (!match)
            return;
        ranked.push({
            id: `${index}:${text.slice(0, 24)}`,
            text,
            firstLine: firstLine(text),
            lineCount: text.split(/\r?\n/).length,
            ageLabel: relativePositionLabel(index),
            match: match.match,
            rank: match.rank,
            index,
        });
    });
    ranked.sort((left, right) => {
        if (left.rank !== right.rank)
            return left.rank - right.rank;
        return left.index - right.index;
    });
    return ranked.slice(0, limit).map(({ rank: _rank, index: _index, ...item }) => item);
}
export function historySearchInsertText(item) {
    return item.text;
}
function rankHistoryEntry(lowerText, query) {
    if (!query)
        return { rank: 10, match: "all" };
    if (lowerText.includes(query))
        return { rank: 0, match: "exact" };
    if (isSubsequence(lowerText, query))
        return { rank: 1, match: "fuzzy" };
    return null;
}
function firstLine(text) {
    return text.split(/\r?\n/)[0]?.trim() || "(empty prompt)";
}
function relativePositionLabel(index) {
    if (index === 0)
        return "latest";
    return `-${index}`;
}
function isSubsequence(text, query) {
    let cursor = 0;
    for (let index = 0; index < text.length && cursor < query.length; index += 1) {
        if (text[index] === query[cursor])
            cursor += 1;
    }
    return cursor === query.length;
}
