import { Company } from '../types/financial';
import {
  TerminalCommandResponse,
  TickerHistorySnapshot,
} from '../types/terminal';

const FREQUENCY_ARGS = new Set(['annual', 'quarterly']);
const TICKER_REQUIRED_COMMANDS = new Set([
  '/fa',
  '/bs',
  '/cf',
  '/dvd',
  '/filings',
  '/concepts',
  '/mappings',
  '/em',
  '/analyze',
]);
const FREQUENCY_OPTION_COMMANDS = new Set([
  '/fa',
  '/bs',
  '/cf',
  '/concepts',
  '/mappings',
  '/em',
]);

export const extractTickerSymbolFromResponse = (
  response: TerminalCommandResponse,
): string | null => {
  if (response.kind !== 'panel') {
    return null;
  }

  const { panel } = response;

  switch (panel.type) {
    case 'company':
      return panel.data.symbol;
    case 'financials':
    case 'balanceSheet':
    case 'cashFlow':
    case 'dividends':
    case 'earnings':
    case 'filings':
    case 'analysis':
      return panel.data.symbol;
    case 'news':
      return panel.ticker?.trim() || null;
    case 'error':
    case 'portfolio':
      return null;
    default:
      return null;
  }
};

export const companyToTickerHistorySnapshot = (
  company: Company,
): TickerHistorySnapshot => ({
  symbol: company.symbol,
  name: company.name,
  price: company.price,
  change: company.change,
  changePercent: company.changePercent,
  volume: company.volume,
  marketCap: company.marketCap,
});

export const resolveTickerCommandFallback = (
  command: string,
  latestTicker: string | null | undefined,
): string => {
  const trimmedCommand = command.trim();

  if (!trimmedCommand.startsWith('/') || !latestTicker) {
    return trimmedCommand;
  }

  const parts = trimmedCommand.split(/\s+/);
  const commandName = parts[0]?.toLowerCase();

  if (!TICKER_REQUIRED_COMMANDS.has(commandName)) {
    return trimmedCommand;
  }

  if (parts.length === 1) {
    return `${commandName} ${latestTicker}`;
  }

  const firstArg = parts[1]?.toLowerCase();
  if (commandName === '/mappings' && firstArg === 'add') {
    return trimmedCommand;
  }

  if (
    FREQUENCY_OPTION_COMMANDS.has(commandName) &&
    FREQUENCY_ARGS.has(firstArg)
  ) {
    return [commandName, latestTicker, ...parts.slice(1)].join(' ');
  }

  return trimmedCommand;
};
