import * as path from 'path';
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 { getConfigValue } from '../services/config.js';
import { GenerationApiClient, GenerationApiError, validateTTSParams, downloadResult, } from '../services/generation-api.js';
const TTS_VOICES = [
    'Cherry', 'Serena', 'Chelsie', 'Aria', 'Bella', 'Vivian', 'Jennifer', 'Katerina',
    'Breeze', 'Maple', 'Sakura',
    'Ethan', 'Aiden', 'Brandon', 'Ryan', 'Luke', 'Leo',
];
export function registerTtsCommand(program) {
    const cmd = program
        .command('tts')
        .description('文本转语音 (Text-to-Speech) - dashscope(默认) 或 minimax(情感 TTS)')
        .argument('<text>', '要转换的文本内容')
        .option('-o, --output <path>', '输出文件路径', '')
        .option('--voice <name>', '声音名称 (默认: Cherry；provider=minimax 时填 MiniMax voice_id)', 'Cherry')
        .option('--provider <name>', "引擎: dashscope(默认) | minimax(情感 TTS)", 'dashscope')
        .option('--emotion <name>', '情感(仅 minimax): happy/sad/angry/fearful/disgusted/surprised/calm/fluent/whisper')
        .option('--speed <n>', '语速 0.5-2.0(仅 minimax)', parseFloat)
        .option('--voices', '列出可用声音')
        .option('--play', '生成后自动播放音频')
        .action(async (text, options) => {
        const pretty = isPrettyMode(options);
        // 列出可用声音
        if (options.voices) {
            if (pretty) {
                info('可用声音列表 (qwen3-tts-flash):');
                console.log(`  女声: Cherry, Serena, Chelsie, Aria, Bella, Vivian, Jennifer, Katerina, Breeze, Maple, Sakura`);
                console.log(`  男声: Ethan, Aiden, Brandon, Ryan, Luke, Leo`);
            }
            else {
                outputSuccess({ voices: TTS_VOICES });
            }
            return;
        }
        try {
            // CLI 层快速校验
            validateTTSParams({ text });
            const outputDir = getConfigValue('outputDir') || './gen-output';
            // minimax 返回 mp3，dashscope(qwen3) 返回 wav；默认输出名按 provider 选扩展名
            const defaultExt = options.provider === 'minimax' ? 'mp3' : 'wav';
            const outputPath = options.output
                ? path.resolve(options.output)
                : path.resolve(outputDir, `tts_${Date.now()}.${defaultExt}`);
            const params = {
                text,
                voice: options.voice,
            };
            // provider 覆盖 + 情感参数（仅 minimax 生效）
            if (options.provider && options.provider !== 'dashscope')
                params.provider = options.provider;
            if (options.emotion)
                params.emotion = options.emotion;
            if (typeof options.speed === 'number' && !Number.isNaN(options.speed))
                params.speed = options.speed;
            const client = new GenerationApiClient();
            const startTime = Date.now();
            if (pretty) {
                const spinner = ora(`正在合成语音 (${options.voice})...`).start();
                try {
                    const result = await client.submitAndPoll('tts', params, {
                        onProgress: (status) => {
                            spinner.text = `语音合成中 (${status})...`;
                        },
                    });
                    if (result.status === 'completed' && result.result_url) {
                        spinner.text = '正在下载音频...';
                        const filename = path.basename(outputPath);
                        const dir = path.dirname(outputPath);
                        await downloadResult(result.result_url, dir, filename);
                        const durationMs = Date.now() - startTime;
                        spinner.succeed('语音合成完成！');
                        success(`输出文件: ${outputPath}`);
                        info(`声音: ${options.voice}, 耗时: ${(durationMs / 1000).toFixed(1)}s`);
                        // 自动播放
                        if (options.play) {
                            const { execSync } = await import('child_process');
                            info('正在播放...');
                            execSync(`afplay "${outputPath}"`, { stdio: 'inherit' });
                        }
                    }
                    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('tts', params);
                if (result.status === 'completed' && result.result_url) {
                    const filename = path.basename(outputPath);
                    const dir = path.dirname(outputPath);
                    await downloadResult(result.result_url, dir, filename);
                    const durationMs = Date.now() - startTime;
                    outputSuccess({
                        task_id: result.task_id,
                        output: outputPath,
                        voice: options.voice,
                        text,
                        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('TTS_FAILED', `语音合成失败: ${err}`, options);
            }
        }
    });
    addEnhancedHelp(cmd, {
        examples: [
            '# 基本用法 - 中文语音合成',
            '$ gen tts "你好，欢迎使用语音合成"',
            '',
            '# 指定输出文件和声音',
            '$ gen tts "Hello world" -o hello.wav --voice Ethan',
            '',
            '# 使用男声',
            '$ gen tts "今天天气真好" --voice Ryan',
            '',
            '# 生成后自动播放',
            '$ gen tts "测试语音" --play',
            '',
            '# 情感 TTS（MiniMax）：悲伤语气 + 指定中文音色',
            '$ gen tts "一个人住，其实没那么孤单" --provider minimax --emotion sad --voice "Chinese (Mandarin)_Warm_Girl" -o seg.mp3',
            '',
            '# 列出可用声音（dashscope）',
            '$ gen tts "" --voices',
        ],
        outputJson: `{
  "success": true,
  "data": {
    "task_id": "abc-123",
    "output": "./gen-output/tts_1234567890.wav",
    "voice": "Cherry",
    "text": "你好",
    "durationMs": 1200
  }
}`,
        relatedCommands: [
            { command: 'asr <file>', description: '语音识别（语音转文字）' },
            { command: 'task get <id>', description: '查看任务状态' },
        ],
        notes: [
            '通过 optima-generation 调用 DashScope qwen3-tts-flash 模型',
            '需要 Optima 账号（~/.optima/token.json 或 OPTIMA_TOKEN）',
            '支持 50+ 种声音，支持中、英、日、韩等 10 种语言',
            '输出格式为 WAV',
        ],
    });
}
//# sourceMappingURL=tts.js.map