import { Option } from 'commander';
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, downloadResult, resolveOutputPath, } from '../services/generation-api.js';
export function registerVideoTranslateCommand(program) {
    const cmd = program
        .command('video-translate')
        .description('视频翻译（HeyGen，自动 lip-sync + 克隆原说话人声音）')
        .requiredOption('--video-url <url>', '源视频 URL（http/https，需公开可访问）')
        .requiredOption('--lang <language>', '目标语言（人类可读名，如 "English" / "Chinese (Mandarin, Simplified)"）')
        .option('--title <title>', '视频标题')
        .option('--audio-only', '只翻译音频（off-screen 解说，不做 lip-sync）')
        .option('--speaker-num <n>', '说话人数量（多人对话场景）')
        .addOption(new Option('--mode <mode>', '生成模式：fast（默认）| quality（2x credits）').choices(['fast', 'quality']).default('fast'))
        .option('--dynamic-duration', '允许调整时长以适配不同语言语速')
        .option('--keep-format', '保留原视频分辨率/格式（不要默认压缩）')
        .option('--brand-voice-id <id>', 'Brand voice ID（自定义术语/发音规则）')
        .option('--voice <id>', 'Stock voice ID（HeyGen catalog 里的 voice_id）。不传则克隆源说话人音色')
        .option('-o, --output <dir>', '输出目录', '')
        .action(async (options) => {
        const pretty = isPrettyMode(options);
        try {
            const params = {
                video_url: options.videoUrl,
                output_language: options.lang,
                title: options.title,
                translate_audio_only: options.audioOnly,
                speaker_num: options.speakerNum ? parseInt(options.speakerNum) : undefined,
                mode: options.mode,
                enable_dynamic_duration: options.dynamicDuration,
                keep_the_same_format: options.keepFormat,
                brand_voice_id: options.brandVoiceId,
                voice_id: options.voice,
            };
            const client = new GenerationApiClient();
            const defaultDir = getConfigValue('outputDir') || './gen-output';
            const spinner = pretty ? ora('正在提交视频翻译任务...').start() : null;
            if (pretty)
                spinner.text = `正在翻译视频到 ${options.lang}（预计 5-20 分钟，视频长度而定）...`;
            const result = await client.submitAndPoll('video-translate', params, {
                timeout: 1800000, // 30 min
                interval: 15000, // 15s
                onProgress: (status) => {
                    if (pretty)
                        spinner.text = `视频翻译中 (${status})...`;
                },
            });
            if (result.status === 'completed' && result.result_url) {
                const langSlug = String(options.lang).toLowerCase().replace(/[^a-z0-9]+/g, '-').slice(0, 30);
                const defaultFilename = `translate_${langSlug}_${result.task_id.slice(0, 8)}.mp4`;
                const { dir, filename } = resolveOutputPath(options.output, defaultDir, defaultFilename);
                const outputPath = await downloadResult(result.result_url, dir, filename);
                if (pretty) {
                    spinner.succeed('视频翻译完成！');
                    success(`输出文件: ${outputPath}`);
                    info(`任务 ID: ${result.task_id}`);
                    if (result.result_meta?.caption_url) {
                        info(`字幕文件: ${result.result_meta.caption_url}`);
                    }
                }
                else {
                    outputSuccess({
                        task_id: result.task_id,
                        status: result.status,
                        output: outputPath, // downloaded mp4 (lip-synced)
                        result_url: result.result_url, // remote video URL (lip-synced)
                        caption_url: result.result_meta?.caption_url, // remote SRT URL
                        audio_url: result.result_meta?.audio_url, // v3: remote audio-only URL (no lip-sync)
                        video_url: result.result_meta?.video_url, // v3: remote video URL (lip-synced, same as result_url)
                        output_language: result.result_meta?.output_language,
                    });
                }
            }
            else {
                // task status != completed → 失败。让顶层 success:false 并 exit 1，否则
                // Agent 会把 failure 当 success（参见 image.ts 同样修复）。
                const errCode = result.error_code ?? 'GENERATION_FAILED';
                const errMsg = result.error_message ?? `任务状态: ${result.status}`;
                if (pretty) {
                    spinner.fail(errMsg);
                    if (result.error_code)
                        info(`错误码: ${result.error_code}${result.retryable ? '（可重试）' : ''}`);
                    info(`使用 'gen task get ${result.task_id}' 查看最新状态`);
                    process.exit(1);
                }
                else {
                    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('VIDEO_TRANSLATE_FAILED', `翻译失败: ${err}`, options);
            }
        }
    });
    addEnhancedHelp(cmd, {
        examples: [
            '# 翻译到英语',
            '$ gen video-translate --video-url https://example.com/v.mp4 --lang "English"',
            '',
            '# 翻译到简体中文（注意语言名要带括号）',
            '$ gen video-translate --video-url https://example.com/v.mp4 --lang "Chinese (Mandarin, Simplified)"',
            '',
            '# 高质量模式（2x credits）',
            '$ gen video-translate --video-url ... --lang "Spanish" --mode quality',
            '',
            '# 多说话人 + 只翻音频（off-screen 解说）',
            '$ gen video-translate --video-url ... --lang "Japanese" --audio-only --speaker-num 2',
        ],
        outputJson: `{
  "success": true,
  "data": {
    "task_id": "abc-123-def",
    "status": "completed",
    "output": "./gen-output/translate_english_abc123.mp4",
    "output_language": "English"
  }
}`,
        relatedCommands: [
            { command: 'task get <id>', description: '查看任务状态' },
            { command: 'video', description: '生成视频' },
        ],
        notes: [
            '由 HeyGen 提供，自动 lip-sync 并克隆原说话人的声音（无需额外参数）',
            '支持 30+ 种语言，常用：English / Spanish / French / German / Japanese / Korean / Chinese (Mandarin, Simplified)',
            '语言名必须用 HeyGen 官方人类可读名（不是 ISO 码）',
            '视频翻译需要 5-20 分钟（取决于视频长度），HeyGen 平台限制无法加速',
            'mode=quality 比 fast 慢 + 贵 2x，但效果更好',
            '需要 Optima 账号（~/.optima/token.json 或 OPTIMA_TOKEN）',
        ],
    });
}
//# sourceMappingURL=video-translate.js.map