import { PlannerAgent, ResearcherAgent, ReflectorAgent, WriterAgent } from './factory';
import { AgentEngine, PipelineStage, AgentExecuteOptions } from '../lib/engine';
import { getConfig } from '../config';

export class AgentWorkflowManager {
    /**
     * 리팩토링된 고성능 에이전트 엔진을 통해 워크플로우를 실행합니다.
     */
    public static async runStrictWorkflow(
        prompt: string,
        modelName: string,
        brainContext: string,
        signal: AbortSignal,
        onProgress: (step: string, message: string) => void
    ): Promise<string> {
        const planner = new PlannerAgent(modelName);
        const researcher = new ResearcherAgent(modelName);
        const writer = new WriterAgent(modelName);
        // [Self-Reflection] 설정으로 비활성화하지 않은 경우에만 Reflector를 주입.
        const enableReflection = getConfig().enableReflection !== false;
        const reflector = enableReflection ? new ReflectorAgent(modelName) : undefined;
        const engine = new AgentEngine(planner, researcher, writer, reflector);
        const missionId = `mission_${Date.now()}`;

        const runOptions: AgentExecuteOptions = {
            config: { enableReflection }
        };

        try {
            return await engine.runMission(
                missionId,
                prompt,
                brainContext,
                signal,
                (stage: PipelineStage, message: string) => {
                    onProgress(this.mapStageToUI(stage), message);
                },
                runOptions
            );
        } catch (error: any) {
            if (error.name === 'AbortError' || error.message.includes('cancelled')) {
                throw error;
            }
            throw new Error(`[Workflow Manager] ${error.message}`);
        }
    }

    private static mapStageToUI(stage: PipelineStage): string {
        const maps: Record<PipelineStage, string> = {
            idle: '대기',
            planner: 'Planner',
            researcher: 'Researcher',
            reflector: 'Reflector',
            writer: 'Writer',
            completed: '완료',
            error: '오류'
        };
        return maps[stage] || '진행 중';
    }
}
