import type { ResearchNavigationIntent, ResearchWorkspace } from '../types/research';
import type { TerminalEntry } from '../types/terminal';
import { extractResearchContext } from './researchContext';
import { buildTerminalResearchNoteSeed } from './terminalResearchNote';

const FALLBACK_CURRENT_CONTEXT_TEXT =
  'Current terminal context is not available yet.\n\nAnalyst note:';

export const resolveTerminalResearchCaptureIntent = (
  command: string,
  history: TerminalEntry[],
): ResearchNavigationIntent | null => {
  const normalized = command.trim().toLowerCase();
  const researchContext = extractResearchContext(history);

  if (normalized === '/notes add') {
    return {
      ticker: researchContext?.ticker,
      terminalNoteSeed: {
        rawText: '',
        ticker: researchContext?.ticker,
        contextLabel: researchContext?.label ?? 'Quick note from terminal',
      },
    };
  }

  if (normalized === '/notes current') {
    const seed = buildTerminalResearchNoteSeed(history);
    const ticker = seed?.ticker ?? researchContext?.ticker;

    return {
      ticker,
      terminalNoteSeed: {
        rawText: seed?.rawText ?? FALLBACK_CURRENT_CONTEXT_TEXT,
        ticker,
        contextLabel:
          seed?.contextLabel ?? researchContext?.label ?? 'Current terminal context',
      },
    };
  }

  return null;
};

export const resolveTerminalCaptureWorkspaceId = ({
  ticker,
  workspaces,
  activeWorkspaceId,
}: {
  ticker?: string;
  workspaces: ResearchWorkspace[];
  activeWorkspaceId?: string | null;
}): string | undefined => {
  const normalizedTicker = ticker?.trim().toUpperCase();
  if (normalizedTicker) {
    return workspaces.find(
      (workspace) => workspace.primaryTicker.trim().toUpperCase() === normalizedTicker,
    )?.id;
  }

  if (activeWorkspaceId) {
    return activeWorkspaceId;
  }

  return workspaces.length === 1 ? workspaces[0].id : undefined;
};
