/**
 * Workflow Orchestrator - Core orchestration logic for sw:next
 *
 * Coordinates workflow execution by detecting current phase and
 * invoking appropriate commands.
 *
 * Part of increment 0039: Ultra-Smart Next Command
 *
 * @module core/workflow/workflow-orchestrator
 * @since v0.22.0
 */
import { PhaseDetector } from './phase-detector.js';
import { WorkflowPhase } from './types.js';
import { ActiveIncrementManager } from '../increment/active-increment-manager.js';
/**
 * Workflow Orchestrator - Coordinates intelligent workflow execution
 *
 * This is a simplified initial implementation focusing on core phase detection.
 * Full autonomous execution will be added in future tasks.
 */
export class WorkflowOrchestrator {
    constructor() {
        this.phaseDetector = new PhaseDetector();
        this.activeIncrementManager = new ActiveIncrementManager();
    }
    /**
     * Execute next step in workflow (interactive mode)
     *
     * Detects current phase and suggests/executes appropriate action.
     *
     * @param incrementId - Optional increment ID (auto-detects if not provided)
     * @param options - Execution options
     * @returns Workflow execution result
     */
    async executeNext(incrementId, options = {}) {
        try {
            // Phase 1: Detect current workflow phase
            const detection = await this.detectCurrentPhase(incrementId);
            // Phase 2: Determine action based on phase and confidence
            const action = this.determineAction(detection, options);
            // Format reasoning from detection evidence
            const reasoning = this.formatReasoning(detection);
            // Phase 3: Execute action (or return suggestion)
            if (options.dryRun) {
                return {
                    success: true,
                    phase: detection.phase,
                    confidence: detection.confidence,
                    action: action.description,
                    reasoning: `[DRY RUN] Would execute: ${action.description}\n\n${reasoning}`
                };
            }
            // For now, return suggestion (actual execution will be added in later tasks)
            return {
                success: true,
                phase: detection.phase,
                confidence: detection.confidence,
                action: action.description,
                command: action.command,
                reasoning
            };
        }
        catch (error) {
            return {
                success: false,
                phase: WorkflowPhase.UNKNOWN,
                confidence: 0,
                error: error instanceof Error ? error.message : String(error),
                reasoning: 'Failed to detect workflow phase or execute action'
            };
        }
    }
    /**
     * Format reasoning from phase detection result
     */
    formatReasoning(detection) {
        const parts = [];
        // Add suggestion reason if present
        if (detection.suggestionReason) {
            parts.push(detection.suggestionReason);
        }
        // Add evidence summary
        if (detection.evidence && detection.evidence.length > 0) {
            parts.push('\nEvidence:');
            detection.evidence.forEach(ev => {
                parts.push(`- ${ev.description} (${(ev.weight * 100).toFixed(0)}% weight)`);
            });
        }
        return parts.join('\n');
    }
    /**
     * Detect current workflow phase for increment
     *
     * @param incrementId - Increment ID (auto-detects if not provided)
     * @returns Phase detection result
     */
    async detectCurrentPhase(incrementId) {
        // If no increment ID provided, try to auto-detect active increment
        if (!incrementId) {
            incrementId = await this.detectActiveIncrement();
        }
        // Build detection context
        const context = {
            userPrompt: 'Detect current workflow phase',
            incrementId,
            workingDirectory: process.cwd()
        };
        // Detect phase using PhaseDetector
        return this.phaseDetector.detect(context);
    }
    /**
     * Auto-detect active increment
     *
     * @returns Increment ID or throws if none found
     */
    async detectActiveIncrement() {
        const activeIds = this.activeIncrementManager.getActive();
        if (activeIds.length === 0) {
            throw new Error('No active increments found. Use sw:increment to create one.');
        }
        if (activeIds.length === 1) {
            return activeIds[0];
        }
        // Multiple active increments - return primary (first)
        console.log(`Multiple active increments detected: ${activeIds.join(', ')}`);
        console.log(`Using primary increment: ${activeIds[0]}`);
        return activeIds[0];
    }
    /**
     * Determine action based on phase and confidence
     */
    determineAction(detection, options) {
        const { phase, confidence } = detection;
        if (confidence < 0.7 && !options.force) {
            return {
                description: `Phase detection confidence is low (${(confidence * 100).toFixed(0)}%). Please specify action manually.`,
                command: undefined
            };
        }
        const PHASE_ACTIONS = {
            [WorkflowPhase.PLAN_GENERATION]: { description: 'Generate implementation plan', command: 'sw:plan' },
            [WorkflowPhase.IMPLEMENTATION]: { description: 'Execute tasks', command: 'sw:do' },
            [WorkflowPhase.TESTING]: { description: 'Run tests', command: 'npm test' },
            [WorkflowPhase.REVIEW]: { description: 'Run quality assessment', command: 'sw:qa' },
            [WorkflowPhase.COMPLETION]: { description: 'Close increment', command: 'sw:done' },
            [WorkflowPhase.SPEC_WRITING]: { description: 'Complete spec.md and generate plan', command: 'sw:plan' },
            [WorkflowPhase.TASK_BREAKDOWN]: { description: 'Create tasks and start implementation', command: 'sw:do' },
            [WorkflowPhase.DOCUMENTATION]: { description: 'Update living documentation', command: 'sw:sync-docs update' },
            [WorkflowPhase.UNKNOWN]: { description: 'Phase detection unclear - please specify action manually', command: '' }
        };
        const action = PHASE_ACTIONS[phase];
        return action.command ? action : { description: action.description, command: undefined };
    }
}
//# sourceMappingURL=workflow-orchestrator.js.map