/**
 * Shared, pure builder for the debug-log timeline entries (`message` / `turn` / `event`) — the
 * common core of the host element's `buildDiagnosticEntries` and any HEADLESS consumer that drives
 * a `ChatDriver` of its own (e.g. `ai-service` running the engine server-side) and needs to harvest
 * that engine's debug log for the client to fold into its own download / persisted stream
 * (GENC-1461 unified diagnostics). DOM-clean and dependency-light so it works in bare Node.
 *
 * It deliberately excludes the `meta-snapshot` entry: that block is host/DOM-specific (it reads
 * `window.location.host`, the element's agent list, live context/cost), and a merged log keeps only
 * the newest snapshot anyway — a headless source's agent/prompt/tools are already captured in its
 * `turn` entries.
 *
 * @packageDocumentation
 */
import { flattenSubAgentMessages } from '../../utils/flatten-sub-agent-messages';
/**
 * Build the `message` / `turn` / `event` timeline entries from a driver's pull surfaces
 * (`getRawHistory()` / `getTurnSnapshots()` / `getMetaEvents(sessionKey)`). Order within the array
 * is message → turn → event; the caller (`assembleDebugLog`) sorts the whole timeline by timestamp,
 * so this ordering only sets the co-timestamp tie-break. Pure.
 */
export function buildTimelineEntries(input) {
    const { turnSnapshots, messages, metaEvents } = input;
    // Collapse a turn's systemPrompt when byte-identical to the previous turn's — a stable agent
    // repeats the same (often multi-KB) prompt every turn, while a stateful agent's changes. The
    // prompt is shown in full whenever it changes, so prompt evolution stays visible.
    let lastFullPrompt;
    let lastFullIndex = '';
    const turns = turnSnapshots.map((t) => {
        let { systemPrompt } = t;
        if (systemPrompt != null && systemPrompt === lastFullPrompt) {
            systemPrompt = `<repeated — identical to turn ${lastFullIndex}>`;
        }
        else if (systemPrompt != null) {
            lastFullPrompt = systemPrompt;
            lastFullIndex = t.turnIndex;
        }
        return Object.assign(Object.assign({ kind: 'turn' }, t), { systemPrompt });
    });
    // Sub-agent conversations are stored nested on the parent tool call's `subAgentTrace`;
    // `flattenSubAgentMessages` hoists them to top-level `kind: 'message'` entries (breadcrumbed +
    // correlated, the nested copy moved out — not duplicated) so the timeline reads chronologically.
    const messageEntries = flattenSubAgentMessages(messages);
    const eventEntries = metaEvents.map((e) => (Object.assign({ kind: 'event' }, e)));
    return [...messageEntries, ...turns, ...eventEntries];
}
