import type { TerminalEntry } from '../types/terminal';

export interface TerminalResearchContext {
  ticker?: string;
  label: string;
  sourceCommand?: string;
}

export const extractResearchContext = (
  history: TerminalEntry[],
): TerminalResearchContext | null => {
  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;
      }
    }

    switch (entry.content.type) {
      case 'company':
        return {
          ticker: entry.content.data.symbol,
          label: `${entry.content.data.symbol} company snapshot`,
          sourceCommand,
        };
      case 'analysis':
        return {
          ticker: entry.content.data.symbol,
          label: `${entry.content.data.symbol} analysis panel`,
          sourceCommand,
        };
      case 'news':
        return {
          ticker: entry.content.ticker ?? entry.content.data[0]?.tickers[0],
          label: `${entry.content.ticker ?? 'Market'} news context`,
          sourceCommand,
        };
      case 'financials':
        return {
          ticker: entry.content.data.symbol,
          label: `${entry.content.data.symbol} financials`,
          sourceCommand,
        };
      case 'balanceSheet':
        return {
          ticker: entry.content.data.symbol,
          label: `${entry.content.data.symbol} balance sheet`,
          sourceCommand,
        };
      case 'cashFlow':
      case 'dividends':
      case 'earnings':
      case 'filings':
        return {
          ticker: entry.content.data.symbol,
          label: `${entry.content.data.symbol} ${entry.content.type}`,
          sourceCommand,
        };
      default:
        break;
    }
  }

  return null;
};
