import { parseIntent } from './dialog.types';
import { enqueue, flush } from './toolcalls.queue';

export async function handleTranscript(
  text: string,
  ctx: {
    lastInsight?: any;
    pin?: (i: any) => void;
    openSummary?: () => void;
    closeSummary?: () => void;
    exportFns?: {
      logsCSV: () => void;
      logsJSON: () => void;
      pinsCSV: () => void;
      pinsPDF: () => void;
    };
    snapshotFns?: { start: () => void; stop: () => void };
  }
) {
  const intent = parseIntent(text);
  if (!intent) return { reply: 'Say: help' };

  switch (intent.kind) {
    case 'PIN':
      enqueue({ type: 'PIN_INSIGHT', payload: { insight: ctx.lastInsight } });
      break;
    case 'OPEN_SUMMARY':
      ctx.openSummary?.();
      break;
    case 'CLOSE_SUMMARY':
      ctx.closeSummary?.();
      break;
    case 'EXPORT_LOGS_CSV':
      ctx.exportFns?.logsCSV();
      break;
    case 'EXPORT_LOGS_JSON':
      ctx.exportFns?.logsJSON();
      break;
    case 'EXPORT_CSV':
      ctx.exportFns?.pinsCSV();
      break;
    case 'EXPORT_PDF':
      ctx.exportFns?.pinsPDF();
      break;
    case 'AUTO_START':
      ctx.snapshotFns?.start();
      break;
    case 'AUTO_STOP':
      ctx.snapshotFns?.stop();
      break;
    case 'HELP':
    default:
      break;
  }
  await flush(ctx);
  return { reply: intent.reply || 'Done.' };
}
