import { ChatPanelContext, TerminalEntry } from '../types/terminal';

export const extractChatPanelContext = (
  history: TerminalEntry[],
): ChatPanelContext | undefined => {
  for (let index = history.length - 1; index >= 0; index -= 1) {
    const entry = history[index];
    if (entry.type !== 'panel' || typeof entry.content === 'string') {
      continue;
    }

    let sourceCommand: string | undefined;
    for (let commandIndex = index - 1; commandIndex >= 0; commandIndex -= 1) {
      const candidate = history[commandIndex];
      if (
        candidate.type === 'command' &&
        typeof candidate.content === 'string' &&
        candidate.content.startsWith('/')
      ) {
        sourceCommand = candidate.content;
        break;
      }
    }

    return {
      sourceCommand,
      capturedAt: entry.timestamp?.toISOString(),
      panel: entry.content,
    };
  }

  return undefined;
};
