'use strict';

/**
 * Exchange chunker: groups consecutive human + AI message pairs into atomic exchange units.
 * Ported from MemPalace convo_miner.py exchange-pair chunking.
 *
 * When searching for "what did I say about X?", finding the Q+A pair together
 * is much more useful than finding the question or answer alone.
 */

/**
 * Chunk a conversation transcript into exchange pairs.
 * Each exchange = one human message + the following AI response.
 *
 * @param {Array<object>} messages - Array of { role: 'user'|'assistant', content: string, timestamp? }
 * @param {object} [opts] - Options
 * @param {number} [opts.maxChunkLength=1500] - Max length per exchange chunk
 * @returns {Array<object>} Array of { content, participants, direction: 'exchange', timestamp }
 */
function chunkExchanges(messages, opts = {}) {
  if (!messages || messages.length < 2) return [];
  const maxLen = opts.maxChunkLength || 1500;
  const exchanges = [];

  let i = 0;
  while (i < messages.length) {
    const msg = messages[i];

    // Look for user message followed by assistant response
    if (msg.role === 'user' && i + 1 < messages.length && messages[i + 1].role === 'assistant') {
      const userMsg = msg.content || '';
      const aiMsg = messages[i + 1].content || '';

      // Combine as exchange
      let combined = `Q: ${userMsg}\nA: ${aiMsg}`;

      // Truncate if too long
      if (combined.length > maxLen) {
        combined = combined.slice(0, maxLen) + '...';
      }

      exchanges.push({
        content: combined,
        direction: 'exchange',
        timestamp: msg.timestamp || messages[i + 1].timestamp,
        participants: msg.participants || null,
      });

      i += 2; // skip both messages
    } else {
      i++;
    }
  }

  return exchanges;
}

/**
 * Extract exchange pairs from a chat session's message history.
 * @param {string} sessionId - Chat session ID
 * @param {object} brain - Brain module reference
 * @returns {Array<object>} Exchange chunks ready for insertMemory
 */
function extractSessionExchanges(sessionId, brain) {
  if (!sessionId || !brain) return [];

  try {
    const messages = brain.listChatMessages(sessionId);
    if (!messages || messages.length < 2) return [];

    const formatted = messages.map(m => ({
      role: m.role,
      content: m.content,
      timestamp: m.created_at,
    }));

    return chunkExchanges(formatted);
  } catch {
    return [];
  }
}

module.exports = { chunkExchanges, extractSessionExchanges };
