'use strict';

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

class GeminiJsonlAdapter extends SourceAdapterBase {
  static schema = {
    adapterId: 'gemini-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 },
    },
  };

  validateSource(source) {
    const normalized = super.validateSource(source);
    if (!source.sourceId) normalized.sourceId = sourceIdFromFile('gemini', 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);

    let cwd = source.cwd || '';
    const messages = [];

    for (const { line, event } of events) {
      if (event.type === 'session_metadata' || event.session_metadata) {
        const meta = event.session_metadata || event;
        cwd = meta.cwd || meta.workspace || cwd;
        continue;
      }
      const rawRole = event.role || event.type || event.author || event.sender;
      const role = rawRole === 'model' || rawRole === 'gemini' || rawRole === 'assistant'
        ? 'assistant'
        : rawRole === 'user' ? 'user' : null;
      if (!role) continue;
      const content = role === 'user'
        ? cleanUserText(extractMessageText(event))
        : extractMessageText(event);
      if (!content || looksLikeToolResult(content)) continue;

      const message = {
        itemId: event.id || event.uuid || `line-${line}`,
        role,
        content,
        timestamp: toIso(event.timestamp || event.created_at),
        cwd,
        rawType: event.type || '',
        harness: 'gemini',
        toolCalls: [],
      };
      messages.push(message);
      for (const record of messageToRecords({ source, message, version })) yield record;
    }

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

module.exports = GeminiJsonlAdapter;
