use tvai_sdk::{TvaiSdk, TemplateBuilder};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    println!("🎬 Topaz Video AI SDK 综合功能演示");
    println!("=====================================\n");

    let sdk = TvaiSdk::new();

    // 1. 展示内置配置加载
    println!("📦 1. 内置配置状态:");
    println!("   音频编解码器: {} 个", sdk.ffmpeg_generator.get_available_audio_codecs().len());
    println!("   视频编码器: {} 个", sdk.ffmpeg_generator.get_available_video_encoders().len());
    
    // 验证关键编解码器
    let key_codecs = ["AAC", "AC3", "PCM"];
    for codec in &key_codecs {
        if sdk.ffmpeg_generator.get_audio_codec(codec).is_some() {
            println!("   ✓ {} 编解码器已加载", codec);
        }
    }
    println!();

    // 2. 模型推荐演示
    println!("🤖 2. AI 模型推荐:");
    let resolutions = [(480, "SD"), (720, "HD"), (1080, "FHD"), (2160, "4K")];
    for (height, name) in &resolutions {
        let models = sdk.ffmpeg_generator.recommend_model_for_resolution(*height);
        println!("   {} ({}p): {:?}", name, height, models);
    }
    println!();

    // 3. 平台兼容性演示
    println!("💻 3. 平台兼容性:");
    let platforms = [("windows", "Windows"), ("osx", "macOS"), ("linux", "Linux")];
    for (os, name) in &platforms {
        let count = sdk.ffmpeg_generator.get_compatible_video_encoders(os, None).len();
        println!("   {}: {} 个兼容编码器", name, count);
    }
    println!();

    // 4. 创建不同用途的模板
    println!("📝 4. 模板创建演示:");
    
    // 4K 上采样模板
    let upscale_template = TemplateBuilder::new("4K上采样")
        .description("将视频上采样到4K分辨率")
        .enable_enhancement("prob-4")
        .enhancement_params(20, 35, 15)
        .resolution(3840, 2160)
        .video_codec("hevc_nvenc", Some(18))
        .audio_settings("AAC", 256, 2)
        .build()?;
    println!("   ✓ 4K上采样模板创建成功");

    // 60fps 插帧模板
    let fps_template = TemplateBuilder::new("60fps插帧")
        .description("将视频插帧到60fps")
        .enable_frame_interpolation("chr-2", 1.0)
        .output_settings(0, 60.0)
        .video_codec("h264_nvenc", Some(23))
        .audio_settings("AAC", 192, 2)
        .build()?;
    println!("   ✓ 60fps插帧模板创建成功");

    // 降噪模板
    let denoise_template = TemplateBuilder::new("降噪处理")
        .description("使用Nyx模型进行降噪")
        .enable_enhancement("nyx-3")
        .enhancement_params(70, 15, 5)
        .video_codec("libx264", Some(20))
        .audio_settings("AAC", 160, 2)
        .build()?;
    println!("   ✓ 降噪处理模板创建成功");
    println!();

    // 5. FFmpeg 命令生成演示
    println!("⚙️  5. FFmpeg 命令生成:");
    
    let test_files = [
        ("input_sd.mp4", "output_4k.mp4", &upscale_template, "4K上采样"),
        ("input_30fps.mp4", "output_60fps.mp4", &fps_template, "60fps插帧"),
        ("noisy_video.mp4", "clean_video.mp4", &denoise_template, "降噪处理"),
    ];

    for (input, output, template, desc) in &test_files {
        let command = sdk.generate_ffmpeg_command(template, input, output)?;
        println!("   {} 命令:", desc);
        println!("   {}\n", truncate_command(&command, 100));
    }

    // 6. 自动编码器选择演示
    println!("🔧 6. 自动编码器选择:");
    let auto_scenarios = [
        ("windows", Some("nvidia"), "Windows + NVIDIA"),
        ("osx", Some("appleIntel"), "macOS + Intel"),
        ("linux", None, "Linux 软件编码"),
    ];

    for (os, gpu, desc) in &auto_scenarios {
        match sdk.ffmpeg_generator.generate_with_auto_encoder(
            &upscale_template,
            "input.mp4",
            "output.mp4",
            os,
            *gpu
        ) {
            Ok(command) => println!("   ✓ {}: 命令生成成功", desc),
            Err(e) => println!("   ✗ {}: {}", desc, e),
        }
    }
    println!();

    // 7. 批处理演示
    println!("📁 7. 批处理功能:");
    let batch_files = vec![
        "video1.mp4".to_string(),
        "video2.mp4".to_string(), 
        "video3.mp4".to_string(),
    ];
    
    let batch_commands = sdk.generate_batch_commands(&upscale_template, &batch_files, "output")?;
    println!("   生成了 {} 个批处理命令", batch_commands.len());
    for (i, _) in batch_commands.iter().enumerate() {
        println!("   ✓ 批处理命令 {} 生成成功", i + 1);
    }
    println!();

    // 8. 编码器参数生成演示
    println!("🎛️  8. 编码器参数生成:");
    
    // 音频参数
    let audio_tests = [("AAC", 192), ("AC3", 448), ("AAC", 128)];
    for (codec, bitrate) in &audio_tests {
        let params = sdk.ffmpeg_generator.generate_audio_codec_params(codec, Some(*bitrate));
        println!("   {} {}kbps: {}", codec, bitrate, params);
    }
    
    // 视频参数
    if let Some(encoder) = sdk.ffmpeg_generator.get_video_encoder("h264-high-win-nvidia") {
        let vbr_params = sdk.ffmpeg_generator.generate_video_encoder_params(&encoder.id, "vbr", Some(23));
        println!("   H.264 NVENC VBR: {}", truncate_command(&vbr_params, 80));
    }
    println!();

    // 9. 性能统计
    println!("📊 9. 功能统计:");
    println!("   支持的音频格式: {:?}", get_supported_audio_formats(&sdk));
    println!("   支持的视频格式: {:?}", get_supported_video_formats(&sdk));
    println!("   硬件加速编码器: {} 个", count_hardware_encoders(&sdk));
    println!("   跨平台编码器: {} 个", count_cross_platform_encoders(&sdk));
    println!();

    println!("🎉 综合演示完成！");
    println!("所有功能正常工作，内置配置系统运行良好。");

    Ok(())
}

fn truncate_command(command: &str, max_len: usize) -> String {
    if command.len() <= max_len {
        command.to_string()
    } else {
        format!("{}...", &command[..max_len])
    }
}

fn get_supported_audio_formats(sdk: &TvaiSdk) -> Vec<String> {
    let mut formats = std::collections::HashSet::new();
    for codec in sdk.ffmpeg_generator.get_available_audio_codecs() {
        for ext in &codec.ext {
            formats.insert(ext.clone());
        }
    }
    let mut result: Vec<_> = formats.into_iter().collect();
    result.sort();
    result
}

fn get_supported_video_formats(sdk: &TvaiSdk) -> Vec<String> {
    let mut formats = std::collections::HashSet::new();
    for encoder in sdk.ffmpeg_generator.get_available_video_encoders() {
        for ext in &encoder.ext {
            formats.insert(ext.clone());
        }
    }
    let mut result: Vec<_> = formats.into_iter().collect();
    result.sort();
    result
}

fn count_hardware_encoders(sdk: &TvaiSdk) -> usize {
    sdk.ffmpeg_generator.get_available_video_encoders()
        .iter()
        .filter(|encoder| encoder.gpu.is_some())
        .count()
}

fn count_cross_platform_encoders(sdk: &TvaiSdk) -> usize {
    sdk.ffmpeg_generator.get_available_video_encoders()
        .iter()
        .filter(|encoder| {
            encoder.os.as_ref().map_or(false, |os| os.contains('|'))
        })
        .count()
}
