import { createContext, getContext, loadContext, logToContext } from '../utils/contextStore';
import { orchestratorLogger as logger } from '../utils/logger';
import { narrator, setVoiceEnabled } from '../utils/voice';
import { AgentOrchestrator } from '../utils/agentOrchestrator';
import { AGENT_DEFINITIONS, getAgentsByPhase, getCriticalAgents } from '../configs/agentConfigs';

interface OrchestratorOptions {
  feature: string;
  voice?: boolean;
  resume?: string;
  maxConcurrent?: number;
  onStop?: (log: string[]) => void;
  onProgress?: (status: { completed: number; failed: number; running: number }) => void;
}

export const runOrchestrator = async (options: OrchestratorOptions) => {
  const { feature, voice = false, resume, maxConcurrent = 5, onStop, onProgress } = options;
  setVoiceEnabled(voice);

  let orchestrator: AgentOrchestrator | null = null;
  const isVerbose = process.env.DEBUG === 'true';

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

    // Only show orchestration plan in verbose mode
    if (isVerbose) {
      const phases = getAgentsByPhase();
      const criticalAgents = getCriticalAgents();
      
      logger.info(`Orchestration Plan:`);
      phases.forEach((agents, phase) => {
        const criticalInPhase = agents.filter(agent => criticalAgents.includes(agent));
        logger.info(`  Phase ${phase}: ${agents.join(', ')} ${criticalInPhase.length > 0 ? `(Critical: ${criticalInPhase.join(', ')})` : ''}`);
      });
    }

    // Create and configure orchestrator
    orchestrator = new AgentOrchestrator(maxConcurrent, onProgress);
    
    // Add all agent definitions
    AGENT_DEFINITIONS.forEach(definition => {
      orchestrator!.addAgent(definition);
    });

    // Run orchestration
    await orchestrator.runAll();

    const context = getContext();
    if (isVerbose) logger.success(`Orchestration completed successfully!`);

    if (onStop) {
      onStop(context.log);
    }

    return context;
  } catch (error) {
    if (isVerbose) logger.error(`Orchestration failed: ${error}`);
    logToContext(`ERROR: ${error}`);
    throw error;
  } finally {
    // Cleanup orchestrator
    if (orchestrator) {
      orchestrator.cleanup();
    }
  }
};
