"use strict";
/**
 * Middleware pipeline orchestrator.
 *
 * Implements the same { onMessage, finalize } interface that runAgent() expects,
 * while internally dispatching to an ordered list of middleware plugins.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.MiddlewarePipeline = void 0;
const phase_detector_1 = require("./phase-detector");
class MiddlewarePipeline {
    middlewares;
    store = new Map();
    phaseDetector;
    autoDetectPhases;
    _currentPhase = 'setup';
    _currentPhaseFreshContext = true;
    constructor(middlewares, opts) {
        this.middlewares = middlewares;
        this.phaseDetector = opts?.phaseDetector ?? new phase_detector_1.PhaseDetector();
        this.autoDetectPhases = opts?.autoDetectPhases ?? true;
        const ctx = this.createContext();
        for (const mw of this.middlewares) {
            mw.onInit?.(ctx);
        }
    }
    /** Feed an SDK message through all middleware (satisfies tracker.onMessage) */
    onMessage(message) {
        // Phase detection first — updates context before middleware sees it
        if (this.autoDetectPhases) {
            const newPhase = this.phaseDetector.detect(message);
            if (newPhase && newPhase !== this._currentPhase) {
                this.transitionPhase(newPhase, false);
            }
        }
        const ctx = this.createContext();
        const storeHandle = this.createStore();
        for (const mw of this.middlewares) {
            mw.onMessage?.(message, ctx, storeHandle);
        }
    }
    /** Finalize the run (satisfies tracker.finalize) */
    finalize(resultMessage, totalDurationMs) {
        const ctx = this.createContext();
        const storeHandle = this.createStore();
        let result;
        for (const mw of this.middlewares) {
            const r = mw.onFinalize?.(resultMessage, totalDurationMs, ctx, storeHandle);
            if (r !== undefined)
                result = r;
        }
        return result;
    }
    /** Explicit phase start (for phased runner support) */
    startPhase(name, freshContext) {
        this.transitionPhase(name, freshContext);
    }
    transitionPhase(newPhase, freshContext) {
        const oldPhase = this._currentPhase;
        this._currentPhase = newPhase;
        this._currentPhaseFreshContext = freshContext;
        const ctx = this.createContext();
        const storeHandle = this.createStore();
        for (const mw of this.middlewares) {
            mw.onPhaseTransition?.(oldPhase, newPhase, ctx, storeHandle);
        }
    }
    createContext() {
        return {
            currentPhase: this._currentPhase,
            currentPhaseFreshContext: this._currentPhaseFreshContext,
            get: (key) => this.store.get(key),
        };
    }
    createStore() {
        return {
            set: (key, value) => this.store.set(key, value),
        };
    }
}
exports.MiddlewarePipeline = MiddlewarePipeline;
