"use strict";
/**
 * Enhanced Progress Display
 * Multi-stage progress indicators with better visual feedback
 */
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.EnhancedProgressDisplay = void 0;
exports.createStageProgress = createStageProgress;
const chalk_1 = __importDefault(require("chalk"));
const output = __importStar(require("./output"));
class EnhancedProgressDisplay {
    stages = [];
    startTime = Date.now();
    lastRender = '';
    constructor(stages) {
        this.stages = stages.map(name => ({
            name,
            status: 'pending',
        }));
    }
    /**
     * Update a stage's progress
     */
    updateStage(stageName, update) {
        const stage = this.stages.find(s => s.name === stageName);
        if (stage) {
            Object.assign(stage, update);
            this.render();
        }
    }
    /**
     * Mark a stage as in progress
     */
    startStage(stageName, total) {
        this.updateStage(stageName, {
            status: 'in-progress',
            current: 0,
            total,
            message: undefined,
        });
    }
    /**
     * Update progress within a stage
     */
    updateProgress(stageName, current, message) {
        this.updateStage(stageName, { current, message });
    }
    /**
     * Complete a stage
     */
    completeStage(stageName, message) {
        const stage = this.stages.find(s => s.name === stageName);
        if (stage) {
            const duration = stage.status === 'in-progress' ? Date.now() - this.startTime : undefined;
            this.updateStage(stageName, {
                status: 'completed',
                message,
                duration,
            });
        }
    }
    /**
     * Fail a stage
     */
    failStage(stageName, message) {
        this.updateStage(stageName, {
            status: 'failed',
            message,
        });
    }
    /**
     * Render the progress display
     */
    render() {
        const lines = [];
        // Calculate overall progress
        const completed = this.stages.filter(s => s.status === 'completed').length;
        const total = this.stages.length;
        const percentage = Math.round((completed / total) * 100);
        // Overall progress bar
        lines.push('');
        lines.push(chalk_1.default.bold('Progress:') + ' ' + this.renderProgressBar(completed, total) + ' ' + chalk_1.default.cyan(`${percentage}%`));
        lines.push('');
        // Render each stage
        for (const stage of this.stages) {
            lines.push(this.renderStage(stage));
        }
        // Elapsed time
        const elapsed = Math.round((Date.now() - this.startTime) / 1000);
        lines.push('');
        lines.push(chalk_1.default.gray(`Elapsed: ${this.formatDuration(elapsed)}`));
        // Clear previous render and display new one
        const rendered = lines.join('\n');
        if (rendered !== this.lastRender) {
            // Move cursor up to overwrite previous render
            if (this.lastRender) {
                const lineCount = this.lastRender.split('\n').length;
                process.stdout.write(`\x1b[${lineCount}A`);
            }
            process.stdout.write(rendered + '\n');
            this.lastRender = rendered;
        }
    }
    /**
     * Render a single stage
     */
    renderStage(stage) {
        let icon;
        let color;
        switch (stage.status) {
            case 'completed':
                icon = '✓';
                color = chalk_1.default.green;
                break;
            case 'in-progress':
                icon = '◐';
                color = chalk_1.default.cyan;
                break;
            case 'failed':
                icon = '✗';
                color = chalk_1.default.red;
                break;
            default:
                icon = '○';
                color = chalk_1.default.gray;
        }
        let line = '  ' + color(icon) + ' ' + stage.name;
        // Add progress within stage
        if (stage.status === 'in-progress' && stage.total) {
            const current = stage.current || 0;
            const stagePercentage = Math.round((current / stage.total) * 100);
            line += ' ' + chalk_1.default.gray(`(${current}/${stage.total}) ${stagePercentage}%`);
        }
        // Add duration for completed stages
        if (stage.status === 'completed' && stage.duration) {
            const duration = Math.round(stage.duration / 1000);
            line += ' ' + chalk_1.default.gray(`[${this.formatDuration(duration)}]`);
        }
        // Add message
        if (stage.message) {
            line += '\n    ' + chalk_1.default.gray(stage.message);
        }
        return line;
    }
    /**
     * Render a progress bar
     */
    renderProgressBar(current, total) {
        const width = 30;
        const filled = Math.round((current / total) * width);
        const empty = width - filled;
        return chalk_1.default.green('█'.repeat(filled)) + chalk_1.default.gray('░'.repeat(empty));
    }
    /**
     * Format duration in human-readable format
     */
    formatDuration(seconds) {
        if (seconds < 60) {
            return `${seconds}s`;
        }
        const mins = Math.floor(seconds / 60);
        const secs = seconds % 60;
        return `${mins}m ${secs}s`;
    }
    /**
     * Final summary
     */
    renderSummary() {
        output.blank();
        output.header('Summary');
        const _completed = this.stages.filter(s => s.status === 'completed').length;
        const failed = this.stages.filter(s => s.status === 'failed').length;
        const total = this.stages.length;
        if (failed > 0) {
            output.error(`${failed} stage(s) failed`);
        }
        else {
            output.success(`All ${total} stages completed successfully`);
        }
        const totalDuration = Math.round((Date.now() - this.startTime) / 1000);
        output.info(`Total time: ${this.formatDuration(totalDuration)}`);
        output.blank();
    }
}
exports.EnhancedProgressDisplay = EnhancedProgressDisplay;
/**
 * Create a simple stage-based progress tracker
 */
function createStageProgress(stages) {
    return new EnhancedProgressDisplay(stages);
}
//# sourceMappingURL=enhanced-progress.js.map