import { success, info } from '../utils/logger.js';
import { outputSuccess, outputError, isPrettyMode } from '../utils/output.js';
import { addEnhancedHelp } from '../utils/helpText.js';
import { GenerationApiClient, GenerationApiError, } from '../services/generation-api.js';
export function registerTaskCommand(program) {
    const task = program
        .command('task')
        .description('任务管理 - 查看、取消、重试生成任务');
    // gen task get <id>
    const getCmd = task
        .command('get')
        .description('查看任务状态')
        .argument('<task_id>', '任务 ID')
        .action(async (taskId, options) => {
        const pretty = isPrettyMode(options);
        try {
            const client = new GenerationApiClient();
            const result = await client.getTask(taskId);
            if (pretty) {
                success(`任务 ${result.task_id}`);
                info(`类型: ${result.type || '-'}`);
                info(`状态: ${result.status}`);
                if (result.result_url)
                    info(`结果: ${result.result_url}`);
                if (result.error_message)
                    info(`错误: ${result.error_message}`);
                if (result.created_at)
                    info(`创建: ${result.created_at}`);
                if (result.completed_at)
                    info(`完成: ${result.completed_at}`);
            }
            else {
                outputSuccess(result);
            }
        }
        catch (err) {
            handleError(err, 'TASK_GET_FAILED', options);
        }
    });
    // gen task list
    const listCmd = task
        .command('list')
        .description('列出我的任务')
        .option('--status <status>', '按状态筛选: pending | completed | failed | cancelled')
        .option('--type <type>', '按类型筛选: image | video | tts | asr | tryon')
        .option('--limit <n>', '返回数量', '20')
        .action(async (options) => {
        const pretty = isPrettyMode(options);
        try {
            const client = new GenerationApiClient();
            const result = await client.listTasks({
                status: options.status,
                type: options.type,
                limit: parseInt(options.limit),
            });
            if (pretty) {
                success(`共 ${result.total} 个任务`);
                for (const task of result.tasks) {
                    const statusIcon = task.status === 'completed' ? '✓' :
                        task.status === 'failed' ? '✗' :
                            task.status === 'pending' ? '○' :
                                task.status === 'processing' ? '◐' : '•';
                    info(`  ${statusIcon} ${task.task_id}  ${task.type || '-'}  ${task.status}  ${task.created_at || ''}`);
                }
            }
            else {
                outputSuccess(result);
            }
        }
        catch (err) {
            handleError(err, 'TASK_LIST_FAILED', options);
        }
    });
    // gen task cancel <id>
    const cancelCmd = task
        .command('cancel')
        .description('取消任务')
        .argument('<task_id>', '任务 ID')
        .action(async (taskId, options) => {
        const pretty = isPrettyMode(options);
        try {
            const client = new GenerationApiClient();
            const result = await client.cancelTask(taskId);
            if (pretty) {
                if (result.status === 'cancelled') {
                    success(`任务 ${taskId} 已取消`);
                }
                else {
                    info(`取消结果: ${result.status}`);
                    if (result.error_message)
                        info(result.error_message);
                }
            }
            else {
                outputSuccess(result);
            }
        }
        catch (err) {
            handleError(err, 'TASK_CANCEL_FAILED', options);
        }
    });
    // gen task retry <id>
    const retryCmd = task
        .command('retry')
        .description('重试失败的任务（用原始参数重新提交）')
        .argument('<task_id>', '任务 ID')
        .action(async (taskId, options) => {
        const pretty = isPrettyMode(options);
        try {
            const client = new GenerationApiClient();
            const result = await client.retryTask(taskId);
            if (pretty) {
                success(`已重新提交，新任务 ID: ${result.task_id}`);
                info(`状态: ${result.status}`);
            }
            else {
                outputSuccess(result);
            }
        }
        catch (err) {
            handleError(err, 'TASK_RETRY_FAILED', options);
        }
    });
    // Enhanced help
    addEnhancedHelp(task, {
        examples: [
            '# 查看任务状态',
            '$ gen task get abc-123',
            '',
            '# 列出所有任务',
            '$ gen task list',
            '',
            '# 列出失败的图片任务',
            '$ gen task list --status failed --type image',
            '',
            '# 取消正在进行的任务',
            '$ gen task cancel abc-123',
            '',
            '# 重试失败的任务',
            '$ gen task retry abc-123',
        ],
        outputJson: `{
  "success": true,
  "data": {
    "task_id": "abc-123",
    "type": "image",
    "status": "completed",
    "result_url": "https://...",
    "created_at": "2026-03-21T10:00:00Z",
    "completed_at": "2026-03-21T10:00:15Z"
  }
}`,
        relatedCommands: [
            { command: 'image <prompt>', description: '生成图像' },
            { command: 'video <image>', description: '生成视频' },
            { command: 'tts <text>', description: '文本转语音' },
            { command: 'asr <file>', description: '语音识别' },
            { command: 'tryon <model> <garment>', description: '虚拟试穿' },
        ],
        notes: [
            '所有生成命令会自动轮询等待结果',
            '如果轮询超时，可以用 gen task get <id> 手动查看',
            '取消正在执行的任务时，如果官方 API 不支持取消，任务会继续执行，结果仍可查看',
        ],
    });
}
function handleError(err, code, options) {
    if (err instanceof GenerationApiError) {
        outputError(err.code, err.message, options);
    }
    else {
        const message = err instanceof Error ? err.message : String(err);
        outputError(code, message, options);
    }
}
//# sourceMappingURL=task.js.map