"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.DesignPipelineStateManager = void 0;
const fs = __importStar(require("fs-extra"));
const path = __importStar(require("path"));
const chalk_1 = __importDefault(require("chalk"));
class DesignPipelineStateManager {
    constructor(projectPath = process.cwd()) {
        this.statePath = path.join(projectPath, ".mycontext", "design-pipeline-state.json");
    }
    /**
     * Save the current pipeline state
     */
    async saveState(state) {
        try {
            // Ensure .mycontext directory exists
            await fs.ensureDir(path.dirname(this.statePath));
            // Save state with timestamp
            const stateWithTimestamp = {
                ...state,
                timestamp: new Date().toISOString(),
            };
            await fs.writeJson(this.statePath, stateWithTimestamp, { spaces: 2 });
            console.log(chalk_1.default.gray(`   💾 Pipeline state saved (Phase ${state.currentPhase})`));
        }
        catch (error) {
            console.warn(chalk_1.default.yellow("⚠️  Failed to save pipeline state:"), error);
        }
    }
    /**
     * Load existing pipeline state
     */
    async loadState() {
        try {
            if (!(await fs.pathExists(this.statePath))) {
                return null;
            }
            const stateData = await fs.readJson(this.statePath);
            // Convert timestamp back to Date object
            return {
                ...stateData,
                timestamp: new Date(stateData.timestamp),
            };
        }
        catch (error) {
            console.warn(chalk_1.default.yellow("⚠️  Failed to load pipeline state:"), error);
            return null;
        }
    }
    /**
     * Clear the state file (called on successful completion)
     */
    async clearState() {
        try {
            if (await fs.pathExists(this.statePath)) {
                await fs.remove(this.statePath);
                console.log(chalk_1.default.gray("   🧹 Pipeline state cleared"));
            }
        }
        catch (error) {
            console.warn(chalk_1.default.yellow("⚠️  Failed to clear pipeline state:"), error);
        }
    }
    /**
     * Check if there's a resumable state
     */
    async canResume() {
        const state = await this.loadState();
        return state !== null && state.failedPhase !== undefined;
    }
    /**
     * Get the next phase to execute
     */
    async getNextPhase() {
        const state = await this.loadState();
        if (!state)
            return 1;
        return state.failedPhase ? state.failedPhase : state.currentPhase;
    }
    /**
     * Get completed phases
     */
    async getCompletedPhases() {
        const state = await this.loadState();
        return state?.completedPhases || [];
    }
    /**
     * Get failure information
     */
    async getFailureInfo() {
        const state = await this.loadState();
        if (!state || !state.failedPhase)
            return null;
        return {
            phase: state.failedPhase,
            reason: state.failureReason || "Unknown error",
        };
    }
    /**
     * Get partial results from completed phases
     */
    async getPartialResults() {
        const state = await this.loadState();
        return state?.partialResults || {};
    }
    /**
     * Check if state is stale (older than 24 hours)
     */
    async isStateStale() {
        const state = await this.loadState();
        if (!state)
            return false;
        const now = new Date();
        const stateTime = new Date(state.timestamp);
        const hoursDiff = (now.getTime() - stateTime.getTime()) / (1000 * 60 * 60);
        return hoursDiff > 24;
    }
    /**
     * Get state summary for display
     */
    async getStateSummary() {
        const state = await this.loadState();
        if (!state)
            return "No pipeline state found";
        const completed = state.completedPhases.length;
        const total = 8;
        const progress = Math.round((completed / total) * 100);
        let summary = `Pipeline Progress: ${completed}/${total} phases (${progress}%)`;
        if (state.failedPhase) {
            summary += `\nLast failed: Phase ${state.failedPhase} (${state.failureReason})`;
        }
        const age = Math.round((Date.now() - new Date(state.timestamp).getTime()) / (1000 * 60));
        summary += `\nState age: ${age} minutes ago`;
        return summary;
    }
}
exports.DesignPipelineStateManager = DesignPipelineStateManager;
//# sourceMappingURL=designPipelineStateManager.js.map