"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.runCatalogSearchWorkerSelection = runCatalogSearchWorkerSelection;
exports.applyCatalogSearchWorkerSelection = applyCatalogSearchWorkerSelection;
exports.renderCatalogSearchTarget = renderCatalogSearchTarget;
const errors_1 = require("../worker/errors");
async function runCatalogSearchWorkerSelection(input) {
    if (input.runtime.runCatalogSearchSelection === undefined) {
        return { kind: "fallback", reason: "worker_runtime_unsupported" };
    }
    try {
        const result = await input.runtime.runCatalogSearchSelection({
            prompt: input.query,
            kind: input.kind,
            mode: input.mode,
            target: input.target,
            workspacePath: input.repositoryRoot,
            repositoryRoot: input.repositoryRoot,
            outputLanguage: input.outputLanguage,
        });
        if (result.kind === "deferred") {
            return { kind: "fallback", reason: result.reason };
        }
        return {
            kind: "selected",
            selected: result.launchResult.selection.selected,
        };
    }
    catch (error) {
        return {
            kind: "fallback",
            reason: formatCatalogSearchWorkerError(error),
        };
    }
}
function applyCatalogSearchWorkerSelection(input) {
    const canonicalItemIdsBySelectionId = new Map();
    for (const item of input.items) {
        for (const selectionId of input.itemSelectionIds?.(item) ?? [item.id]) {
            const canonicalIds = canonicalItemIdsBySelectionId.get(selectionId) ?? new Set();
            canonicalIds.add(item.id);
            canonicalItemIdsBySelectionId.set(selectionId, canonicalIds);
        }
    }
    const seenCanonicalIds = new Set();
    const selected = [];
    const rejected = [];
    for (const item of input.selected) {
        const canonicalIds = canonicalItemIdsBySelectionId.get(item.id);
        const canonicalId = canonicalIds?.size === 1 ? [...canonicalIds][0] : undefined;
        if (canonicalId === undefined ||
            !Number.isFinite(item.confidence) ||
            item.confidence < 0 ||
            item.confidence > 1) {
            rejected.push(item);
            continue;
        }
        if (seenCanonicalIds.has(canonicalId)) {
            continue;
        }
        seenCanonicalIds.add(canonicalId);
        selected.push({ ...item, id: canonicalId });
    }
    const selectedOrder = new Map(selected.map((item, index) => [item.id, index]));
    return {
        items: [...input.items].sort((left, right) => {
            const leftOrder = selectedOrder.get(left.id);
            const rightOrder = selectedOrder.get(right.id);
            if (leftOrder !== undefined || rightOrder !== undefined) {
                return ((leftOrder ?? Number.MAX_SAFE_INTEGER) -
                    (rightOrder ?? Number.MAX_SAFE_INTEGER));
            }
            return 0;
        }),
        selected,
        rejected,
    };
}
function renderCatalogSearchTarget(input) {
    return input.target ?? input.targets.join(",");
}
function formatCatalogSearchWorkerError(error) {
    if ((0, errors_1.isWorkerFailureError)(error)) {
        return error.failureKind;
    }
    return error instanceof Error ? error.message : String(error);
}
