import { Flags } from '@oclif/core';
import { PMOCommand, pmoBaseFlags } from '../../lib/pmo/index.js';
import { styles } from '../../lib/styles.js';
import { shouldOutputJson } from '../../lib/prompt-json.js';
// Progress bar helper
function progressBar(percent, width = 20) {
    const filled = Math.round((percent / 100) * width);
    const empty = width - filled;
    return '█'.repeat(filled) + '░'.repeat(empty);
}
export default class EpicList extends PMOCommand {
    static description = 'List all epics';
    static examples = [
        '<%= config.bin %> <%= command.id %>',
        '<%= config.bin %> <%= command.id %> --status active',
    ];
    static flags = {
        ...pmoBaseFlags,
        status: Flags.string({
            char: 's',
            description: 'Filter by status',
            options: ['active', 'draft', 'complete', 'dropped', 'future'],
        }),
    };
    async execute() {
        const { flags } = await this.parse(EpicList);
        const jsonMode = shouldOutputJson(flags);
        const projectId = await this.requireProject();
        const epics = await this.storage.listEpics(projectId, flags.status ? { status: flags.status } : undefined);
        if (epics.length === 0) {
            if (jsonMode) {
                this.log(JSON.stringify([], null, 2));
                return;
            }
            this.log(styles.muted('\nNo epics found.'));
            this.log(styles.muted('Create one with: prlt epic create'));
            return;
        }
        // Get ticket counts for each epic in parallel
        const ticketCounts = await Promise.all(epics.map(async (epic) => {
            const tickets = await this.storage.getTicketsForEpic(projectId, epic.id);
            const done = tickets.filter((t) => t.status === 'done').length;
            return { epicId: epic.id, done, total: tickets.length };
        }));
        const epicProgress = new Map(ticketCounts.map(({ epicId, done, total }) => [epicId, { done, total }]));
        if (jsonMode) {
            const epicsWithProgress = epics.map(epic => {
                const progress = epicProgress.get(epic.id) || { done: 0, total: 0 };
                const percent = progress.total > 0 ? Math.round((progress.done / progress.total) * 100) : 0;
                return { ...epic, progress: { ...progress, percent } };
            });
            this.log(JSON.stringify(epicsWithProgress, null, 2));
            return;
        }
        // Group epics by status
        const grouped = this.groupByStatus(epics);
        const projectName = await this.getProjectName(projectId);
        this.log(`\n🎯 ${styles.emphasis('Epics')} - ${projectName}`);
        this.log('═'.repeat(55));
        const statusOrder = ['active', 'draft', 'complete', 'dropped', 'future'];
        const statusEmoji = {
            active: '🟢',
            draft: '🟡',
            complete: '✅',
            dropped: '❌',
            future: '🔮',
        };
        for (const status of statusOrder) {
            const statusEpics = grouped.get(status);
            if (!statusEpics || statusEpics.length === 0)
                continue;
            this.log(`\n${statusEmoji[status]} ${status.toUpperCase()} (${statusEpics.length})`);
            for (const epic of statusEpics) {
                const progress = epicProgress.get(epic.id) || { done: 0, total: 0 };
                const percent = progress.total > 0 ? Math.round((progress.done / progress.total) * 100) : 0;
                const bar = progressBar(percent);
                const readyToArchive = percent === 100 && status === 'active' ? ' ← ready to archive!' : '';
                // Show rank (position + 1) for active epics
                const rank = status === 'active' ? `#${epic.position + 1} ` : '   ';
                this.log(`  ${rank}${epic.id.padEnd(10)} ${epic.title.substring(0, 27).padEnd(27)} ${bar} ${String(percent).padStart(3)}% (${progress.done}/${progress.total})${readyToArchive}`);
            }
        }
        this.log('\n' + '═'.repeat(55));
        const counts = statusOrder
            .map(s => `${grouped.get(s)?.length || 0} ${s}`)
            .filter(s => !s.startsWith('0'))
            .join(', ');
        this.log(`Total: ${epics.length} epics (${counts})`);
        this.log(styles.muted('\nCommands:'));
        this.log(styles.muted('  prlt epic progress <id>    View detailed progress'));
        this.log(styles.muted('  prlt epic archive <id>     Archive completed epic'));
    }
    groupByStatus(epics) {
        const grouped = new Map();
        for (const epic of epics) {
            const list = grouped.get(epic.status) || [];
            list.push(epic);
            grouped.set(epic.status, list);
        }
        return grouped;
    }
}
//# sourceMappingURL=list.js.map