//! Web Integration Demo
//! 
//! This example demonstrates the web API integration for the Topaz Video AI
//! parameter configurator, showing how the web interface connects to the Rust backend.

use tvai::*;
use serde_json;

fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
    println!("=== Topaz Video AI Web Integration Demo ===\n");
    println!("Demonstrating the web API integration for the parameter configurator\n");

    // Demo 1: Get available templates
    println!("1. 获取可用模板:");
    match WebApi::get_templates() {
        Ok(templates) => {
            println!("找到 {} 个内置模板:", templates.len());
            for template in &templates {
                println!("  • {} - {}", template.name, template.description);
            }
            println!();
        }
        Err(e) => println!("获取模板失败: {}", e),
    }

    // Demo 2: Simulate web request for single-pass processing
    println!("2. 模拟单阶段处理请求:");
    let single_request = web_api::GenerateCommandRequest {
        settings: create_sample_web_settings(),
        input_file: "input_video.mp4".to_string(),
        output_file: "output_enhanced.mp4".to_string(),
        processing_mode: web_api::ProcessingMode::Single,
        rate_control: "constqp".to_string(),
    };

    let response = WebApi::generate_command(single_request);
    if response.success {
        if let Some(cmd) = response.single_command {
            println!("生成的单阶段命令:");
            println!("{}\n", cmd);
        }
        
        println!("使用统计:");
        println!("  • 启用的功能: {:?}", response.usage_stats.enabled_features);
        println!("  • 滤镜数量: {}", response.usage_stats.filter_count);
        println!("  • 参数使用率: {}%", response.usage_stats.parameter_usage_rate);
        println!("  • 处理复杂度: {}", response.usage_stats.processing_complexity);
        println!("  • 预估处理时间: {}", response.usage_stats.estimated_processing_time);
        println!();
    } else {
        println!("命令生成失败: {:?}", response.error);
    }

    // Demo 3: Simulate web request for two-pass processing
    println!("3. 模拟两阶段处理请求:");
    let two_pass_request = web_api::GenerateCommandRequest {
        settings: create_complex_web_settings(),
        input_file: "complex_input.mp4".to_string(),
        output_file: "complex_output.mov".to_string(),
        processing_mode: web_api::ProcessingMode::TwoPass,
        rate_control: "cbr".to_string(),
    };

    let response = WebApi::generate_command(two_pass_request);
    if response.success {
        if let Some(analysis_cmd) = response.analysis_command {
            println!("分析阶段命令:");
            println!("{}\n", analysis_cmd);
        }
        
        if let Some(processing_cmd) = response.processing_command {
            println!("处理阶段命令:");
            println!("{}\n", processing_cmd);
        }
        
        println!("复杂处理统计:");
        println!("  • 启用的功能: {:?}", response.usage_stats.enabled_features);
        println!("  • 滤镜数量: {}", response.usage_stats.filter_count);
        println!("  • 处理复杂度: {}", response.usage_stats.processing_complexity);
        println!();
    } else {
        println!("两阶段命令生成失败: {:?}", response.error);
    }

    // Demo 4: JSON serialization example (for web API)
    println!("4. JSON 序列化示例 (用于 Web API):");
    let sample_settings = create_sample_web_settings();
    match serde_json::to_string_pretty(&sample_settings) {
        Ok(json) => {
            println!("Web 设置 JSON 格式:");
            println!("{}\n", json);
        }
        Err(e) => println!("JSON 序列化失败: {}", e),
    }

    // Demo 5: Show parameter mapping
    println!("5. 参数映射演示:");
    println!("Web 表单参数 → Rust 结构体 → FFmpeg 命令");
    println!("  stabilize.active: true → StabilizeSettings.active → tvai_stb 滤镜");
    println!("  enhance.model: 'prob-4' → EnhanceSettings.model → tvai_up model 参数");
    println!("  slowmo.factor: 4 → SlowMotionSettings.factor → tvai_fi slowmo 参数");
    println!("  hdr.active: true → HdrSettings.active → tvai_up hyp-1 + setparams");
    println!("  rate_control: 'cbr' → RateControlMode::ConstantBitrate → -rc cbr -b:v 24M");
    println!();

    println!("=== Web Integration Summary ===");
    println!("🌐 Web API 功能:");
    println!("  • 模板获取: WebApi::get_templates()");
    println!("  • 命令生成: WebApi::generate_command()");
    println!("  • JSON 序列化: 完整支持 serde");
    println!("  • 错误处理: 统一的错误响应格式");
    println!();
    println!("🔧 集成特性:");
    println!("  • TypeScript 类型安全");
    println!("  • React 组件化界面");
    println!("  • 实时参数验证");
    println!("  • 命令预览和复制");
    println!("  • 模板自动填充");
    println!();
    println!("📊 技术栈:");
    println!("  • 后端: Rust + Serde + Topaz Video AI 库");
    println!("  • 前端: React + TypeScript + Tailwind CSS");
    println!("  • 通信: JSON API");
    println!("  • 集成: Desktop 应用内嵌页面");

    Ok(())
}

// 创建示例 Web 设置 (简单)
fn create_sample_web_settings() -> web_api::WebTopazSettings {
    web_api::WebTopazSettings {
        stabilize: web_api::WebStabilizeSettings {
            active: true,
            smooth: 50,
            method: 1,
            reduce_motion: 2,
            reduce_motion_iteration: 2,
            rsc: false,
        },
        motionblur: web_api::WebMotionBlurSettings {
            active: false,
            model: "thm-2".to_string(),
            model_name: "thm-2".to_string(),
        },
        slowmo: web_api::WebSlowMotionSettings {
            active: true,
            model: "apo-8".to_string(),
            factor: 4,
            duplicate_threshold: 10.0,
            duplicate: true,
        },
        enhance: web_api::WebEnhanceSettings {
            active: true,
            model: "prob-4".to_string(),
            video_type: 1,
            compress: 0,
            detail: 30,
            sharpen: 20,
            denoise: 15,
            dehalo: 10,
            deblur: 5,
            auto: 0,
            recover_original_detail_value: 20,
        },
        grain: web_api::WebGrainSettings {
            active: false,
            grain: 5,
            grain_size: 2,
        },
        hdr: web_api::WebHdrSettings {
            active: false,
            model: "hyp-1".to_string(),
            auto: 0,
            exposure: 0,
            saturation: 0,
            sdr_inflection_point: 0.7,
        },
        output: web_api::WebOutputSettings {
            active: true,
            out_size_method: 2, // 3x upscale
            out_fps: 0,
            crop_to_fit: false,
            lock_aspect_ratio: true,
        },
    }
}

// 创建复杂 Web 设置 (包含所有功能)
fn create_complex_web_settings() -> web_api::WebTopazSettings {
    web_api::WebTopazSettings {
        stabilize: web_api::WebStabilizeSettings {
            active: true,
            smooth: 60,
            method: 1,
            reduce_motion: 3,
            reduce_motion_iteration: 3,
            rsc: true,
        },
        motionblur: web_api::WebMotionBlurSettings {
            active: true,
            model: "thm-2".to_string(),
            model_name: "thm-2".to_string(),
        },
        slowmo: web_api::WebSlowMotionSettings {
            active: true,
            model: "apo-8".to_string(),
            factor: 2,
            duplicate_threshold: 5.0,
            duplicate: true,
        },
        enhance: web_api::WebEnhanceSettings {
            active: true,
            model: "ghq-5".to_string(),
            video_type: 1,
            compress: 10,
            detail: 50,
            sharpen: 40,
            denoise: 30,
            dehalo: 20,
            deblur: 60,
            auto: 0,
            recover_original_detail_value: 25,
        },
        grain: web_api::WebGrainSettings {
            active: true,
            grain: 8,
            grain_size: 3,
        },
        hdr: web_api::WebHdrSettings {
            active: true,
            model: "hyp-1".to_string(),
            auto: 50,
            exposure: 15,
            saturation: 12,
            sdr_inflection_point: 0.7,
        },
        output: web_api::WebOutputSettings {
            active: true,
            out_size_method: 3, // 4x upscale
            out_fps: 60,
            crop_to_fit: false,
            lock_aspect_ratio: true,
        },
    }
}
