/**
 * Long-running edit ops (e.g. copy-items) return from HTTP before CreatedItemIds exist.
 * EditorShell sends operation:completed over the socket with the final payload; we bridge
 * that to a window event so operations.duplicateItem / copyItems can await the result.
 */
export const EDIT_OPERATION_TERMINAL_EVENT = "parhelia:edit-operation-terminal";
const TERMINAL_RESULT_CACHE_KEY = "__parheliaEditOperationTerminalResults";
const TERMINAL_RESULT_TTL_MS = 5 * 60 * 1000;
export function editOperationNeedsTerminalCompletion(result) {
    if (result.errorMessage)
        return false;
    const ids = result.createdItemIds;
    if (Array.isArray(ids) && ids.length > 0)
        return false;
    const type = String(result.type ?? "");
    if (type === "copy-items" || type === "clone-items")
        return true;
    return (result.executionStatus === "executing" || result.isLongRunning === true);
}
export const copyItemsNeedsTerminalCompletion = editOperationNeedsTerminalCompletion;
export function normalizeOpId(id) {
    return String(id).replace(/[{}]/g, "").toLowerCase();
}
function getTerminalResultCache() {
    if (typeof window === "undefined") {
        return new Map();
    }
    const target = window;
    if (!target[TERMINAL_RESULT_CACHE_KEY]) {
        target[TERMINAL_RESULT_CACHE_KEY] = new Map();
    }
    return target[TERMINAL_RESULT_CACHE_KEY];
}
function pruneTerminalResultCache(cache, now) {
    for (const [key, value] of cache.entries()) {
        if (now - value.storedAt > TERMINAL_RESULT_TTL_MS) {
            cache.delete(key);
        }
    }
}
function getCachedEditOperationTerminalResult(operationId) {
    if (typeof window === "undefined")
        return undefined;
    const cache = getTerminalResultCache();
    const now = Date.now();
    pruneTerminalResultCache(cache, now);
    return cache.get(normalizeOpId(operationId))?.result;
}
export function cacheEditOperationTerminalResult(detail) {
    if (typeof window === "undefined")
        return;
    const operationId = detail.operationId ?? detail.id;
    if (!operationId)
        return;
    const cache = getTerminalResultCache();
    const now = Date.now();
    pruneTerminalResultCache(cache, now);
    cache.set(normalizeOpId(operationId), {
        result: {
            createdItemIds: detail.createdItemIds,
            errorMessage: detail.errorMessage,
            successCount: detail.successCount,
            failureCount: detail.failureCount,
            summary: detail.summary,
        },
        storedAt: now,
    });
}
export function waitForEditOperationTerminal(operationId, timeoutMs) {
    const want = normalizeOpId(operationId);
    const cachedResult = getCachedEditOperationTerminalResult(want);
    if (cachedResult) {
        return Promise.resolve(cachedResult);
    }
    return new Promise((resolve, reject) => {
        const timeout = setTimeout(() => {
            window.removeEventListener(EDIT_OPERATION_TERMINAL_EVENT, handler);
            reject(new Error("Operation timed out"));
        }, timeoutMs);
        const handler = (ev) => {
            const d = ev.detail;
            const oid = d.operationId ?? d.id;
            if (!oid || normalizeOpId(oid) !== want)
                return;
            clearTimeout(timeout);
            window.removeEventListener(EDIT_OPERATION_TERMINAL_EVENT, handler);
            resolve({
                createdItemIds: d.createdItemIds,
                errorMessage: d.errorMessage,
                successCount: d.successCount,
                failureCount: d.failureCount,
                summary: d.summary,
            });
        };
        window.addEventListener(EDIT_OPERATION_TERMINAL_EVENT, handler);
    });
}
//# sourceMappingURL=waitForEditOperationTerminal.js.map