'use strict';

function normalizeContextMessagesForChat(messages, currentMessage = '') {
  const raw = Array.isArray(messages) ? messages : [];
  const normalized = [];
  for (const item of raw) {
    if (!item || typeof item !== 'object') continue;
    const role = String(item.role || '').trim();
    if (role !== 'user' && role !== 'assistant') continue;
    const content = typeof item.content === 'string'
      ? item.content
      : (typeof item.text === 'string' ? item.text : '');
    if (!content) continue;
    normalized.push({ role, content });
  }
  const current = String(currentMessage || '');
  if (current) {
    const last = normalized[normalized.length - 1];
    if (!last || last.role !== 'user' || last.content !== current) {
      normalized.push({ role: 'user', content: current });
    } else {
      last.content = current;
    }
  }
  return normalized.slice(-60);
}

module.exports = { normalizeContextMessagesForChat };
