'use strict';

const { SourceAdapterBase } = require('./base');
const {
  cleanUserText,
  extractMessageText,
  extractToolCalls,
  fileVersion,
  looksLikeToolResult,
  readJsonlFile,
  sourceIdFromFile,
  toIso,
} = require('./jsonl-utils');
const { buildExchangeRecords, messageToRecords } = require('./coding-session-utils');

class ClaudeCodeJsonlAdapter extends SourceAdapterBase {
  static schema = {
    adapterId: 'claude-code-jsonl',
    version: '1.0.0',
    supportsIncremental: true,
    defaultPrivacyClass: 'pii_potential',
    declaredTransformations: [
      'newline_normalize',
      'strip_tool_chrome',
      'base64_payload_omit',
      'tool_result_summarize',
      'whitespace_trim',
      'exchange_pair_chunk',
    ],
    fields: {
      sourceId: { type: 'string', required: true },
      sourceFile: { type: 'string', required: true },
      cwd: { type: 'string', required: false },
      gitBranch: { type: 'string', required: false },
    },
  };

  validateSource(source) {
    const normalized = super.validateSource(source);
    if (!source.sourceId) normalized.sourceId = sourceIdFromFile('claude', normalized.sourceFile || normalized.uri);
    return normalized;
  }

  async *ingest({ source, context }) {
    const filePath = source.sourceFile || source.uri;
    const version = fileVersion(filePath);
    const { events, diagnostics } = readJsonlFile(filePath);
    for (const diagnostic of diagnostics) context?.warn?.(diagnostic.message, diagnostic);

    const messages = [];
    for (const { line, event } of events) {
      if (!event?.message || !['user', 'assistant'].includes(event.type)) continue;
      const role = event.message.role || event.type;
      if (!['user', 'assistant'].includes(role)) continue;
      let content = extractMessageText(event.message);
      if (role === 'user') content = cleanUserText(content);
      if (!content || looksLikeToolResult(content)) continue;

      const message = {
        itemId: event.uuid || `line-${line}`,
        role,
        content,
        timestamp: toIso(event.timestamp || event.message.timestamp),
        cwd: event.cwd || source.cwd || '',
        gitBranch: event.gitBranch || source.metadata?.gitBranch || '',
        rawType: event.type,
        harness: 'claude-code',
        toolCalls: extractToolCalls(event.message),
      };
      messages.push(message);
      for (const record of messageToRecords({ source, message, version })) yield record;
    }

    for (const record of buildExchangeRecords(source, messages)) yield record;
  }
}

module.exports = ClaudeCodeJsonlAdapter;
