/**
 * Session file parsers for Claude, Codex, Gemini, and OpenCode.
 *
 * Each agent stores sessions in a different format (JSONL, JSON, SQLite).
 * This module normalizes all of them into a flat array of SessionEvent
 * objects suitable for rendering, filtering, and summarization.
 */

import * as fs from 'fs';
import * as path from 'path';
import { execFileSync } from 'child_process';
import type { SessionAgentId, SessionEvent } from './types.js';

/**
 * Largest session file we will load into memory. Above this we throw a clean
 * error instead of OOMing or hitting V8's ERR_STRING_TOO_LONG. Aligns with
 * Node's ~512MB string ceiling with a healthy margin.
 */
export const SESSION_FILE_MAX_BYTES = 200_000_000;

/**
 * Strip terminal control sequences that a malicious session file could use to
 * hijack the user's terminal (clipboard via OSC 52, scrollback wipe, alt-screen
 * takeover, cursor moves, etc.). Allowed through: tab (0x09), newline (0x0a),
 * carriage return (0x0d). Everything else in the C0/C1 range and every CSI/OSC
 * escape is dropped.
 */
const TERMINAL_ESCAPE_REGEX = /\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b\[[0-?]*[ -/]*[@-~]|\x1b[@-_]|[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]/g;

export function sanitizeForTerminal(s: string): string {
  if (typeof s !== 'string' || !s) return s;
  return s.replace(TERMINAL_ESCAPE_REGEX, '');
}

/** Recursively sanitize every string value within a tool-args object. */
function sanitizeArgsDeep(value: any): any {
  if (typeof value === 'string') return sanitizeForTerminal(value);
  if (Array.isArray(value)) return value.map(sanitizeArgsDeep);
  if (value && typeof value === 'object') {
    const out: Record<string, any> = {};
    for (const k of Object.keys(value)) out[k] = sanitizeArgsDeep(value[k]);
    return out;
  }
  return value;
}

/** In-place sanitize all user-visible string fields on an event. */
function sanitizeEvent(e: SessionEvent): void {
  if (e.content) e.content = sanitizeForTerminal(e.content);
  if (e.command) e.command = sanitizeForTerminal(e.command);
  if (e.path) e.path = sanitizeForTerminal(e.path);
  if (e.output) e.output = sanitizeForTerminal(e.output);
  if (e.tool) e.tool = sanitizeForTerminal(e.tool);
  if (e.model) e.model = sanitizeForTerminal(e.model);
  if (e.mediaType) e.mediaType = sanitizeForTerminal(e.mediaType);
  if (e.args) e.args = sanitizeArgsDeep(e.args);
}

/**
 * Read a session file, refusing files above maxBytes. Bounded read protects
 * against multi-GB session blobs that would OOM the CLI or exceed V8's
 * ERR_STRING_TOO_LONG ceiling.
 */
export function safeReadSessionFile(filePath: string, maxBytes: number = SESSION_FILE_MAX_BYTES): string {
  const stat = fs.statSync(filePath);
  if (stat.size > maxBytes) {
    throw new Error(
      `Session file too large: ${filePath} is ${stat.size} bytes (limit ${maxBytes}). Refusing to load.`,
    );
  }
  return fs.readFileSync(filePath, 'utf-8');
}

/**
 * Auto-detect agent type from file path and parse the session.
 */
export function parseSession(filePath: string, agent?: SessionAgentId): SessionEvent[] {
  const detected = agent || detectAgent(filePath);
  if (!detected) {
    throw new Error(`Cannot detect agent type from path: ${filePath}`);
  }

  let events: SessionEvent[];
  switch (detected) {
    case 'claude': events = parseClaude(filePath); break;
    case 'codex': events = parseCodex(filePath); break;
    case 'gemini': events = parseGemini(filePath); break;
    case 'opencode': events = parseOpenCode(filePath); break;
    case 'grok': events = parseGrok(filePath); break;
    case 'rush': events = parseRush(filePath); break;
    case 'openclaw': events = []; break; // OpenClaw sessions don't have parseable files yet
    case 'hermes': events = parseHermes(filePath); break;
    case 'kimi': events = []; break; // Kimi event parsing not implemented yet — discover.ts builds metadata only
  }

  // Chokepoint: every string field that originated in an untrusted session
  // file gets stripped of terminal escapes here, so renderers downstream can
  // safely splat values into chalk/console output.
  for (const e of events) sanitizeEvent(e);
  return events;
}

/** Infer the agent type from a session file path using known directory conventions. */
export function detectAgent(filePath: string): SessionAgentId | null {
  if (filePath.includes('/.claude/') || filePath.includes('\\.claude\\')) return 'claude';
  if (filePath.includes('/.codex/') || filePath.includes('\\.codex\\')) return 'codex';
  if (filePath.includes('/.gemini/') || filePath.includes('\\.gemini\\')) return 'gemini';
  if (filePath.includes('/.grok/') || filePath.includes('\\.grok\\')) return 'grok';
  if (filePath.includes('/.rush/') || filePath.includes('\\.rush\\')) return 'rush';
  if (filePath.includes('/.hermes/') || filePath.includes('\\.hermes\\')) return 'hermes';
  // Cloud convention: cloud-sessions/<id>/session.<format>.jsonl
  const cloudMatch = filePath.match(/session\.(claude|codex|rush)\.jsonl(?:$|[?#])/);
  if (cloudMatch) return cloudMatch[1] as SessionAgentId;
  if (filePath.includes('opencode.db')) return 'opencode';

  // Try file extension + content heuristic
  if (filePath.endsWith('.json')) return 'gemini';
  return null;
}

/**
 * Summarize a tool_use into a one-liner string.
 */
export function summarizeToolUse(tool: string, args?: Record<string, any>): string {
  if (!args) return tool;

  switch (tool) {
    case 'Bash':
      return `Bash: ${truncate(String(args.command || '').replace(/\n/g, ' ').trim(), 120)}`;
    case 'Read':
      return `Read ${shortenPath(args.file_path || '')}`;
    case 'Write':
      return `Write ${shortenPath(args.file_path || '')}`;
    case 'Edit':
      return `Edit ${shortenPath(args.file_path || '')}`;
    case 'Glob':
      return `Glob ${args.pattern || ''}`;
    case 'Grep':
      return `Grep ${args.pattern || ''} ${args.path || ''}`.trim();
    case 'Agent':
      return `Agent: ${truncate(args.description || args.prompt || '', 80)}`;
    case 'WebSearch':
    case 'WebFetch':
      return `${tool}: ${truncate(args.query || args.url || '', 80)}`;
    // Codex tools
    case 'exec_command':
      return `Bash: ${truncate(String(args.command || args.cmd || '').replace(/\n/g, ' ').trim(), 120)}`;
    case 'read_file':
      return `Read ${shortenPath(args.file_path || args.path || '')}`;
    case 'write_file':
    case 'create_file':
      return `Write ${shortenPath(args.file_path || args.path || '')}`;
    case 'edit_file':
      return `Edit ${shortenPath(args.file_path || args.path || '')}`;
    // Gemini tools
    case 'run_shell_command':
      return `Bash: ${truncate(String(args.command || '').replace(/\n/g, ' ').trim(), 120)}`;
    case 'search_file_content':
      return `Search ${args.pattern || ''}`;
    default: {
      // Generic: show first meaningful arg
      for (const key of ['file_path', 'path', 'pattern', 'command', 'prompt', 'query', 'url']) {
        if (args[key]) return `${tool}: ${truncate(String(args[key]), 80)}`;
      }
      return tool;
    }
  }
}

/** Truncate a string to n characters, appending '...' if shortened. */
function truncate(s: string, n: number): string {
  return s.length <= n ? s : s.slice(0, n - 3) + '...';
}

/** Replace the home directory prefix with ~ for display. */
function shortenPath(p: string): string {
  const home = process.env.HOME || '';
  if (home && p.startsWith(home)) return '~' + p.slice(home.length);
  return p;
}

// ---------------------------------------------------------------------------
// Claude parser
// ---------------------------------------------------------------------------

/** Parse a Claude JSONL session file into normalized events. */
export function parseClaude(filePath: string): SessionEvent[] {
  const content = safeReadSessionFile(filePath);
  const lines = content.split('\n').filter(l => l.trim());
  const events: SessionEvent[] = [];

  // Map tool_use id -> {tool, args} for correlating with tool_result
  const toolUseMap = new Map<string, { tool: string; args: Record<string, any> }>();

  for (const line of lines) {
    let raw: any;
    try {
      raw = JSON.parse(line);
    } catch {
      /* malformed JSONL line, skip */
      continue;
    }

    const type = raw.type;
    const timestamp = raw.timestamp || new Date().toISOString();

    if (type === 'assistant') {
      const contentBlocks = raw.message?.content || [];
      for (const block of contentBlocks) {
        if (block.type === 'thinking') {
          // Thinking content -- may be encrypted (has .signature field)
          const thinkingText = block.thinking || '';
          if (thinkingText) {
            events.push({
              type: 'thinking',
              agent: 'claude',
              timestamp,
              content: thinkingText,
            });
          }
        } else if (block.type === 'text') {
          const text = (block.text || '').trim();
          if (text) {
            events.push({
              type: 'message',
              agent: 'claude',
              timestamp,
              role: 'assistant',
              content: text,
            });
          }
        } else if (block.type === 'tool_use') {
          const toolName = block.name || 'unknown';
          const toolInput = block.input || {};
          const toolId = block.id;
          const isLocal = toolInput.is_local === true;

          if (toolId) {
            toolUseMap.set(toolId, { tool: toolName, args: toolInput });
          }

          const event: any = {
            type: 'tool_use',
            agent: 'claude' as const,
            timestamp,
            tool: toolName,
            args: toolInput,
            path: toolInput.file_path || undefined,
            command: toolName === 'Bash' ? toolInput.command : undefined,
          };
          if (isLocal) event._local = true;
          events.push(event);
        }
      }
      // Capture token usage and model from assistant turn
      if (raw.message?.usage) {
        const u = raw.message.usage;
        events.push({
          type: 'usage',
          agent: 'claude',
          timestamp,
          model: raw.message.model,
          inputTokens: u.input_tokens,
          outputTokens: u.output_tokens,
          cacheReadTokens: u.cache_read_input_tokens,
          cacheCreationTokens: u.cache_creation_input_tokens,
        });
      }
    } else if (type === 'user') {
      const contentBlocks = raw.message?.content;

      if (typeof contentBlocks === 'string') {
        // Simple user text
        const text = contentBlocks.trim();
        if (text) {
          events.push({
            type: 'message',
            agent: 'claude',
            timestamp,
            role: 'user',
            content: text,
          });
        }
      } else if (Array.isArray(contentBlocks)) {
        for (const block of contentBlocks) {
          if (block.type === 'text') {
            const text = (block.text || '').trim();
            if (text && !text.startsWith('[Request interrupted')) {
              events.push({
                type: 'message',
                agent: 'claude',
                timestamp,
                role: 'user',
                content: text,
              });
            }
          } else if (block.type === 'image') {
            const source = block.source || {};
            if (source.type === 'base64') {
              const sizeBytes = Math.ceil(((source.data as string)?.length || 0) * 0.75);
              events.push({
                type: 'attachment',
                agent: 'claude',
                timestamp,
                mediaType: source.media_type || 'image/png',
                sizeBytes,
              });
            }
          } else if (block.type === 'document') {
            const source = block.source || {};
            events.push({
              type: 'attachment',
              agent: 'claude',
              timestamp,
              mediaType: source.media_type || 'application/pdf',
              sizeBytes: 0,
            });
          } else if (block.type === 'tool_result') {
            const toolId = block.tool_use_id;
            const toolInfo = toolId ? toolUseMap.get(toolId) : undefined;
            const isError = block.is_error === true;

            // Extract output text from tool result
            let output = '';
            if (typeof block.content === 'string') {
              output = block.content;
            } else if (Array.isArray(block.content)) {
              output = block.content
                .filter((c: any) => c.type === 'text')
                .map((c: any) => c.text || '')
                .join('\n');
            }

            if (isError) {
              events.push({
                type: 'error',
                agent: 'claude',
                timestamp,
                tool: toolInfo?.tool,
                content: output || 'Tool execution failed',
              });
            } else {
              events.push({
                type: 'tool_result',
                agent: 'claude',
                timestamp,
                tool: toolInfo?.tool,
                success: true,
                output: output.length > 500 ? output.slice(0, 497) + '...' : output,
              });
            }

            if (toolId) toolUseMap.delete(toolId);
          }
        }
      }
    } else if (type === 'result') {
      events.push({
        type: 'result',
        agent: 'claude',
        timestamp,
        content: raw.subtype || 'success',
      });
    }
    // Skip: permission-mode, attachment, and other line types
  }

  return events;
}

// ---------------------------------------------------------------------------
// Codex parser
// ---------------------------------------------------------------------------

/** Parse a Codex JSONL session file into normalized events. */
export function parseCodex(filePath: string): SessionEvent[] {
  const content = safeReadSessionFile(filePath);
  const lines = content.split('\n').filter(l => l.trim());
  const events: SessionEvent[] = [];

  // Track function_call id -> name for correlating with function_call_output
  const callMap = new Map<string, { name: string; args: any }>();

  for (const line of lines) {
    let raw: any;
    try {
      raw = JSON.parse(line);
    } catch {
      /* malformed JSONL line, skip */
      continue;
    }

    const lineType = raw.type;
    const timestamp = raw.timestamp || new Date().toISOString();
    const payload = raw.payload || {};

    if (lineType === 'session_meta') {
      events.push({
        type: 'init',
        agent: 'codex',
        timestamp,
        content: `Codex ${payload.cli_version || ''} session in ${payload.cwd || ''}`.trim(),
      });
      continue;
    }

    if (lineType === 'response_item') {
      const ptype = payload.type;

      if (ptype === 'message') {
        const contentBlocks = payload.content || [];
        const role = payload.role === 'user' || payload.role === 'developer' ? 'user' : 'assistant';

        for (const block of contentBlocks) {
          if (block.type === 'output_text') {
            const text = (block.text || '').trim();
            if (text) {
              events.push({
                type: 'message',
                agent: 'codex',
                timestamp,
                role: 'assistant',
                content: text,
              });
            }
          } else if (block.type === 'input_text') {
            // Developer/user input messages -- only include actual prompts, not system instructions
            const text = (block.text || '').trim();
            if (text && text.length < 2000 && !text.includes('<permissions instructions>')) {
              events.push({
                type: 'message',
                agent: 'codex',
                timestamp,
                role: 'user',
                content: text,
              });
            }
          }
        }
      } else if (ptype === 'function_call') {
        const name = payload.name || 'unknown';
        let args: any = {};
        try {
          args = typeof payload.arguments === 'string'
            ? JSON.parse(payload.arguments)
            : (payload.arguments || {});
        } catch {
          /* arguments not valid JSON, preserve raw */
          args = { raw: payload.arguments };
        }

        const callId = payload.call_id || payload.id;
        if (callId) {
          callMap.set(callId, { name, args });
        }

        events.push({
          type: 'tool_use',
          agent: 'codex',
          timestamp,
          tool: name,
          args,
          command: name === 'exec_command' ? (args.command || args.cmd) : undefined,
          path: args.file_path || args.path || undefined,
        });
      } else if (ptype === 'function_call_output') {
        const callId = payload.call_id || payload.id;
        const callInfo = callId ? callMap.get(callId) : undefined;
        const output = String(payload.output || '');

        events.push({
          type: 'tool_result',
          agent: 'codex',
          timestamp,
          tool: callInfo?.name,
          success: true,
          output: output.length > 500 ? output.slice(0, 497) + '...' : output,
        });

        if (callId) callMap.delete(callId);
      } else if (ptype === 'reasoning') {
        // Codex reasoning -- try to get the readable summary
        const summaries = payload.summary || [];
        const text = summaries.length > 0
          ? summaries.map((s: any) => s.text || '').join('\n')
          : (payload.text || '');
        if (text.trim()) {
          events.push({
            type: 'thinking',
            agent: 'codex',
            timestamp,
            content: text.trim(),
          });
        }
      }
    }
    // Skip: event_msg (token_count, etc.), turn_context
  }

  return events;
}

// ---------------------------------------------------------------------------
// Gemini parser
// ---------------------------------------------------------------------------

/** Parse a Gemini JSON session file into normalized events. */
export function parseGemini(filePath: string): SessionEvent[] {
  const content = safeReadSessionFile(filePath);
  let session: any;
  try {
    session = JSON.parse(content);
  } catch {
    /* Gemini session file is not valid JSON */
    throw new Error(`Failed to parse Gemini session: ${filePath}`);
  }

  const messages = session.messages || [];
  const events: SessionEvent[] = [];

  events.push({
    type: 'init',
    agent: 'gemini',
    timestamp: session.startTime || new Date().toISOString(),
    content: `Gemini session ${session.sessionId || ''}`.trim(),
  });

  for (const msg of messages) {
    const timestamp = msg.timestamp || session.startTime || new Date().toISOString();

    if (msg.type === 'user') {
      const text = extractGeminiContent(msg.content);
      if (text) {
        events.push({
          type: 'message',
          agent: 'gemini',
          timestamp,
          role: 'user',
          content: text,
        });
      }
    } else if (msg.type === 'gemini') {
      // Reasoning thoughts
      if (Array.isArray(msg.thoughts)) {
        for (const thought of msg.thoughts) {
          const text = thought.description || thought.subject || '';
          if (text.trim()) {
            const subject = thought.subject ? `**${thought.subject}**: ` : '';
            events.push({
              type: 'thinking',
              agent: 'gemini',
              timestamp: thought.timestamp || timestamp,
              content: `${subject}${thought.description || ''}`.trim(),
            });
          }
        }
      }

      // Assistant text
      const text = extractGeminiContent(msg.content);
      if (text) {
        events.push({
          type: 'message',
          agent: 'gemini',
          timestamp,
          role: 'assistant',
          content: text,
        });
      }

      // Tool calls (Gemini inlines call + result on the same message)
      if (Array.isArray(msg.toolCalls)) {
        for (const tc of msg.toolCalls) {
          const toolName = tc.name || 'unknown';
          const args = tc.args || {};

          events.push({
            type: 'tool_use',
            agent: 'gemini',
            timestamp: tc.timestamp || timestamp,
            tool: toolName,
            args,
            command: ['run_shell_command', 'shell', 'bash'].includes(toolName) ? args.command : undefined,
            path: args.file_path || args.path || undefined,
          });

          // Inline result
          if (tc.result || tc.status) {
            let output = '';
            if (Array.isArray(tc.result)) {
              for (const r of tc.result) {
                const resp = r?.functionResponse?.response;
                if (resp?.output) {
                  output += String(resp.output);
                }
              }
            } else if (typeof tc.result === 'string') {
              output = tc.result;
            }

            events.push({
              type: 'tool_result',
              agent: 'gemini',
              timestamp: tc.timestamp || timestamp,
              tool: toolName,
              success: tc.status === 'success',
              output: output.length > 500 ? output.slice(0, 497) + '...' : output,
            });
          }
        }
      }
    }
  }

  return events;
}

/**
 * Extract text content from Gemini's content field,
 * which can be a string or an array of {text: string} parts.
 */
function extractGeminiContent(content: any): string {
  if (typeof content === 'string') return content.trim();
  if (Array.isArray(content)) {
    return content
      .map((part: any) => {
        if (typeof part === 'string') return part;
        if (typeof part?.text === 'string') return part.text;
        return '';
      })
      .join('\n')
      .trim();
  }
  return '';
}

// ---------------------------------------------------------------------------
// OpenCode parser
// ---------------------------------------------------------------------------

/**
 * Parse an OpenCode session from its SQLite database.
 * filePath format: "/path/to/opencode.db#session_id"
 *
 * Data model: session -> message -> part
 * Messages have role (user/assistant) and metadata.
 * Parts contain the actual content: text, tool, reasoning, patch, step-start/finish.
 */
export function parseGrok(filePath: string): SessionEvent[] {
  // Grok sessions are rich (summary.json + events.jsonl + chat_history.jsonl + updates.jsonl)
  // This is a minimal stub for now so grok appears in `agents sessions`.
  // Full parser (with subagents, tool calls, etc.) can be expanded later.
  try {
    const content = fs.readFileSync(filePath, 'utf-8');
    // If it's a summary.json, create a basic event
    if (filePath.endsWith('summary.json')) {
      const summary = JSON.parse(content);
      return [{
        timestamp: summary.created_at || new Date().toISOString(),
        type: 'session_start',
        content: summary.session_summary || 'Grok session',
        agent: 'grok',
        metadata: { sessionId: summary.id, cwd: summary.cwd },
      } as any];
    }
    // For JSONL files (events, chat_history, updates), return basic parsed lines
    if (filePath.endsWith('.jsonl')) {
      const lines = content.trim().split('\n').filter(Boolean);
      return lines.slice(0, 50).map((line, i) => {
        try {
          const obj = JSON.parse(line);
          return {
            timestamp: obj.timestamp || obj.ts || new Date().toISOString(),
            type: obj.type || obj.method || 'grok_event',
            content: typeof obj.content === 'string' ? obj.content : JSON.stringify(obj).slice(0, 200),
            agent: 'grok',
          } as any;
        } catch {
          return { timestamp: new Date().toISOString(), type: 'raw', content: line.slice(0, 200), agent: 'grok' } as any;
        }
      });
    }
  } catch {}
  return [];
}

export function parseOpenCode(filePath: string): SessionEvent[] {
  const [dbPath, sessionId] = filePath.split('#');
  if (!dbPath || !sessionId) return [];

  const events: SessionEvent[] = [];

  try {
    // Query messages with their parts, ordered chronologically.
    // Each row: msg_role ||| part_type ||| part_data (truncated for tool output) ||| msg_time
    const query = `
      SELECT
        json_extract(m.data, '$.role'),
        json_extract(p.data, '$.type'),
        CASE
          WHEN json_extract(p.data, '$.type') = 'tool'
          THEN substr(p.data, 1, 2000)
          ELSE p.data
        END,
        m.time_created
      FROM message m
      JOIN part p ON p.message_id = m.id AND p.session_id = m.session_id
      WHERE m.session_id = '${sessionId.replace(/'/g, "''")}'
      ORDER BY m.time_created ASC, p.time_created ASC;
    `.replace(/\n/g, ' ');

    const out = execFileSync('sqlite3', ['-separator', '|||', dbPath, query], {
      encoding: 'utf-8',
      timeout: 10000,
      maxBuffer: 32 * 1024 * 1024,
      stdio: ['ignore', 'pipe', 'ignore'],
    });

    for (const line of out.split('\n')) {
      if (!line.trim()) continue;

      const sepIdx1 = line.indexOf('|||');
      if (sepIdx1 === -1) continue;
      const sepIdx2 = line.indexOf('|||', sepIdx1 + 3);
      if (sepIdx2 === -1) continue;
      const sepIdx3 = line.lastIndexOf('|||');

      const role = line.slice(0, sepIdx1);
      const partType = line.slice(sepIdx1 + 3, sepIdx2);
      const partDataStr = line.slice(sepIdx2 + 3, sepIdx3);
      const timeStr = line.slice(sepIdx3 + 3);

      const timeMs = parseInt(timeStr, 10);
      const timestamp = isNaN(timeMs) ? new Date().toISOString() : new Date(timeMs).toISOString();

      let partData: any;
      try {
        partData = JSON.parse(partDataStr);
      } catch {
        /* malformed part data, skip */
        continue;
      }

      switch (partType) {
        case 'text': {
          const text = (partData.text || '').trim();
          if (text) {
            events.push({
              type: 'message',
              agent: 'opencode',
              timestamp,
              role: role === 'user' ? 'user' : 'assistant',
              content: text,
            });
          }
          break;
        }
        case 'reasoning': {
          const text = (partData.text || '').trim();
          if (text) {
            events.push({
              type: 'thinking',
              agent: 'opencode',
              timestamp,
              content: text,
            });
          }
          break;
        }
        case 'tool': {
          const toolName = partData.tool || 'unknown';
          const state = partData.state || {};
          const input = state.input || {};
          const output = state.output || '';

          events.push({
            type: 'tool_use',
            agent: 'opencode',
            timestamp,
            tool: toolName,
            args: input,
            command: toolName === 'shell' ? input.command : undefined,
            path: input.filePath || input.path || undefined,
          });

          if (state.status === 'completed' || state.status === 'error') {
            const outputStr = typeof output === 'string' ? output : JSON.stringify(output);
            events.push({
              type: state.status === 'error' ? 'error' : 'tool_result',
              agent: 'opencode',
              timestamp,
              tool: toolName,
              success: state.status === 'completed',
              output: outputStr.length > 500 ? outputStr.slice(0, 497) + '...' : outputStr,
            });
          }
          break;
        }
        // Skip step-start, step-finish, patch, file — not needed for transcript/trace
      }
    }
  } catch {
    /* DB not accessible or query failed */
  }

  return events;
}

// ---------------------------------------------------------------------------
// Rush parser
//
// Rush messages.jsonl format is flat: one JSON object per line with
//   { id, session_id, role, type, content, created_at, tool_call_id?, name? }
// type ∈ {message, tool_call, tool_result}
// content varies by type:
//   message     -> { text: string }
//   tool_call   -> { input: {...} }
//   tool_result -> { input, output } (output.success === false marks an error)
// ---------------------------------------------------------------------------

/** Parse a Rush JSONL session file into normalized events. */
export function parseRush(filePath: string): SessionEvent[] {
  const content = safeReadSessionFile(filePath);
  const lines = content.split('\n').filter(l => l.trim());
  const events: SessionEvent[] = [];

  // Map tool_call id -> {tool, args} for correlating with tool_result.
  const toolCallMap = new Map<string, { tool: string; args: Record<string, any> }>();

  for (const line of lines) {
    let raw: any;
    try {
      raw = JSON.parse(line);
    } catch {
      /* malformed JSONL line, skip */
      continue;
    }

    const type = raw.type;
    const timestamp = raw.created_at || new Date().toISOString();
    const content = raw.content || {};

    if (type === 'message') {
      const text = typeof content.text === 'string' ? content.text.trim() : '';
      if (!text) continue;

      const role: 'user' | 'assistant' = raw.role === 'user' ? 'user' : 'assistant';
      // Rush wraps the first user turn in <user_input>...</user_input> — strip.
      const cleaned = text
        .replace(/^<user_input>/, '')
        .replace(/<\/user_input>$/, '')
        .trim();

      // Skip sentinel execution-start marker that isn't human-readable.
      if (raw.role === 'system' && cleaned === 'execution_start') continue;

      events.push({
        type: 'message',
        agent: 'rush',
        timestamp,
        role,
        content: cleaned,
      });
    } else if (type === 'tool_call') {
      const toolName = raw.name || 'unknown';
      const args = content.input || {};
      const callId = raw.tool_call_id;
      if (callId) toolCallMap.set(callId, { tool: toolName, args });

      events.push({
        type: 'tool_use',
        agent: 'rush',
        timestamp,
        tool: toolName,
        args,
        path: args.file_path || args.path || undefined,
        command: (toolName === 'Bash' || toolName === 'shell') ? args.command : undefined,
      });
    } else if (type === 'tool_result') {
      const callId = raw.tool_call_id;
      const info = callId ? toolCallMap.get(callId) : undefined;
      const output = content.output;

      let outputStr = '';
      if (typeof output === 'string') {
        outputStr = output;
      } else if (output !== undefined) {
        try {
          outputStr = JSON.stringify(output);
        } catch {
          outputStr = String(output);
        }
      }

      const success = output?.success !== false;
      events.push({
        type: success ? 'tool_result' : 'error',
        agent: 'rush',
        timestamp,
        tool: info?.tool ?? raw.name,
        success,
        output: outputStr.length > 500 ? outputStr.slice(0, 497) + '...' : outputStr,
      });

      if (callId) toolCallMap.delete(callId);
    }
  }

  return events;
}

// ---------------------------------------------------------------------------
// Hermes parser
//
// Hermes stores one JSON file per session at ~/.hermes/sessions/session_<id>.json:
//   { session_id, model, platform, session_start, last_updated,
//     system_prompt, message_count, messages: [{role, content}, ...] }
// Content may be a string or an array of text parts.
// ---------------------------------------------------------------------------

/** Parse a Hermes session JSON file into normalized events. */
export function parseHermes(filePath: string): SessionEvent[] {
  let session: any;
  try {
    session = JSON.parse(safeReadSessionFile(filePath));
  } catch {
    return [];
  }

  const messages = Array.isArray(session.messages) ? session.messages : [];
  const timestamp = typeof session.session_start === 'string'
    ? session.session_start
    : new Date().toISOString();

  const events: SessionEvent[] = [];
  for (const msg of messages) {
    const role = msg?.role === 'user' ? 'user' : 'assistant';
    const text = hermesContentToText(msg?.content);
    if (!text) continue;
    events.push({
      type: 'message',
      agent: 'hermes',
      timestamp,
      role,
      content: text,
    });
  }

  return events;
}

function hermesContentToText(content: any): string {
  if (typeof content === 'string') return content.trim();
  if (!Array.isArray(content)) return '';
  return content
    .map((part: any) => {
      if (typeof part === 'string') return part;
      if (typeof part?.text === 'string') return part.text;
      return '';
    })
    .join('\n')
    .trim();
}
