import { createContext, getContext, saveContext, updateContext, loadContext } from '../utils/contextStore';
import { orchestratorLogger as logger } from '../utils/logger';
import { narrator, setVoiceEnabled } from '../utils/voice';
import * as protocols from '../protocols';

type ProtocolName = keyof typeof protocols;

interface OrchestratorOptions {
  feature: string;
  protocol?: ProtocolName;
  voice?: boolean;
  resume?: string;
}

export const runOrchestrator = async (options: OrchestratorOptions) => {
  const { feature, protocol = 'fullRoundtrip', voice = false, resume } = options;
  setVoiceEnabled(voice);

  if (resume) {
    await loadContext(resume);
    logger.info(`Resuming orchestration for specId: ${resume}`);
    narrator.speak(`Resuming orchestration for specId: ${resume}`);
  } else {
    createContext(feature);
    logger.info(`Starting orchestration for feature: \"${feature}\"`);
    narrator.speak(`Starting orchestration for feature: ${feature}`);
  }

  const selectedProtocol = protocols[protocol];
  if (!selectedProtocol) {
    throw new Error(`Unknown protocol: ${protocol}`);
  }

  await selectedProtocol();

  const context = getContext();
  // ... (keep the existing finalBundle logic)

  const savedPath = await saveContext();
  logger.success(`Orchestration complete. Context saved to ${savedPath}`);
  narrator.speak('All agents have completed their tasks. The final bundle is ready.');

  return getContext();
};
