'use strict';

const crypto = require('node:crypto');
const { normalizeToolCall: normalizeToolCallInput } = require('../llm/text-tool-calls');

function newId(prefix = 'msg') {
  return `${prefix}_${crypto.randomUUID ? crypto.randomUUID() : crypto.randomBytes(16).toString('hex')}`;
}

function textFromContent(content) {
  if (!content) return '';
  if (typeof content === 'string') return content;
  if (Array.isArray(content)) {
    return content.map((part) => {
      if (!part) return '';
      if (typeof part === 'string') return part;
      return part.text || part.content || '';
    }).filter(Boolean).join('\n');
  }
  if (typeof content === 'object') {
    if (content.text != null) return textFromContent(content.text);
    if (content.content != null) return textFromContent(content.content);
    try { return JSON.stringify(content); } catch { return String(content); }
  }
  return String(content);
}

function normalizeToolCall(call = {}, index = 0) {
  return normalizeToolCallInput({
    id: call.id || call.toolCallId || call.tool_use_id || newId(`tool_${index}`),
    name: call.name || call.tool || call.function?.name || '',
    input: call.input || call.arguments || call.function?.arguments || {},
  });
}

function assistantMessageFromResponse(response = {}) {
  const toolCalls = (response.toolCalls || []).map(normalizeToolCall);
  const content = [];
  if (response.reasoningContent) content.push({ type: 'reasoning', text: response.reasoningContent });
  if (response.content) content.push({ type: 'text', text: textFromContent(response.content) });
  for (const call of toolCalls) {
    content.push({ type: 'tool_use', id: call.id, name: call.name, input: call.input });
  }
  return {
    role: 'assistant',
    content: content.length === 1 && content[0].type === 'text' ? content[0].text : content,
  };
}

function toolResultMessage(toolResults = []) {
  return {
    role: 'user',
    content: toolResults.map((result) => ({
      type: 'tool_result',
      tool_use_id: result.toolCallId || result.id,
      content: textFromContent(result.content ?? result.result ?? result.error ?? ''),
      is_error: Boolean(result.error),
    })),
  };
}

module.exports = {
  newId,
  textFromContent,
  normalizeToolCall,
  assistantMessageFromResponse,
  toolResultMessage,
};
