'use strict';

const { INGEST_MODES, PRIVACY_CLASSES, RECORD_TYPES } = require('./record-types');
const { cleanedContent, toIso } = require('./jsonl-utils');

const DEFAULT_TEXT_TRANSFORMS = Object.freeze([
  'newline_normalize',
  'strip_tool_chrome',
  'base64_payload_omit',
  'tool_result_summarize',
  'whitespace_trim',
]);

function sourceItem({ source, itemId, version, timestamp, ingestMode, privacyClass, metadata }) {
  return {
    type: RECORD_TYPES.SOURCE_ITEM,
    sourceId: source.sourceId,
    sourceFile: source.sourceFile,
    itemId,
    version,
    timestamp: toIso(timestamp),
    ingestMode: ingestMode || INGEST_MODES.WHOLE_RECORD,
    privacyClass: privacyClass || source.privacyClass || PRIVACY_CLASSES.PII_POTENTIAL,
    metadata: metadata || {},
  };
}

function memoryRecord({
  source,
  itemId,
  memoryType,
  role,
  contentRaw,
  transforms = DEFAULT_TEXT_TRANSFORMS,
  timestamp,
  privacyClass,
  metadata,
}) {
  return {
    type: RECORD_TYPES.MEMORY_RECORD,
    sourceId: source.sourceId,
    sourceFile: source.sourceFile,
    itemId,
    role,
    memoryType,
    contentRaw,
    content: cleanedContent(contentRaw, transforms),
    transforms,
    timestamp: toIso(timestamp),
    ingestMode: INGEST_MODES.WHOLE_RECORD,
    privacyClass: privacyClass || source.privacyClass || PRIVACY_CLASSES.PII_POTENTIAL,
    metadata: metadata || {},
  };
}

function messageToRecords({ source, message, version }) {
  const metadata = {
    role: message.role,
    cwd: message.cwd || '',
    gitBranch: message.gitBranch || '',
    toolCalls: message.toolCalls || [],
    rawType: message.rawType || '',
    harness: message.harness || '',
  };
  const item = sourceItem({
    source,
    itemId: message.itemId,
    version,
    timestamp: message.timestamp,
    metadata,
  });
  const memory = memoryRecord({
    source,
    itemId: `${message.itemId}:message`,
    memoryType: message.memoryType || `coding_session_${message.role}_message`,
    role: message.role,
    contentRaw: message.content,
    timestamp: message.timestamp,
    metadata,
  });
  return [item, memory];
}

function buildExchangeRecords(source, messages) {
  const records = [];
  for (let i = 0; i < messages.length - 1; i++) {
    const user = messages[i];
    const assistant = messages[i + 1];
    if (user.role !== 'user' || assistant.role !== 'assistant') continue;
    const contentRaw = `Q: ${user.content}\nA: ${assistant.content}`;
    records.push(memoryRecord({
      source,
      itemId: `exchange:${user.itemId}:${assistant.itemId}`,
      memoryType: 'coding_session_exchange',
      role: 'exchange',
      contentRaw,
      transforms: [...DEFAULT_TEXT_TRANSFORMS, 'exchange_pair_chunk'],
      timestamp: user.timestamp || assistant.timestamp,
      metadata: {
        userItemId: user.itemId,
        assistantItemId: assistant.itemId,
        cwd: user.cwd || assistant.cwd || '',
        gitBranch: user.gitBranch || assistant.gitBranch || '',
        toolCalls: assistant.toolCalls || [],
      },
    }));
  }
  return records;
}

module.exports = {
  DEFAULT_TEXT_TRANSFORMS,
  buildExchangeRecords,
  memoryRecord,
  messageToRecords,
  sourceItem,
};
