import chalk from 'chalk';
import ora from 'ora';
import { TaskService } from '../tasks/service.js';
import { TaskCoordinator } from '../tasks/coordination.js';
import { CoordinationService } from '../coordination/service.js';
import { compactSessionSummary } from './dashboard.js';
import { STATUS_ICONS, TYPE_ICONS, PRIORITY_LABELS } from '../tasks/types.js';
import { progressBar, stackedBar, stackedBarLegend, horizontalBarChart, sectionHeader, miniGauge, divider, inlineProgressSummary, } from './visualize.js';
export async function taskCommand(action, options = {}) {
    const service = new TaskService();
    switch (action) {
        case 'create':
            await createTask(service, options);
            break;
        case 'list':
            await listTasks(service, options);
            break;
        case 'show':
            await showTask(service, options);
            break;
        case 'update':
            await updateTask(service, options);
            break;
        case 'close':
            await closeTask(service, options);
            break;
        case 'delete':
            await deleteTask(service, options);
            break;
        case 'ready':
            await showReady(service, options);
            break;
        case 'blocked':
            await showBlocked(service, options);
            break;
        case 'dep':
            await addDependency(service, options);
            break;
        case 'undep':
            await removeDependency(service, options);
            break;
        case 'claim':
            await claimTask(service, options);
            break;
        case 'release':
            await releaseTask(service, options);
            break;
        case 'stats':
            await showStats(service, options);
            break;
        case 'board':
            await showBoard(service, options);
            break;
        case 'sync':
            await syncTasks(service, options);
            break;
        case 'compact':
            await compactTasks(service, options);
            break;
    }
}
async function createTask(service, options) {
    if (!options.title) {
        console.error(chalk.red('Error: --title is required'));
        process.exit(1);
    }
    const spinner = ora('Creating task...').start();
    try {
        const input = {
            title: options.title,
            description: options.description,
            type: options.type || 'task',
            priority: parsePriority(options.priority) ?? 2,
            labels: options.labels ? options.labels.split(',').map((l) => l.trim()) : [],
            parentId: options.parent,
            notes: options.notes,
        };
        const task = service.create(input);
        spinner.succeed(`Task created: ${task.id}`);
        console.log('');
        console.log(`  ${TYPE_ICONS[task.type]} ${chalk.bold(task.title)}`);
        console.log(`  ID: ${chalk.cyan(task.id)}`);
        console.log(`  Type: ${task.type}`);
        console.log(`  Priority: ${PRIORITY_LABELS[task.priority]}`);
        if (task.labels.length > 0) {
            console.log(`  Labels: ${task.labels.join(', ')}`);
        }
        if (task.parentId) {
            console.log(`  Parent: ${task.parentId}`);
        }
        if (options.json) {
            console.log(JSON.stringify(task, null, 2));
        }
        for (const line of inlineProgressSummary(service.getStats()))
            console.log(line);
    }
    catch (error) {
        spinner.fail('Failed to create task');
        console.error(chalk.red(error instanceof Error ? error.message : String(error)));
        process.exit(1);
    }
}
async function listTasks(service, options) {
    const filter = {};
    if (options.filterStatus) {
        filter.status = normalizeStatusList(options.filterStatus);
    }
    if (options.filterType) {
        filter.type = options.filterType.split(',');
    }
    if (options.filterPriority) {
        filter.priority = options.filterPriority
            .split(',')
            .map((p) => parsePriority(p))
            .filter((p) => p !== undefined);
    }
    if (options.filterAssignee) {
        filter.assignee = options.filterAssignee;
    }
    if (options.filterLabels) {
        filter.labels = options.filterLabels.split(',').map((l) => l.trim());
    }
    if (options.search) {
        filter.search = options.search;
    }
    if (options.showBlocked) {
        filter.isBlocked = true;
    }
    if (options.showReady) {
        filter.isReady = true;
    }
    const tasks = service.list(filter);
    if (options.json) {
        console.log(JSON.stringify(tasks, null, 2));
        return;
    }
    if (tasks.length === 0) {
        console.log(chalk.dim('No tasks found'));
        return;
    }
    console.log(chalk.bold(`\nTasks (${tasks.length})\n`));
    for (const task of tasks) {
        const statusIcon = STATUS_ICONS[task.status];
        const typeIcon = TYPE_ICONS[task.type];
        const priorityColor = getPriorityColor(task.priority);
        console.log(`  ${statusIcon} ${priorityColor(`P${task.priority}`)} ${typeIcon} ` +
            `${chalk.cyan(task.id)} ${task.title}`);
        if (options.verbose) {
            if (task.assignee) {
                console.log(chalk.dim(`    Assignee: ${task.assignee}`));
            }
            if (task.labels.length > 0) {
                console.log(chalk.dim(`    Labels: ${task.labels.join(', ')}`));
            }
        }
    }
    console.log('');
}
async function showTask(service, options) {
    if (!options.id) {
        console.error(chalk.red('Error: --id is required'));
        process.exit(1);
    }
    const task = service.getWithRelations(options.id);
    if (!task) {
        console.error(chalk.red(`Task not found: ${options.id}`));
        process.exit(1);
    }
    if (options.json) {
        console.log(JSON.stringify(task, null, 2));
        return;
    }
    const statusIcon = STATUS_ICONS[task.status];
    const typeIcon = TYPE_ICONS[task.type];
    const priorityColor = getPriorityColor(task.priority);
    console.log('');
    console.log(`${statusIcon} ${priorityColor(`P${task.priority}`)} ${typeIcon} ${chalk.bold(task.title)}`);
    console.log(chalk.dim('─'.repeat(60)));
    console.log(`ID: ${chalk.cyan(task.id)}`);
    console.log(`Status: ${task.status}${task.isBlocked ? chalk.red(' (BLOCKED)') : ''}${task.isReady ? chalk.green(' (READY)') : ''}`);
    console.log(`Type: ${task.type}`);
    console.log(`Priority: ${PRIORITY_LABELS[task.priority]}`);
    if (task.assignee) {
        console.log(`Assignee: ${task.assignee}`);
    }
    if (task.worktreeBranch) {
        console.log(`Worktree: ${task.worktreeBranch}`);
    }
    if (task.labels.length > 0) {
        console.log(`Labels: ${task.labels.join(', ')}`);
    }
    if (task.parentId) {
        console.log(`Parent: ${task.parentId}`);
    }
    if (task.description) {
        console.log('');
        console.log(chalk.bold('Description:'));
        console.log(task.description);
    }
    if (task.notes) {
        console.log('');
        console.log(chalk.bold('Notes:'));
        console.log(task.notes);
    }
    // Dependencies
    if (task.blockedBy.length > 0) {
        console.log('');
        console.log(chalk.bold('Blocked by:'));
        for (const blockerId of task.blockedBy) {
            const blocker = service.get(blockerId);
            if (blocker) {
                const blockerStatus = STATUS_ICONS[blocker.status];
                const done = blocker.status === 'done' || blocker.status === 'wont_do';
                console.log(`  ${blockerStatus} ${done ? chalk.dim(blockerId) : chalk.red(blockerId)}: ${blocker.title}`);
            }
        }
    }
    if (task.blocks.length > 0) {
        console.log('');
        console.log(chalk.bold('Blocks:'));
        for (const blocksId of task.blocks) {
            const blocked = service.get(blocksId);
            if (blocked) {
                console.log(`  ${chalk.yellow(blocksId)}: ${blocked.title}`);
            }
        }
    }
    if (task.children.length > 0) {
        console.log('');
        console.log(chalk.bold('Children:'));
        for (const childId of task.children) {
            const child = service.get(childId);
            if (child) {
                const childStatus = STATUS_ICONS[child.status];
                console.log(`  ${childStatus} ${chalk.cyan(childId)}: ${child.title}`);
            }
        }
    }
    // Timestamps
    console.log('');
    console.log(chalk.dim(`Created: ${task.createdAt}`));
    console.log(chalk.dim(`Updated: ${task.updatedAt}`));
    if (task.closedAt) {
        console.log(chalk.dim(`Closed: ${task.closedAt}`));
        if (task.closedReason) {
            console.log(chalk.dim(`Reason: ${task.closedReason}`));
        }
    }
    // History
    if (options.verbose) {
        const history = service.getHistory(task.id);
        if (history.length > 0) {
            console.log('');
            console.log(chalk.bold('History:'));
            for (const entry of history.slice(0, 10)) {
                console.log(chalk.dim(`  ${entry.changedAt || '?'}: ${entry.field || 'unknown'} changed`));
            }
        }
    }
    console.log('');
}
async function updateTask(service, options) {
    if (!options.id) {
        console.error(chalk.red('Error: --id is required'));
        process.exit(1);
    }
    const input = {};
    if (options.title)
        input.title = options.title;
    if (options.description)
        input.description = options.description;
    if (options.type)
        input.type = options.type;
    if (options.status)
        input.status = normalizeStatus(options.status);
    if (options.priority) {
        const priority = parsePriority(options.priority);
        if (priority !== undefined)
            input.priority = priority;
    }
    if (options.assignee)
        input.assignee = options.assignee === 'none' ? undefined : options.assignee;
    if (options.worktree)
        input.worktreeBranch = options.worktree === 'none' ? undefined : options.worktree;
    if (options.labels)
        input.labels = options.labels.split(',').map((l) => l.trim());
    if (options.notes)
        input.notes = options.notes;
    if (Object.keys(input).length === 0) {
        console.error(chalk.red('Error: No updates specified'));
        process.exit(1);
    }
    const spinner = ora('Updating task...').start();
    try {
        const task = service.update(options.id, input);
        if (!task) {
            spinner.fail(`Task not found: ${options.id}`);
            process.exit(1);
        }
        spinner.succeed(`Task updated: ${task.id}`);
        console.log(`  ${STATUS_ICONS[task.status]} ${task.title}`);
    }
    catch (error) {
        spinner.fail('Failed to update task');
        console.error(chalk.red(error instanceof Error ? error.message : String(error)));
        process.exit(1);
    }
}
async function closeTask(service, options) {
    if (!options.id) {
        console.error(chalk.red('Error: --id is required'));
        process.exit(1);
    }
    const spinner = ora('Closing task...').start();
    try {
        const task = service.close(options.id, options.reason);
        if (!task) {
            spinner.fail(`Task not found: ${options.id}`);
            process.exit(1);
        }
        spinner.succeed(`Task closed: ${task.id}`);
        console.log(`  ${STATUS_ICONS.done} ${task.title}`);
        if (options.reason) {
            console.log(chalk.dim(`  Reason: ${options.reason}`));
        }
        for (const line of inlineProgressSummary(service.getStats()))
            console.log(line);
        compactSessionSummary();
    }
    catch (error) {
        spinner.fail('Failed to close task');
        console.error(chalk.red(error instanceof Error ? error.message : String(error)));
        process.exit(1);
    }
}
async function deleteTask(service, options) {
    if (!options.id) {
        console.error(chalk.red('Error: --id is required'));
        process.exit(1);
    }
    const spinner = ora('Deleting task...').start();
    try {
        const success = service.delete(options.id);
        if (!success) {
            spinner.fail(`Task not found: ${options.id}`);
            process.exit(1);
        }
        spinner.succeed(`Task deleted: ${options.id}`);
    }
    catch (error) {
        spinner.fail('Failed to delete task');
        console.error(chalk.red(error instanceof Error ? error.message : String(error)));
        process.exit(1);
    }
}
async function showReady(service, options) {
    const tasks = service.ready();
    if (options.json) {
        console.log(JSON.stringify(tasks, null, 2));
        return;
    }
    // Display decision loop context for each ready task
    console.log(chalk.bold.cyan('\n=== DECISION LOOP CONTEXT ===') + '\n');
    console.log('1. CLASSIFY -> Analyzing complexity and backup needs...');
    const stats = service.getStats();
    for (const line of inlineProgressSummary(stats))
        console.log(line);
    console.log('');
    if (tasks.length === 0) {
        console.log(chalk.dim('No ready tasks'));
        // Provide guidance on creating new tasks with decision loop context
        console.log('\n' + chalk.bold.cyan('=== DECISION LOOP: CREATE NEW TASK ===') + '\n');
        console.log(`2. PROTECT -> Backup critical files before changes`);
        console.log(`3. MEMORY  -> Query relevant context from memory system`);
        console.log(`4. AGENTS  -> Check for multi-agent overlaps (if applicable)`);
        console.log(`5. SKILLS  -> Load domain-specific skills via @Skill:name.md`);
        console.log('');
        return;
    }
    console.log(chalk.bold.green(`✓ Ready Tasks (${tasks.length})\n`));
    // Enhanced output with decision loop guidance for each task
    for (const task of tasks) {
        const priorityColor = getPriorityColor(task.priority);
        const typeIcon = TYPE_ICONS[task.type];
        console.log(chalk.bold('---') + '\n');
        console.log(`  ${priorityColor(`P${task.priority}`)} ${typeIcon} ` +
            `${chalk.cyan(task.id)} ${task.title}`);
        if (task.description) {
            console.log(chalk.dim(`     Description: ${task.description.substring(0, 60)}...`));
        }
        // Show dependencies and blocking info
        if (task.blockedBy.length > 0) {
            console.log(chalk.yellow('     Blocked by:') + ` ${task.blockedBy.join(', ')}`);
        }
        else if (task.blocks.length > 0) {
            console.log(chalk.green('     Unblocks: ' + task.blocks.length + ' task(s):') +
                chalk.dim(` ${task.blocks.slice(0, 3).join(', ')}`));
        }
        // Provide decision loop guidance specific to this task type
        const hasDependencies = task.blockedBy.length > 0 || task.blocks.length > 0;
        if (hasDependencies) {
            console.log(chalk.dim('\n     Decision Loop Steps:'));
            console.log(`       • CLASSIFY -> Task complexity: ${task.priority >= 8 ? 'HIGH' : 'MEDIUM/LOW'}`);
            console.log('       • PROTECT   -> Backup files before changes');
            console.log('       • MEMORY    -> Query related task history');
            if (hasDependencies) {
                console.log(`       • AGENTS    -> Coordinate with dependents: ${task.blockedBy.length + task.blocks.length} tasks`);
            }
        }
        // Show worktree requirement reminder
        console.log(chalk.dim('\n     MANDATORY WORKTREE REQUIRED'));
        console.log('       → uap worktree create <description>');
        if (task.labels) {
            const labels = Array.isArray(task.labels) ? task.labels : [task.labels];
            console.log(`       Labels: ${labels.join(', ')}`);
        }
        console.log('\n' + chalk.dim('─'.repeat(60)));
    }
    // End with decision loop summary
    console.log(chalk.bold.cyan('\n=== DECISION LOOP SUMMARY ===') + '\n');
    console.log(`Total ready tasks: ${tasks.length}`);
    // Count high priority from stats (P0-P1 are highest)
    const p0 = stats.byPriority[0] || 0;
    const p1 = stats.byPriority[1] || 0;
    console.log(`Critical/High Priority: ${p0 + p1}`);
    console.log('Next step: Select task → Create worktree → Begin implementation');
    console.log('\n' + chalk.dim('(Remember to follow all DECISION_LOOP steps before coding!)'));
    console.log('');
}
async function showBlocked(service, options) {
    const tasks = service.blocked();
    if (options.json) {
        console.log(JSON.stringify(tasks, null, 2));
        return;
    }
    const stats = service.getStats();
    for (const line of inlineProgressSummary(stats))
        console.log(line);
    console.log('');
    if (tasks.length === 0) {
        console.log(chalk.dim('No blocked tasks'));
        return;
    }
    console.log(chalk.bold.red(`❄ Blocked Tasks (${tasks.length})\n`));
    for (const task of tasks) {
        const priorityColor = getPriorityColor(task.priority);
        const typeIcon = TYPE_ICONS[task.type];
        console.log(`  ${priorityColor(`P${task.priority}`)} ${typeIcon} ` +
            `${chalk.cyan(task.id)} ${task.title}`);
        console.log(chalk.red(`    Blocked by: ${task.blockedBy.join(', ')}`));
    }
    console.log('');
}
async function addDependency(service, options) {
    if (!options.from || !options.to) {
        console.error(chalk.red('Error: --from and --to are required'));
        process.exit(1);
    }
    const depType = (options.depType || 'blocks');
    const spinner = ora(`Adding ${depType} dependency...`).start();
    try {
        const result = service.addDependency(options.from, options.to, depType);
        if (!result.ok) {
            const messages = {
                not_found: 'One or both task IDs not found',
                self_dependency: 'A task cannot depend on itself',
                would_create_cycle: 'Adding this dependency would create a cycle',
                duplicate: 'This dependency already exists',
            };
            spinner.fail(`Failed to add dependency: ${messages[result.reason]}`);
            process.exit(1);
        }
        spinner.succeed(`Dependency added: ${options.from} ${depType} ${options.to}`);
    }
    catch (error) {
        spinner.fail('Failed to add dependency');
        console.error(chalk.red(error instanceof Error ? error.message : String(error)));
        process.exit(1);
    }
}
async function removeDependency(service, options) {
    if (!options.from || !options.to) {
        console.error(chalk.red('Error: --from and --to are required'));
        process.exit(1);
    }
    const success = service.removeDependency(options.from, options.to);
    if (success) {
        console.log(chalk.green(`Dependency removed: ${options.from} → ${options.to}`));
    }
    else {
        console.log(chalk.yellow('Dependency not found'));
    }
}
async function claimTask(service, options) {
    if (!options.id) {
        console.error(chalk.red('Error: --id is required'));
        process.exit(1);
    }
    const spinner = ora('Claiming task...').start();
    try {
        // Get or create agent ID
        const coordService = new CoordinationService();
        const agentId = coordService.register('task-claimer', ['tasks']);
        const coordinator = new TaskCoordinator({
            taskService: service,
            coordinationService: coordService,
            agentId,
            agentName: 'task-claimer',
            worktreeBranch: options.branch,
        });
        const result = await coordinator.claim(options.id, options.branch);
        if (!result) {
            spinner.fail(`Task not found: ${options.id}`);
            process.exit(1);
        }
        spinner.succeed(`Task claimed: ${options.id}`);
        console.log(`  ${STATUS_ICONS.in_progress} ${result.task.title}`);
        console.log(`  Worktree: ${result.worktreeBranch || 'none'}`);
        if (result.overlaps.length > 0) {
            console.log(chalk.yellow('\n  ⚠️  Overlapping work detected:'));
            for (const overlap of result.overlaps) {
                console.log(chalk.yellow(`    ${overlap.conflictRisk || 'unknown'}: ${overlap.suggestion || 'Review overlapping work'}`));
            }
        }
        for (const line of inlineProgressSummary(service.getStats()))
            console.log(line);
    }
    catch (error) {
        spinner.fail('Failed to claim task');
        console.error(chalk.red(error instanceof Error ? error.message : String(error)));
        process.exit(1);
    }
}
async function releaseTask(service, options) {
    if (!options.id) {
        console.error(chalk.red('Error: --id is required'));
        process.exit(1);
    }
    const spinner = ora('Releasing task...').start();
    try {
        const coordService = new CoordinationService();
        const agentId = coordService.register('task-releaser', ['tasks']);
        const coordinator = new TaskCoordinator({
            taskService: service,
            coordinationService: coordService,
            agentId,
            agentName: 'task-releaser',
        });
        const result = await coordinator.release(options.id, options.reason);
        if (!result) {
            spinner.fail(`Task not found: ${options.id}`);
            process.exit(1);
        }
        spinner.succeed(`Task released: ${options.id}`);
        console.log(`  ${STATUS_ICONS.done} ${result.task.title}`);
        for (const line of inlineProgressSummary(service.getStats()))
            console.log(line);
        compactSessionSummary();
    }
    catch (error) {
        spinner.fail('Failed to release task');
        console.error(chalk.red(error instanceof Error ? error.message : String(error)));
        process.exit(1);
    }
}
async function showBoard(service, _options) {
    const allTasks = service.list({});
    const stats = service.getStats();
    // Group tasks by status
    const columns = {
        open: allTasks.filter(t => t.status === 'open'),
        in_progress: allTasks.filter(t => t.status === 'in_progress'),
        blocked: allTasks.filter(t => t.status === 'blocked'),
        done: allTasks.filter(t => t.status === 'done').slice(0, 10),
        wont_do: allTasks.filter(t => t.status === 'wont_do').slice(0, 5),
    };
    const colHeaders = {
        open: { label: `${STATUS_ICONS.open} Open`, color: chalk.white },
        in_progress: { label: `${STATUS_ICONS.in_progress} In Progress`, color: chalk.cyan },
        blocked: { label: `${STATUS_ICONS.blocked} Blocked`, color: chalk.red },
        done: { label: `${STATUS_ICONS.done} Done`, color: chalk.green },
        wont_do: { label: `${STATUS_ICONS.wont_do} Won't Do`, color: chalk.dim },
    };
    // Determine column width based on terminal
    const termWidth = process.stdout.columns || 120;
    const colCount = 5;
    const colWidth = Math.max(20, Math.floor((termWidth - colCount - 1) / colCount));
    const maxRows = Math.max(...Object.values(columns).map(c => c.length), 0);
    console.log('');
    console.log(chalk.bold.cyan('  Task Board'));
    const completed = stats.byStatus.done + stats.byStatus.wont_do;
    console.log(`  ${progressBar(completed, stats.total, 40, { label: 'Progress', filled: chalk.green })}`);
    console.log(divider(termWidth - 2));
    // Column headers
    const headerLine = Object.entries(colHeaders).map(([key, { label, color }]) => {
        const count = columns[key].length;
        const text = `${label} (${count})`;
        return color(text.padEnd(colWidth).slice(0, colWidth));
    }).join(chalk.dim('\u2502'));
    console.log(`  ${headerLine}`);
    console.log(`  ${Array(colCount).fill('\u2500'.repeat(colWidth)).join(chalk.dim('\u253C'))}`);
    // Render rows
    for (let row = 0; row < Math.min(maxRows, 15); row++) {
        const cells = Object.keys(columns).map(status => {
            const tasks = columns[status];
            if (row >= tasks.length)
                return ' '.repeat(colWidth);
            const t = tasks[row];
            const prioColor = t.priority === 0 ? chalk.red : t.priority === 1 ? chalk.yellow : t.priority === 2 ? chalk.blue : chalk.dim;
            const typeIcon = TYPE_ICONS[t.type] || '\u25C6';
            const prio = PRIORITY_LABELS[t.priority] || 'P2';
            const titleMax = colWidth - 12;
            const title = t.title.length > titleMax ? t.title.slice(0, titleMax - 1) + '\u2026' : t.title;
            // Format: P0 icon title [id]
            const card = `${prioColor(prio)} ${typeIcon} ${title}`;
            // Pad to column width (accounting for ANSI codes)
            const visLen = `${prio} ${typeIcon} ${title}`.length;
            const pad = Math.max(0, colWidth - visLen);
            return card + ' '.repeat(pad);
        });
        console.log(`  ${cells.join(chalk.dim('\u2502'))}`);
    }
    if (maxRows > 15) {
        console.log(chalk.dim(`  ... ${maxRows - 15} more tasks not shown`));
    }
    console.log('');
}
async function showStats(service, options) {
    const stats = service.getStats();
    if (options.json) {
        console.log(JSON.stringify(stats, null, 2));
        return;
    }
    console.log('');
    console.log(chalk.bold.cyan('  Task Statistics'));
    console.log(divider(60));
    console.log('');
    // Completion progress bar
    const completed = stats.byStatus.done + stats.byStatus.wont_do;
    console.log(`  ${progressBar(completed, stats.total, 40, {
        label: 'Completion',
        filled: chalk.green,
    })}`);
    console.log('');
    // Status stacked bar
    const segments = [
        { value: stats.byStatus.done, color: chalk.green, label: `Done ${STATUS_ICONS.done}` },
        {
            value: stats.byStatus.in_progress,
            color: chalk.cyan,
            label: `In Progress ${STATUS_ICONS.in_progress}`,
        },
        { value: stats.byStatus.open, color: chalk.white, label: `Open ${STATUS_ICONS.open}` },
        { value: stats.byStatus.blocked, color: chalk.red, label: `Blocked ${STATUS_ICONS.blocked}` },
        { value: stats.byStatus.wont_do, color: chalk.dim, label: `Won't Do ${STATUS_ICONS.wont_do}` },
    ];
    console.log(`  ${stackedBar(segments, stats.total, 50)}`);
    console.log(`  ${stackedBarLegend(segments)}`);
    console.log('');
    // Gauges
    console.log(`  ${chalk.bold('Total    ')} ${chalk.bold(String(stats.total))}`);
    console.log(`  ${chalk.bold('Ready    ')} ${miniGauge(stats.ready, stats.total, 15)} ${chalk.green(String(stats.ready))}`);
    console.log(`  ${chalk.bold('Blocked  ')} ${miniGauge(stats.blocked, stats.total, 15)} ${chalk.red(String(stats.blocked))}`);
    console.log('');
    // Priority chart
    console.log(sectionHeader('By Priority'));
    console.log('');
    for (const line of horizontalBarChart([
        { label: 'P0 Critical', value: stats.byPriority[0], color: chalk.red },
        { label: 'P1 High', value: stats.byPriority[1], color: chalk.yellow },
        { label: 'P2 Medium', value: stats.byPriority[2], color: chalk.blue },
        { label: 'P3 Low', value: stats.byPriority[3], color: chalk.dim },
        { label: 'P4 Backlog', value: stats.byPriority[4], color: chalk.dim },
    ], { maxWidth: 30, maxLabelWidth: 14 })) {
        console.log(line);
    }
    console.log('');
    // Type chart
    const typeData = Object.entries(stats.byType).filter(([, count]) => count > 0);
    if (typeData.length > 0) {
        console.log(sectionHeader('By Type'));
        console.log('');
        for (const line of horizontalBarChart(typeData.map(([type, count]) => ({
            label: `${TYPE_ICONS[type]} ${type}`,
            value: count,
            color: chalk.magenta,
        })), { maxWidth: 30, maxLabelWidth: 14 })) {
            console.log(line);
        }
        console.log('');
    }
}
async function syncTasks(service, _options) {
    const spinner = ora('Syncing tasks...').start();
    try {
        // Import from JSONL first
        const imported = service.importFromJSONL();
        // Then export current state
        service.saveToJSONL();
        spinner.succeed('Tasks synced');
        if (imported > 0) {
            console.log(chalk.dim(`  Imported ${imported} task(s) from JSONL`));
        }
        console.log(chalk.dim('  Exported current state to JSONL'));
    }
    catch (error) {
        spinner.fail('Failed to sync tasks');
        console.error(chalk.red(error instanceof Error ? error.message : String(error)));
        process.exit(1);
    }
}
async function compactTasks(service, options) {
    const days = options.days ? parseInt(options.days, 10) : 90;
    const spinner = ora(`Compacting tasks older than ${days} days...`).start();
    try {
        const summary = service.compact(days);
        if (!summary) {
            spinner.info('No tasks to compact');
            return;
        }
        spinner.succeed(`Compacted ${summary.originalIds.length} task(s)`);
        console.log(chalk.dim(`  Period: ${summary.closedPeriod}`));
        console.log(chalk.dim(`  Summary: ${summary.summary}`));
    }
    catch (error) {
        spinner.fail('Failed to compact tasks');
        console.error(chalk.red(error instanceof Error ? error.message : String(error)));
        process.exit(1);
    }
}
function getPriorityColor(priority) {
    switch (priority) {
        case 0:
            return chalk.red;
        case 1:
            return chalk.yellow;
        case 2:
            return chalk.blue;
        case 3:
            return chalk.dim;
        case 4:
            return chalk.dim;
        default:
            return chalk.white;
    }
}
function parsePriority(value) {
    if (!value)
        return undefined;
    const normalized = value.trim().toLowerCase();
    const map = {
        p0: 0,
        critical: 0,
        high: 1,
        p1: 1,
        medium: 2,
        p2: 2,
        low: 3,
        p3: 3,
        backlog: 4,
        p4: 4,
    };
    if (map[normalized] !== undefined)
        return map[normalized];
    const parsed = parseInt(normalized, 10);
    if (!Number.isNaN(parsed) && parsed >= 0 && parsed <= 4) {
        return parsed;
    }
    return undefined;
}
function normalizeStatus(value) {
    const normalized = value.trim().toLowerCase();
    const map = {
        pending: 'open',
        completed: 'done',
    };
    return (map[normalized] || normalized);
}
function normalizeStatusList(value) {
    return value
        .split(',')
        .map((status) => normalizeStatus(status))
        .filter((status) => status.length > 0);
}
//# sourceMappingURL=task.js.map