import type { Sql } from '../db.js';
import { snapshotToPartPayload, type AcpToolSnapshot } from "./acp-tool-snapshot.js";

interface PartInsert {
  message_id: string;
  sequence: number;
  kind: 'reasoning' | 'tool_call';
  payload: unknown;
}

async function insertParts(sql: Sql, parts: PartInsert[]): Promise<void> {
  if (parts.length === 0) return;
  await sql`
    INSERT INTO message_parts ${sql(
      parts.map((p) => ({
        message_id: p.message_id,
        sequence: p.sequence,
        kind: p.kind,
        payload: sql.json(p.payload as never),
      })),
      'message_id',
      'sequence',
      'kind',
      'payload',
    )}
  `;
}

/** Persist external-agent reasoning + tool calls into message_parts for reload. */
export async function persistExternalAgentTurn(
  sql: Sql,
  assistantMessageId: string,
  snapshots: AcpToolSnapshot[],
  reasoningText: string,
): Promise<void> {
  const parts: PartInsert[] = [];
  let seq = 0;
  if (reasoningText.trim()) {
    parts.push({
      message_id: assistantMessageId,
      sequence: seq++,
      kind: 'reasoning',
      payload: { text: reasoningText },
    });
  }
  for (const snapshot of snapshots) {
    parts.push({
      message_id: assistantMessageId,
      sequence: seq++,
      kind: 'tool_call',
      payload: snapshotToPartPayload(snapshot),
    });
  }
  await insertParts(sql, parts);
}
