/**
 * Orchestrator - 메인 오케스트레이터 클래스
 */
import { promises as fs } from 'fs';
import path from 'path';
import { parallelResearch, createResearchTasks, parallelResearchWithMultiLlm } from './parallelResearch.js';
import { MemoryManager } from '../lib/MemoryManager.js';
import { debugLog, errorLog } from '../lib/utils.js';
// 분리된 모듈 임포트
import { SmartRouter } from './SmartRouter.js';
import { LLMCluster } from './LLMCluster.js';
import { AgentManager } from './AgentManager.js';
import { backgroundManager } from './BackgroundManager.js';
/**
 * Core Orchestrator
 * 모든 /vibe.* 명령어의 오케스트레이션을 담당
 */
export class CoreOrchestrator {
    options;
    memoryManager;
    // 분리된 컴포넌트
    router;
    llmCluster;
    agentManager;
    constructor(options = {}) {
        this.options = {
            projectPath: process.cwd(),
            verbose: false,
            saveResults: true,
            resultsPath: '.claude/vibe/orchestrator',
            ...options
        };
        this.memoryManager = MemoryManager.getInstance(this.options.projectPath);
        // 컴포넌트 초기화
        this.router = new SmartRouter({ verbose: this.options.verbose });
        this.llmCluster = new LLMCluster();
        this.agentManager = new AgentManager({ projectPath: this.options.projectPath });
        // Registry 초기화 (프로젝트 경로가 있을 때만)
        if (this.options.projectPath) {
            backgroundManager.initRegistry(this.options.projectPath);
        }
    }
    // ============================================
    // Smart Routing (SmartRouter 위임)
    // ============================================
    async smartRoute(request) {
        return this.router.route(request);
    }
    async smartWebSearch(query) {
        return this.router.webSearch(query);
    }
    async smartArchitectureReview(prompt) {
        return this.router.architectureReview(prompt);
    }
    async smartUiuxReview(prompt) {
        return this.router.uiuxReview(prompt);
    }
    async smartCodeAnalysis(prompt) {
        return this.router.codeAnalysis(prompt);
    }
    async smartDebugging(prompt) {
        return this.router.debugging(prompt);
    }
    async smartCodeGen(description, context) {
        return this.router.codeGen(description, context);
    }
    // ============================================
    // Agent Management (AgentManager 위임)
    // ============================================
    async discoverAgents(category) {
        return this.agentManager.discover(category);
    }
    async loadAgent(agentName) {
        return this.agentManager.load(agentName);
    }
    async launchAgent(args) {
        return this.agentManager.launch(args);
    }
    async launchAgents(configs) {
        return this.agentManager.launchParallel(configs);
    }
    async getAgentResult(sessionId) {
        return this.agentManager.getResult(sessionId);
    }
    cancelAgent(sessionId) {
        return this.agentManager.cancel(sessionId);
    }
    getActiveSessions() {
        return this.agentManager.getActiveSessions();
    }
    getHistory(limit = 10) {
        return this.agentManager.getHistory(limit);
    }
    async runParallelReview(filePaths, techStack = []) {
        const results = await this.agentManager.runParallelReview(filePaths, techStack);
        if (this.options.saveResults) {
            await this.saveOrchestratorResult('review', { results, filePaths, techStack });
        }
        return results;
    }
    // ============================================
    // Parallel Research
    // ============================================
    async runParallelResearch(args) {
        const result = await parallelResearch({
            ...args,
            projectPath: args.projectPath || this.options.projectPath
        });
        if (this.options.saveResults && 'results' in result) {
            await this.saveOrchestratorResult('research', result);
        }
        if ('results' in result) {
            return result;
        }
        return {
            results: [],
            totalDuration: 0,
            successCount: 0,
            failureCount: 0
        };
    }
    async researchFeature(feature, techStack = []) {
        const tasks = createResearchTasks(feature, techStack);
        const result = await parallelResearchWithMultiLlm({
            tasks,
            projectPath: this.options.projectPath,
            feature,
            techStack
        });
        if (this.options.saveResults && 'results' in result) {
            await this.saveOrchestratorResult('research', result);
        }
        if ('results' in result) {
            return result;
        }
        return {
            results: [],
            totalDuration: 0,
            successCount: 0,
            failureCount: 0
        };
    }
    // ============================================
    // LLM Integration (LLMCluster 위임)
    // ============================================
    /** @deprecated GPT Codex API는 웹 검색을 지원하지 않습니다. antigravityWebSearch를 사용하세요. */
    async gptWebSearch(query) {
        return this.llmCluster.gptWebSearch(query);
    }
    async gptOrchestrate(prompt, systemPrompt, options) {
        return this.llmCluster.gptOrchestrate(prompt, systemPrompt, options);
    }
    async antigravityWebSearch(query) {
        return this.llmCluster.antigravityWebSearch(query);
    }
    async antigravityOrchestrate(prompt, systemPrompt, options) {
        return this.llmCluster.antigravityOrchestrate(prompt, systemPrompt, options);
    }
    async multiLlmQuery(prompt, options) {
        return this.llmCluster.multiQuery(prompt, options);
    }
    async checkLlmStatus() {
        return this.llmCluster.checkStatus();
    }
    // ============================================
    // Memory Management
    // ============================================
    saveToMemory(key, value, category = 'orchestrator') {
        this.memoryManager.save(key, value, category);
    }
    getFromMemory(key) {
        const memory = this.memoryManager.recall(key);
        return memory?.value || null;
    }
    // ============================================
    // Internal Utilities
    // ============================================
    async saveOrchestratorResult(type, data) {
        const resultsDir = path.join(this.options.projectPath, this.options.resultsPath);
        try {
            await fs.mkdir(resultsDir, { recursive: true });
            const filename = `${type}-${Date.now()}.json`;
            const filepath = path.join(resultsDir, filename);
            await fs.writeFile(filepath, JSON.stringify(data, null, 2));
            if (this.options.verbose) {
                debugLog(`Saved orchestrator result: ${filepath}`);
            }
        }
        catch (error) {
            errorLog('Failed to save orchestrator result:', error);
        }
    }
    // ============================================
    // Component Accessors (고급 사용)
    // ============================================
    getRouter() {
        return this.router;
    }
    getLLMCluster() {
        return this.llmCluster;
    }
    getAgentManager() {
        return this.agentManager;
    }
}
// 싱글톤 인스턴스 (선택적 사용)
let defaultOrchestrator = null;
export function getOrchestrator(options) {
    if (!defaultOrchestrator || options) {
        defaultOrchestrator = new CoreOrchestrator(options);
    }
    return defaultOrchestrator;
}
//# sourceMappingURL=orchestrator.js.map