// tools/execute-sdd-flow.ts — SPEC-583: SDD Flow Orchestrator MCP tool entry point
import { randomUUID } from 'node:crypto';
import { compactResult, compactError } from './output-formatter.js';
import { saveCheckpoint, loadCheckpoint, createInitialState, } from '../engine/sdd-flow/checkpoints.js';
import { runPipeline } from '../engine/sdd-flow/pipeline.js';
import { assignModelToSubtask, formatSubtaskCost, } from '../engine/model-router/subtask-model-assigner.js';
function resolveProjectPath(projectPath) {
    return projectPath ?? process.cwd();
}
function formatResult(result) {
    const lines = [];
    lines.push(`## SDD Flow — ${result.status.toUpperCase()}`);
    lines.push(`**Run ID**: ${result.runId}`);
    if (result.currentStage) {
        lines.push(`**Stage**: ${result.currentStage}`);
    }
    if (result.wavePlan) {
        const wp = result.wavePlan;
        lines.push(`**Waves**: ${wp.waves.length} | **Teammates**: ${wp.totalTeammates} | **Est. cost**: $${wp.estimatedCost.toFixed(2)}`);
        for (const wave of wp.waves) {
            const subtaskLines = wave.specIds.map((specId) => {
                const model = assignModelToSubtask({ title: specId });
                const cost = formatSubtaskCost(model);
                return `${specId} [${model}, ${cost}]`;
            });
            lines.push(`  - Wave ${wave.index + 1}: [${subtaskLines.join(', ')}]`);
        }
    }
    if (result.merged && result.merged.length > 0) {
        lines.push(`**Merged to develop**: ${result.merged.join(', ')}`);
    }
    if (result.released) {
        lines.push('**Release**: changelog generated + version bumped');
    }
    if (result.summary) {
        lines.push(result.summary);
    }
    if (result.interactiveQuestions && result.interactiveQuestions.length > 0) {
        lines.push('');
        lines.push('**Awaiting user decision** — see interactiveQuestions below.');
    }
    return lines.join('\n');
}
export async function handleExecuteSddFlow(args) {
    const projectPath = resolveProjectPath(args.projectPath);
    const controlMode = args.controlMode ?? 'interactive';
    const specIds = args.specIds ?? [];
    if (specIds.length === 0 && !args.resumeFrom) {
        return compactError('specIds is required when not resuming. Provide at least one approved spec ID.');
    }
    let state = args.resumeFrom ? await loadCheckpoint(projectPath, args.resumeFrom) : null;
    if (args.resumeFrom && !state) {
        return compactError(`Run state not found for runId: ${args.resumeFrom}. Check planu/state/ directory.`);
    }
    if (!state) {
        const runId = randomUUID();
        state = createInitialState(runId, projectPath, controlMode, specIds);
        await saveCheckpoint(projectPath, state);
    }
    const perTeammateOverrides = args.modelStrategy
        ? undefined
        : undefined;
    const pipelineOutput = runPipeline({
        state,
        perTeammateOverrides,
        maxTeammates: args.maxTeammates ?? 4,
    });
    await saveCheckpoint(projectPath, pipelineOutput.state);
    const result = {
        runId: pipelineOutput.state.runId,
        status: pipelineOutput.status,
        wavePlan: pipelineOutput.wavePlan,
        merged: pipelineOutput.merged,
        released: pipelineOutput.released,
        interactiveQuestions: pipelineOutput.interactiveQuestions,
    };
    const text = formatResult(result);
    if (pipelineOutput.interactiveQuestions && pipelineOutput.interactiveQuestions.length > 0) {
        return {
            content: [{ type: 'text', text }],
            interactiveQuestions: pipelineOutput.interactiveQuestions,
        };
    }
    return compactResult(text);
}
//# sourceMappingURL=execute-sdd-flow.js.map