"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.PipelineOrchestrator = void 0;
const chalk_1 = __importDefault(require("chalk"));
const FeatureGraphCompiler_1 = require("./FeatureGraphCompiler");
const ImplGraphCompiler_1 = require("./ImplGraphCompiler");
const OperationPipeline_1 = require("./OperationPipeline");
const OperationExecutor_1 = require("./OperationExecutor");
const ExecutionHistory_1 = require("./ExecutionHistory");
const BlockerGate_1 = require("./BlockerGate");
const QuestionGraphEngine_1 = require("./QuestionGraphEngine");
class PipelineOrchestrator {
    constructor() {
        this.featureCompiler = new FeatureGraphCompiler_1.FeatureGraphCompiler();
        this.implCompiler = new ImplGraphCompiler_1.ImplGraphCompiler();
        this.opExecutor = new OperationExecutor_1.OperationExecutor();
        this.opPipeline = new OperationPipeline_1.OperationPipeline(this.opExecutor);
        this.history = new ExecutionHistory_1.ExecutionHistory();
    }
    async executeFromPrompt(prompt) {
        const start = Date.now();
        const trace = [];
        // Stage 1-2: Question Graph — harvest from prompt
        trace.push({ stage: "questions", status: "running" });
        try {
            const qEngine = new QuestionGraphEngine_1.QuestionGraphEngine();
            await qEngine.load();
            const blockerGate = new BlockerGate_1.BlockerGate(qEngine);
            const generated = await qEngine.harvestFromPrompt(prompt);
            await qEngine.save();
            // Check blockers
            try {
                await blockerGate.requireUnblocked("pipeline execution");
                trace.push({
                    stage: "questions",
                    status: "complete",
                    detail: `${generated.length} questions harvested, no blockers`,
                });
            }
            catch (e) {
                trace.push({
                    stage: "questions",
                    status: "blocked",
                    error: e.message,
                });
                return { success: false, trace, duration: Date.now() - start };
            }
        }
        catch (e) {
            trace.push({
                stage: "questions",
                status: "failed",
                error: e.message,
            });
            return { success: false, trace, duration: Date.now() - start };
        }
        // Stage 3-5: Feature Graph — compile from brain
        trace.push({ stage: "features", status: "running" });
        let implGraph;
        let featureId;
        try {
            const graph = await this.featureCompiler.compileFromContext();
            const target = graph.getNextRecommended();
            if (!target) {
                trace.push({
                    stage: "features",
                    status: "skipped",
                    detail: "No unplanned features available for execution",
                });
                return { success: true, trace, duration: Date.now() - start };
            }
            featureId = target.id;
            trace.push({
                stage: "features",
                status: "complete",
                detail: `Selected: ${target.name}`,
            });
        }
        catch (e) {
            trace.push({ stage: "features", status: "failed", error: e.message });
            return { success: false, trace, duration: Date.now() - start };
        }
        // Stage 6-7: Implementation Graph
        trace.push({ stage: "impl", status: "running" });
        try {
            const feature = this.featureCompiler
                .compileFromContext()
                .then((g) => g.getFeatureById(featureId));
            const resolvedFeature = await feature;
            if (!resolvedFeature) {
                throw new Error(`Feature ${featureId} not found after compilation`);
            }
            implGraph = await this.implCompiler.compileFromFeature(resolvedFeature);
            trace.push({
                stage: "impl",
                status: "complete",
                detail: `${implGraph.batches.length} batches, ${implGraph.nodes.size} tasks`,
            });
        }
        catch (e) {
            trace.push({ stage: "impl", status: "failed", error: e.message });
            return { success: false, trace, duration: Date.now() - start };
        }
        // Stage 8-9: Execute implementation
        trace.push({ stage: "operations", status: "running" });
        let opsApplied = 0;
        try {
            for (const batch of implGraph.batches) {
                const result = await this.opPipeline.executeBatch(batch, featureId);
                const applied = result.results.filter((r) => r.success).length;
                opsApplied += applied;
            }
            trace.push({
                stage: "operations",
                status: "complete",
                detail: `${opsApplied} operations applied`,
            });
        }
        catch (e) {
            trace.push({ stage: "operations", status: "failed", error: e.message });
            return { success: false, trace, duration: Date.now() - start };
        }
        // Stage 10: Record history
        trace.push({ stage: "history", status: "running" });
        try {
            await this.history.record({
                type: "pipeline",
                action: `execute: ${prompt.substring(0, 80)}`,
                params: { prompt, featureId, trace },
                result: { opsApplied, batches: implGraph.batches.length },
                status: "success",
                duration: Date.now() - start,
                trace,
            });
            trace.push({ stage: "history", status: "complete" });
        }
        catch {
            trace.push({ stage: "history", status: "failed" });
        }
        return {
            success: true,
            trace,
            duration: Date.now() - start,
            featureId,
            opsApplied,
        };
    }
    async displayResult(result) {
        console.log(chalk_1.default.bold("\n🔷 Pipeline Execution"));
        console.log(chalk_1.default.dim("─".repeat(50)));
        for (const t of result.trace) {
            const icon = t.status === "complete"
                ? chalk_1.default.green("✓")
                : t.status === "running"
                    ? chalk_1.default.cyan("●")
                    : t.status === "blocked"
                        ? chalk_1.default.red("✗")
                        : t.status === "failed"
                            ? chalk_1.default.red("✗")
                            : chalk_1.default.dim("—");
            console.log(`  ${icon} ${chalk_1.default.bold(t.stage)}`);
            if (t.detail) {
                console.log(`     ${chalk_1.default.dim(t.detail)}`);
            }
            if (t.error) {
                console.log(`     ${chalk_1.default.red(t.error)}`);
            }
        }
        console.log(chalk_1.default.dim("─".repeat(50)));
        if (result.success) {
            console.log(chalk_1.default.green(`  ✓ Completed in ${result.duration}ms`));
            if (result.featureId) {
                console.log(chalk_1.default.dim(`  Feature: ${result.featureId}`));
            }
            if (result.opsApplied) {
                console.log(chalk_1.default.dim(`  Operations applied: ${result.opsApplied}`));
            }
        }
        else {
            console.log(chalk_1.default.red(`  ✗ Failed after ${result.duration}ms`));
        }
        console.log();
    }
}
exports.PipelineOrchestrator = PipelineOrchestrator;
//# sourceMappingURL=PipelineOrchestrator.js.map