use tvai_sdk::*;
use std::path::Path;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    println!("Topaz Video AI SDK - Template Management Example");
    println!("===============================================");

    // Create SDK instance
    let mut sdk = TvaiSdk::new();

    // Example 1: Load templates from directory
    println!("\n1. Loading templates from directory:");
    
    let template_dir = "template"; // Relative to current directory
    if Path::new(template_dir).exists() {
        match sdk.load_templates_from_dir(template_dir) {
            Ok(()) => {
                println!("   Successfully loaded templates from directory: {}", template_dir);
                println!("   Total templates loaded: {}", sdk.template_count());
                
                // List loaded templates
                let template_names = sdk.get_template_names();
                for name in template_names {
                    println!("     - {}", name);
                }
            },
            Err(e) => {
                println!("   Failed to load templates: {}", e);
                println!("   Creating templates using presets instead...");
                
                // Create some templates using presets
                sdk.add_template(TemplatePresets::upscale_to_4k()?)?;
                sdk.add_template(TemplatePresets::convert_to_60fps()?)?;
                sdk.add_template(TemplatePresets::remove_noise()?)?;
                sdk.add_template(TemplatePresets::stabilize_video()?)?;
                sdk.add_template(TemplatePresets::slow_motion_4x()?)?;
                
                println!("   Created {} preset templates", sdk.template_count());
            }
        }
    } else {
        println!("   Template directory '{}' not found, creating preset templates...", template_dir);
        
        // Create preset templates
        sdk.add_template(TemplatePresets::upscale_to_4k()?)?;
        sdk.add_template(TemplatePresets::convert_to_60fps()?)?;
        sdk.add_template(TemplatePresets::remove_noise()?)?;
        sdk.add_template(TemplatePresets::stabilize_video()?)?;
        sdk.add_template(TemplatePresets::slow_motion_4x()?)?;
        sdk.add_template(TemplatePresets::comprehensive_enhancement()?)?;
        
        println!("   Created {} preset templates", sdk.template_count());
    }

    // Example 2: Create and manage custom templates
    println!("\n2. Creating custom templates:");
    
    // Create a custom deinterlacing template
    let deinterlace_template = TemplateBuilder::new("Deinterlace and Enhance")
        .description("Deinterlace interlaced video and enhance quality")
        .author("Template Manager")
        .enable_enhancement("prob-4")
        .enhancement_params(20, 30, 15) // moderate denoise, high detail, some sharpen
        .output_settings(6, 0.0) // FHD output
        .build()?;
    
    sdk.add_template(deinterlace_template)?;
    println!("   Created: Deinterlace and Enhance");
    
    // Create a film restoration template
    let film_restore_template = TemplateBuilder::new("Film Restoration")
        .description("Restore old film footage with comprehensive enhancement")
        .author("Template Manager")
        .enable_enhancement("prob-4")
        .enhancement_params(40, 50, 20) // high denoise and detail for old film
        .enable_stabilization(80, 1) // high stabilization for old footage
        .enable_grain(2, 1) // subtle grain to maintain film look
        .output_settings(7, 24.0) // 4K output at 24fps
        .build()?;
    
    sdk.add_template(film_restore_template)?;
    println!("   Created: Film Restoration");
    
    // Create a gaming video template
    let gaming_template = TemplateBuilder::new("Gaming Video Enhancement")
        .description("Optimize gaming footage for streaming")
        .author("Template Manager")
        .enable_enhancement("prob-4")
        .enhancement_params(10, 25, 30) // low denoise, good detail, high sharpen
        .enable_frame_interpolation("chf-3", 1.0)
        .output_settings(6, 60.0) // FHD at 60fps
        .build()?;
    
    sdk.add_template(gaming_template)?;
    println!("   Created: Gaming Video Enhancement");

    println!("   Total templates after additions: {}", sdk.template_count());

    // Example 3: Template inspection and modification
    println!("\n3. Template inspection:");
    
    if let Some(template) = sdk.find_template("Gaming Video Enhancement") {
        println!("   Template: {}", template.name);
        println!("   Description: {}", template.description);
        println!("   Author: {}", template.author);
        println!("   Version: {}", template.veai_version);
        println!("   Settings:");
        println!("     Enhancement active: {}", template.settings.enhance.active);
        println!("     Enhancement model: {}", template.settings.enhance.model);
        println!("     Denoise: {}", template.settings.enhance.denoise);
        println!("     Detail: {}", template.settings.enhance.detail);
        println!("     Sharpen: {}", template.settings.enhance.sharpen);
        println!("     Frame interpolation active: {}", template.settings.slow_motion.active);
        println!("     Output FPS: {}", template.settings.output.out_fps);
    }

    // Example 4: Template validation
    println!("\n4. Template validation:");
    
    let validation_errors = sdk.validate_all_templates();
    if validation_errors.is_empty() {
        println!("   ✅ All templates are valid");
    } else {
        println!("   ❌ Found validation errors:");
        for (name, error) in validation_errors {
            println!("     {}: {}", name, error);
        }
    }

    // Example 5: Export templates to files
    println!("\n5. Exporting templates:");
    
    // Create output directory
    let output_dir = "exported_templates";
    std::fs::create_dir_all(output_dir)?;
    
    // Save all templates to directory
    match sdk.save_templates_to_dir(output_dir) {
        Ok(()) => {
            println!("   ✅ Successfully exported all templates to: {}", output_dir);
            
            // List exported files
            let entries = std::fs::read_dir(output_dir)?;
            println!("   Exported files:");
            for entry in entries {
                let entry = entry?;
                if entry.path().extension().and_then(|s| s.to_str()) == Some("json") {
                    println!("     - {}", entry.file_name().to_string_lossy());
                }
            }
        },
        Err(e) => println!("   ❌ Failed to export templates: {}", e),
    }

    // Example 6: Template removal and cleanup
    println!("\n6. Template management operations:");
    
    // Remove a specific template
    if let Some(removed) = sdk.remove_template("Gaming Video Enhancement") {
        println!("   Removed template: {}", removed.name);
        println!("   Remaining templates: {}", sdk.template_count());
    }
    
    // Show remaining templates
    println!("   Current templates:");
    for name in sdk.get_template_names() {
        println!("     - {}", name);
    }

    // Example 7: JSON export/import workflow
    println!("\n7. JSON export/import workflow:");
    
    // Export to JSON string
    let json_data = sdk.export_templates_to_json()?;
    println!("   Exported {} templates to JSON ({} bytes)", sdk.template_count(), json_data.len());
    
    // Save JSON to file
    let json_file = format!("{}/all_templates.json", output_dir);
    std::fs::write(&json_file, &json_data)?;
    println!("   Saved JSON to: {}", json_file);
    
    // Clear all templates
    let original_count = sdk.template_count();
    sdk.clear_templates();
    println!("   Cleared all templates (was: {}, now: {})", original_count, sdk.template_count());
    
    // Import from JSON file
    let imported_json = std::fs::read_to_string(&json_file)?;
    let imported_count = sdk.import_templates_from_json(&imported_json)?;
    println!("   Imported {} templates from JSON file", imported_count);
    println!("   Final template count: {}", sdk.template_count());

    // Example 8: Model mappings
    println!("\n8. Model mappings:");
    
    let mappings = sdk.get_model_mappings();
    println!("   Current model mappings:");
    for (template_model, ffmpeg_model) in mappings {
        println!("     {} -> {}", template_model, ffmpeg_model);
    }
    
    // Add custom model mapping
    sdk.add_model_mapping("custom-model-1".to_string(), "custom-ffmpeg-1".to_string());
    println!("   Added custom model mapping: custom-model-1 -> custom-ffmpeg-1");

    println!("\n✅ Template management example completed successfully!");
    println!("   Final statistics:");
    println!("     Total templates: {}", sdk.template_count());
    println!("     Model mappings: {}", sdk.get_model_mappings().len());
    
    Ok(())
}
