import * as path from 'path';
import * as fs from 'fs';
import ora from 'ora';
import { success, info } from '../utils/logger.js';
import { outputSuccess, outputError, isPrettyMode } from '../utils/output.js';
import { addEnhancedHelp } from '../utils/helpText.js';
import { GenerationApiClient, GenerationApiError, validateASRParams, fileToBase64, } from '../services/generation-api.js';
export function registerAsrCommand(program) {
    const cmd = program
        .command('asr')
        .description('语音识别 (Speech-to-Text) - 使用 Groq Whisper')
        .argument('<file>', '音频文件路径 (支持 mp3, wav, m4a, ogg, webm)')
        .option('--language <lang>', '语言提示: zh | en | ja | ko 等')
        .option('--model <name>', 'Whisper 模型', 'whisper-large-v3-turbo')
        .action(async (file, options) => {
        const pretty = isPrettyMode(options);
        try {
            // 检查文件是否存在
            const filePath = path.resolve(file);
            if (!fs.existsSync(filePath)) {
                outputError('FILE_NOT_FOUND', `音频文件不存在: ${filePath}`, options);
                return;
            }
            // CLI 层快速校验
            const stat = fs.statSync(filePath);
            validateASRParams({ fileSize: stat.size });
            // 音频文件转 base64
            const fileBase64 = await fileToBase64(filePath);
            const params = {
                file: fileBase64,
                filename: path.basename(filePath),
                language: options.language,
                model: options.model,
            };
            const client = new GenerationApiClient();
            const startTime = Date.now();
            if (pretty) {
                const spinner = ora('正在识别语音...').start();
                try {
                    const result = await client.submitAndPoll('asr', params, {
                        onProgress: (status) => {
                            spinner.text = `语音识别中 (${status})...`;
                        },
                    });
                    const durationMs = Date.now() - startTime;
                    if (result.status === 'completed') {
                        spinner.succeed('语音识别完成！');
                        if (result.result_meta?.text) {
                            success(`识别结果: ${result.result_meta.text}`);
                        }
                        else {
                            info(`任务完成但未返回文本，使用 'gen task get ${result.task_id}' 查看详情`);
                        }
                        info(`耗时: ${(durationMs / 1000).toFixed(1)}s`);
                    }
                    else {
                        spinner.info(`任务状态: ${result.status}`);
                        if (result.error_message)
                            info(`错误: ${result.error_message}`);
                        info(`使用 'gen task get ${result.task_id}' 查看最新状态`);
                    }
                }
                catch (err) {
                    spinner.fail(`识别失败: ${err?.message || err}`);
                    throw err;
                }
            }
            else {
                const result = await client.submitAndPoll('asr', params);
                const durationMs = Date.now() - startTime;
                if (result.status === 'completed') {
                    outputSuccess({
                        task_id: result.task_id,
                        text: result.result_meta?.text || '',
                        file: filePath,
                        language: options.language || 'auto',
                        model: options.model,
                        durationMs,
                    });
                }
                else {
                    // task status != completed → 失败。outputError 让顶层 success:false 并 exit 1，
                    // 否则 Agent 把 failure 当 success（参见 image.ts 同样修复）。
                    const errCode = result.error_code ?? 'GENERATION_FAILED';
                    const errMsg = result.error_message ?? `任务状态: ${result.status}`;
                    outputError(errCode, errMsg, options, {
                        task_id: result.task_id,
                        status: result.status,
                        retryable: result.retryable ?? false,
                        error_class: result.error_class ?? null,
                    });
                }
            }
        }
        catch (err) {
            if (err instanceof GenerationApiError) {
                outputError(err.code, err.message, options);
            }
            else {
                outputError('ASR_FAILED', `语音识别失败: ${err}`, options);
            }
        }
    });
    addEnhancedHelp(cmd, {
        examples: [
            '# 基本用法 - 自动检测语言',
            '$ gen asr recording.mp3',
            '',
            '# 指定语言提示（提高准确率）',
            '$ gen asr recording.wav --language zh',
            '',
            '# 识别英文音频',
            '$ gen asr speech.m4a --language en',
        ],
        outputJson: `{
  "success": true,
  "data": {
    "task_id": "abc-123",
    "text": "识别出的文字内容",
    "file": "/path/to/audio.mp3",
    "language": "zh",
    "model": "whisper-large-v3-turbo",
    "durationMs": 850
  }
}`,
        relatedCommands: [
            { command: 'tts <text>', description: '文本转语音' },
            { command: 'task get <id>', description: '查看任务状态' },
        ],
        notes: [
            '通过 optima-generation 调用 Groq Whisper 模型',
            '需要 Optima 账号（~/.optima/token.json 或 OPTIMA_TOKEN）',
            '支持 mp3, wav, m4a, ogg, webm 等常见音频格式',
            '文件大小限制 25MB',
        ],
    });
}
//# sourceMappingURL=asr.js.map