/**
 * Shared run-event persistence.
 *
 * Every contributor to a run's event log — the pi agent runner, the
 * agent-driven internal mutations, and the Bevy test launcher — appends through
 * this single helper so sequence numbering and the JSON shape stay consistent.
 */

import { db } from '../db.js';

const insertEvent = db.prepare(
  `INSERT INTO agent_run_events (run_id, seq, type, data, created_at)
   VALUES (?, ?, ?, ?, ?)`,
);

/** Next monotonic sequence number for a run's event log. */
export function nextSeq(runId: string): number {
  return (
    db
      .prepare('SELECT COALESCE(MAX(seq), 0) + 1 AS n FROM agent_run_events WHERE run_id = ?')
      .get(runId) as { n: number }
  ).n;
}

export interface AppendedEvent {
  seq: number;
  createdAt: string;
}

/**
 * Append a slim event to a run's persisted history.
 *
 * `type` is the discriminator the UI renders on; `data` carries its payload.
 * Returns the assigned sequence number and timestamp so in-process subscribers
 * (e.g. the SSE stream) can dedup against history they've already flushed.
 */
export function appendRunEvent(
  runId: string,
  type: string,
  data: Record<string, unknown>,
): AppendedEvent {
  const seq = nextSeq(runId);
  const createdAt = new Date().toISOString();
  insertEvent.run(runId, seq, type, JSON.stringify(data), createdAt);
  return { seq, createdAt };
}
