import { getChatProvider } from '../../lib/providers';
import { hydrateInternalInterruptions, toPublicInterruption } from './interruptions';
/**
 * Generates a unique id for tracking pending agent runs across reloads.
 */
export const createRunId = () => `run-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
/**
 * Converts the in-memory pending run into a persistable snapshot, guarding against serialization failures.
 */
export const serializePendingRun = (pending) => {
    try {
        return {
            version: 1,
            id: pending.id,
            createdAt: pending.startedAt,
            updatedAt: pending.updatedAt,
            state: pending.state.toString(),
            assistantText: pending.assistantText,
            toolCalls: pending.toolCalls.map((entry) => ({ ...entry })),
            reasoningEvents: pending.reasoningEvents.map((entry) => ({ ...entry })),
            messageEvents: pending.messageEvents.map((entry) => ({ ...entry })),
            interruptions: pending.interruptions.map((entry) => toPublicInterruption(entry)),
            providerId: pending.providerId
        };
    }
    catch (error) {
        console.error('Failed to serialize pending run state', error);
        return null;
    }
};
/**
 * Rehydrates a serialized pending run back into a live RunState with interruption handles.
 */
export const restorePendingRun = async (serialized, agent, providerId) => {
    const provider = getChatProvider(providerId);
    if (typeof provider.deserializeRunState !== 'function') {
        throw new Error(`Provider "${providerId}" does not support restoring pending runs`);
    }
    const state = await provider.deserializeRunState(agent, serialized.state);
    const interruptions = hydrateInternalInterruptions(serialized.id, serialized.interruptions, state.getInterruptions?.() ?? []);
    return {
        id: serialized.id,
        startedAt: serialized.createdAt,
        updatedAt: serialized.updatedAt,
        state,
        interruptions,
        assistantText: serialized.assistantText,
        toolCalls: serialized.toolCalls.map((entry) => ({ ...entry })),
        reasoningEvents: serialized.reasoningEvents.map((entry) => ({ ...entry })),
        messageEvents: serialized.messageEvents.map((entry) => ({ ...entry })),
        providerId: (serialized.providerId ?? providerId)
    };
};
