// DCP message shape adapter.
// Converts between BooCode MessagePart[] and the DCP internal shape.
// Clean-room implementation — no AGPL source copied.

export interface DcpMessage {
  role: 'user' | 'assistant' | 'tool';
  content: string;
  tool_call_id?: string;
  tool_calls?: Array<{ id: string; name: string; arguments: string }>;
  isError?: boolean;
}

export function toDcpMessages(parts: any[]): DcpMessage[] {
  return parts.map((p: any) => {
    const msg: DcpMessage = { role: p.role, content: p.content ?? '' };
    if (p.tool_call_id) msg.tool_call_id = p.tool_call_id;
    if (p.tool_calls) msg.tool_calls = p.tool_calls;
    if (p.isError) msg.isError = true;
    if (p.role === 'tool' && p.content && p.content.startsWith('Error:')) {
      msg.isError = true;
    }
    return msg;
  });
}

export function fromDcpMessages(msgs: DcpMessage[]): any[] {
  return msgs.map((m) => ({
    role: m.role,
    content: m.content,
    ...(m.tool_call_id ? { tool_call_id: m.tool_call_id } : {}),
    ...(m.tool_calls ? { tool_calls: m.tool_calls } : {}),
    ...(m.isError ? { isError: true } : {}),
  }));
}
