import { buildSessionContext as buildSessionContextFromEntries } from '../core/session-schema.js';
import { EmbeddedSessionEntryBuilder } from './session-entry-builder.js';
export function createShortcutXLAgentSessionStore(options) {
    const builder = new EmbeddedSessionEntryBuilder();
    const entries = [];
    const getMessageIdOverride = (message) => 'id' in message && typeof message.id === 'string' && message.id.length > 0
        ? message.id
        : undefined;
    const getContextEntryIdOverride = (context, index, message) => {
        const contextEntryId = context.messageEntryIds?.[index];
        if (typeof contextEntryId === 'string' && contextEntryId.length > 0) {
            return contextEntryId;
        }
        return getMessageIdOverride(message);
    };
    const appendContextEntries = (context) => {
        if (context.model) {
            entries.push(builder.buildModelChange(context.model.provider, context.model.modelId));
        }
        if (context.thinkingLevel) {
            entries.push(builder.buildThinkingLevelChange(context.thinkingLevel));
        }
        for (const [index, message] of context.messages.entries()) {
            const idOverride = getContextEntryIdOverride(context, index, message);
            if (message.role === 'custom') {
                entries.push(builder.buildCustomMessage(message.customType, message.content, message.display, message.details, undefined, idOverride));
            }
            else {
                entries.push(builder.buildMessage(message, undefined, idOverride));
            }
        }
    };
    const preserveTraceEntries = (traceEntries) => {
        for (const entry of traceEntries) {
            entries.push({
                ...entry,
                parentId: builder.getLeafId()
            });
            builder.seedFromEntries(entries);
        }
    };
    const appendContextEntriesWithTraces = (context, traceEntries) => {
        if (context.model) {
            entries.push(builder.buildModelChange(context.model.provider, context.model.modelId));
        }
        if (context.thinkingLevel) {
            entries.push(builder.buildThinkingLevelChange(context.thinkingLevel));
        }
        let traceIndex = 0;
        for (const [index, message] of context.messages.entries()) {
            if (message.role === 'assistant' && traceIndex < traceEntries.length) {
                preserveTraceEntries([traceEntries[traceIndex]]);
                traceIndex += 1;
            }
            const idOverride = getContextEntryIdOverride(context, index, message);
            if (message.role === 'custom') {
                entries.push(builder.buildCustomMessage(message.customType, message.content, message.display, message.details, undefined, idOverride));
            }
            else {
                entries.push(builder.buildMessage(message, undefined, idOverride));
            }
        }
        preserveTraceEntries(traceEntries.slice(traceIndex));
    };
    if (options.entries && options.entries.length > 0) {
        entries.push(...options.entries);
        builder.seedFromEntries(entries);
    }
    else if (options.context) {
        appendContextEntries(options.context);
    }
    const append = (entry) => {
        entries.push(entry);
        return entry.id;
    };
    const sessionStore = {
        buildSessionContext: () => buildSessionContextFromEntries(entries),
        getSessionId: () => options.sessionId,
        getEntries: () => entries,
        getBranch: () => entries,
        getLeafId: () => builder.getLeafId(),
        reserveAssistantMessageEntryId: () => builder.reserveAssistantMessageEntryId(),
        appendMessage: (message, durationMs, idOverride) => append(builder.buildMessage(message, durationMs, idOverride)),
        appendCustomMessageEntry: (customType, content, display, details, timestamp) => append(builder.buildCustomMessage(customType, content, display, details, timestamp)),
        appendModelChange: (provider, modelId) => append(builder.buildModelChange(provider, modelId)),
        appendThinkingLevelChange: (thinkingLevel) => append(builder.buildThinkingLevelChange(thinkingLevel)),
        appendTurnStart: (turnIndex) => append(builder.buildTurnStart(turnIndex)),
        appendTurnEnd: (turnIndex, durationMs) => append(builder.buildTurnEnd(turnIndex, durationMs)),
        appendSystemPrompt: (content) => append(builder.buildSystemPrompt(content)),
        appendToolDefinitions: (tools) => append(builder.buildToolDefinitions(tools)),
        appendLlmCall: (input) => append(builder.buildLlmCall(input)),
        appendCompaction: (summary, firstKeptEntryId, tokensBefore, details, fromHook) => {
            const entry = builder.buildCompaction(summary, firstKeptEntryId, tokensBefore, details, fromHook ?? false);
            return append(entry);
        },
        truncateFrom: (entryId) => {
            const cutIndex = entries.findIndex((e) => e.id === entryId);
            if (cutIndex < 0)
                return false;
            entries.length = cutIndex;
            builder.seedFromEntries(entries);
            return true;
        }
    };
    return {
        getArtifacts() {
            return {
                context: structuredClone(buildSessionContextFromEntries(entries)),
                entries: structuredClone(entries),
                sessionId: options.sessionId
            };
        },
        replaceContext(context) {
            const traceEntries = entries.filter((entry) => entry.type === 'llm_call');
            entries.length = 0;
            builder.seedFromEntries([]);
            appendContextEntriesWithTraces(context, traceEntries);
        },
        sessionStore
    };
}
//# sourceMappingURL=session-store.js.map