pub mod template;
pub mod ffmpeg;
pub mod manager;
pub mod error;

pub use template::*;
pub use ffmpeg::*;
pub use manager::*;
pub use error::*;

/// Topaz Video AI Rust SDK
///
/// This SDK provides functionality to:
/// - Load and manage Topaz Video AI templates
/// - Convert templates to FFmpeg commands
/// - Validate and complete template structures
/// - Support database storage and runtime loading
pub struct TvaiSdk {
    manager: TemplateManager,
    pub ffmpeg_generator: FfmpegCommandGenerator,
}

impl TvaiSdk {
    /// Create a new SDK instance
    pub fn new() -> Self {
        Self {
            manager: TemplateManager::new(),
            ffmpeg_generator: FfmpegCommandGenerator::new(),
        }
    }

    /// Create SDK instance with custom model mappings
    pub fn with_model_mappings(mappings: std::collections::HashMap<String, String>) -> Self {
        let mut generator = FfmpegCommandGenerator::new();
        for (template_model, ffmpeg_model) in mappings {
            generator.add_model_mapping(template_model, ffmpeg_model);
        }

        Self {
            manager: TemplateManager::new(),
            ffmpeg_generator: generator,
        }
    }

    /// Load templates from a directory
    pub fn load_templates_from_dir<P: AsRef<std::path::Path>>(&mut self, path: P) -> Result<(), TvaiError> {
        self.manager.load_from_directory(path)
    }

    /// Load a single template from file
    pub fn load_template_from_file<P: AsRef<std::path::Path>>(&mut self, path: P) -> Result<Template, TvaiError> {
        self.manager.load_from_file(path)
    }

    /// Add a template to the SDK
    pub fn add_template(&mut self, template: Template) -> Result<(), TvaiError> {
        self.manager.add_template(template)
    }

    /// Remove a template by name
    pub fn remove_template(&mut self, name: &str) -> Option<Template> {
        self.manager.remove_template(name)
    }

    /// Get all loaded templates
    pub fn get_templates(&self) -> Vec<&Template> {
        self.manager.get_templates()
    }

    /// Get template names
    pub fn get_template_names(&self) -> Vec<&String> {
        self.manager.get_template_names()
    }

    /// Find template by name
    pub fn find_template(&self, name: &str) -> Option<&Template> {
        self.manager.find_by_name(name)
    }

    /// Check if template exists
    pub fn has_template(&self, name: &str) -> bool {
        self.manager.contains_template(name)
    }

    /// Get template count
    pub fn template_count(&self) -> usize {
        self.manager.template_count()
    }

    /// Generate FFmpeg command from template
    pub fn generate_ffmpeg_command(&self, template: &Template, input_file: &str, output_file: &str) -> Result<String, TvaiError> {
        self.ffmpeg_generator.generate(template, input_file, output_file)
    }

    /// Generate FFmpeg command with hardware acceleration
    pub fn generate_ffmpeg_command_with_gpu(&self, template: &Template, input_file: &str, output_file: &str, gpu_device: &str) -> Result<String, TvaiError> {
        self.ffmpeg_generator.generate_with_hardware_acceleration(template, input_file, output_file, Some(gpu_device))
    }

    /// Generate FFmpeg command with custom codec
    pub fn generate_ffmpeg_command_with_codec(&self, template: &Template, input_file: &str, output_file: &str, codec: &str, quality: Option<i32>) -> Result<String, TvaiError> {
        self.ffmpeg_generator.generate_with_codec(template, input_file, output_file, codec, quality)
    }

    /// Generate batch processing commands
    pub fn generate_batch_commands(&self, template: &Template, input_files: &[String], output_dir: &str) -> Result<Vec<String>, TvaiError> {
        self.ffmpeg_generator.generate_batch_commands(template, input_files, output_dir)
    }

    /// Validate template for FFmpeg generation
    pub fn validate_template_for_ffmpeg(&self, template: &Template) -> Result<(), TvaiError> {
        self.ffmpeg_generator.validate_template(template)
    }

    /// Validate and complete template structure
    pub fn validate_and_complete_template(&self, template: &mut Template) -> Result<(), TvaiError> {
        template.validate_and_complete()
    }

    /// Create a new template with default settings
    pub fn create_template(&self, name: &str, description: &str) -> Template {
        Template {
            name: name.to_string(),
            description: description.to_string(),
            author: "User".to_string(),
            date: chrono::Utc::now().format("%a %b %d %H:%M:%S %Y GMT%z").to_string(),
            veai_version: "5.1.2".to_string(),
            editable: true,
            enabled: true,
            save_output_settings: false,
            path: None,
            settings: TemplateSettings::default(),
        }
    }

    /// Export all templates to JSON
    pub fn export_templates_to_json(&self) -> Result<String, TvaiError> {
        self.manager.export_templates_to_json()
    }

    /// Import templates from JSON
    pub fn import_templates_from_json(&mut self, json: &str) -> Result<usize, TvaiError> {
        self.manager.import_templates_from_json(json)
    }

    /// Save all templates to directory
    pub fn save_templates_to_dir<P: AsRef<std::path::Path>>(&self, path: P) -> Result<(), TvaiError> {
        self.manager.save_templates_to_directory(path)
    }

    /// Clear all templates
    pub fn clear_templates(&mut self) {
        self.manager.clear();
    }

    /// Validate all loaded templates
    pub fn validate_all_templates(&mut self) -> Vec<(String, TvaiError)> {
        self.manager.validate_all_templates()
    }

    /// Get FFmpeg model mappings
    pub fn get_model_mappings(&self) -> &std::collections::HashMap<String, String> {
        self.ffmpeg_generator.get_model_mappings()
    }

    /// Add custom model mapping
    pub fn add_model_mapping(&mut self, template_model: String, ffmpeg_model: String) {
        self.ffmpeg_generator.add_model_mapping(template_model, ffmpeg_model);
    }
}

/// Template builder for creating templates programmatically
#[derive(Debug)]
pub struct TemplateBuilder {
    template: Template,
}

impl TemplateBuilder {
    /// Create a new template builder
    pub fn new(name: &str) -> Self {
        let template = Template {
            name: name.to_string(),
            description: String::new(),
            author: "User".to_string(),
            date: chrono::Utc::now().format("%a %b %d %H:%M:%S %Y GMT%z").to_string(),
            veai_version: "5.1.2".to_string(),
            editable: true,
            enabled: true,
            save_output_settings: false,
            path: None,
            settings: TemplateSettings::default(),
        };

        Self { template }
    }

    /// Set description
    pub fn description(mut self, description: &str) -> Self {
        self.template.description = description.to_string();
        self
    }

    /// Set author
    pub fn author(mut self, author: &str) -> Self {
        self.template.author = author.to_string();
        self
    }

    /// Enable video enhancement
    pub fn enable_enhancement(mut self, model: &str) -> Self {
        self.template.settings.enhance.active = true;
        self.template.settings.enhance.model = model.to_string();
        self
    }

    /// Configure enhancement parameters
    pub fn enhancement_params(mut self, denoise: i32, detail: i32, sharpen: i32) -> Self {
        self.template.settings.enhance.denoise = denoise;
        self.template.settings.enhance.detail = detail;
        self.template.settings.enhance.sharpen = sharpen;
        self
    }

    /// Enable frame interpolation
    pub fn enable_frame_interpolation(mut self, model: &str, factor: f64) -> Self {
        self.template.settings.slow_motion.active = true;
        self.template.settings.slow_motion.model = model.to_string();
        self.template.settings.slow_motion.factor = factor;
        self
    }

    /// Enable stabilization
    pub fn enable_stabilization(mut self, smoothness: i32, method: i32) -> Self {
        self.template.settings.stabilize.active = true;
        self.template.settings.stabilize.smooth = smoothness;
        self.template.settings.stabilize.method = method;
        self
    }

    /// Set output settings
    pub fn output_settings(mut self, size_method: i32, fps: f64) -> Self {
        self.template.settings.output.out_size_method = size_method;
        self.template.settings.output.out_fps = fps;
        self
    }

    /// Set custom resolution
    pub fn resolution(mut self, width: i32, height: i32) -> Self {
        self.template.settings.output.width = Some(width);
        self.template.settings.output.height = Some(height);
        self
    }

    /// Set video codec and quality
    pub fn video_codec(mut self, codec: &str, crf: Option<i32>) -> Self {
        self.template.settings.output.codec = Some(codec.to_string());
        if let Some(quality) = crf {
            self.template.settings.output.crf = Some(quality);
        }
        self
    }

    /// Set video bitrate (alternative to CRF)
    pub fn video_bitrate(mut self, bitrate: i32) -> Self {
        self.template.settings.output.bitrate = Some(bitrate);
        self.template.settings.output.crf = None; // Clear CRF when using bitrate
        self
    }

    /// Set encoding preset
    pub fn preset(mut self, preset: &str) -> Self {
        self.template.settings.output.preset = Some(preset.to_string());
        self
    }

    /// Set video profile and level
    pub fn profile_level(mut self, profile: &str, level: Option<&str>) -> Self {
        self.template.settings.output.profile = Some(profile.to_string());
        if let Some(l) = level {
            self.template.settings.output.level = Some(l.to_string());
        }
        self
    }

    /// Set audio settings
    pub fn audio_settings(mut self, codec: &str, bitrate: i32, channels: i32) -> Self {
        self.template.settings.output.audio_codec = Some(codec.to_string());
        self.template.settings.output.audio_bitrate = Some(bitrate);
        self.template.settings.output.audio_channels = Some(channels);
        self
    }

    /// Set audio settings with automatic optimization
    pub fn audio_settings_optimized(mut self, codec: &str, quality: &str) -> Self {
        self.template.settings.output.audio_codec = Some(codec.to_string());

        // Set optimized bitrate based on codec and quality
        let bitrate = match (codec.to_lowercase().as_str(), quality.to_lowercase().as_str()) {
            ("aac", "low") => 128,
            ("aac", "medium") => 192,
            ("aac", "high") => 256,
            ("aac", "highest") => 320,
            ("ac3", "low") => 160,
            ("ac3", "medium") => 256,
            ("ac3", "high") => 448,
            ("ac3", "highest") => 640,
            ("pcm", _) => 0, // Lossless, no bitrate needed
            ("vorbis", _) => 192, // Default for Vorbis
            _ => 192, // Safe default
        };

        if bitrate > 0 {
            self.template.settings.output.audio_bitrate = Some(bitrate);
        }

        // Set appropriate channels based on codec
        let channels = match codec.to_lowercase().as_str() {
            "aac" | "vorbis" => 2, // Stereo
            "ac3" => 6, // 5.1 surround
            "pcm" => 2, // Stereo for PCM
            _ => 2, // Default stereo
        };

        self.template.settings.output.audio_channels = Some(channels);
        self
    }

    /// Set container format with compatible audio codec
    pub fn container_format(mut self, format: &str) -> Self {
        self.template.settings.output.format = Some(format.to_string());

        // Auto-select compatible audio codec if not set
        if self.template.settings.output.audio_codec.is_none() {
            let codec = match format.to_lowercase().as_str() {
                "mp4" | "mov" | "mkv" | "avi" => "aac", // AAC is widely compatible
                "webm" => "vorbis", // Vorbis for WebM
                _ => "aac", // Default to AAC
            };
            self.template.settings.output.audio_codec = Some(codec.to_string());

            // Set appropriate channels and bitrate for the codec
            if codec == "vorbis" {
                self.template.settings.output.audio_channels = Some(2);
                self.template.settings.output.audio_bitrate = Some(192);
            }
        }

        self
    }

    /// Set hardware acceleration
    pub fn hardware_acceleration(mut self, hwaccel: &str, device: Option<&str>) -> Self {
        self.template.settings.output.hwaccel = Some(hwaccel.to_string());
        if let Some(dev) = device {
            self.template.settings.output.gpu_device = Some(dev.to_string());
        }
        self
    }

    /// Set pixel format
    pub fn pixel_format(mut self, format: &str) -> Self {
        self.template.settings.output.pixel_format = Some(format.to_string());
        self
    }

    /// Set color settings for HDR content
    pub fn color_settings(mut self, colorspace: &str, primaries: &str, trc: &str) -> Self {
        self.template.settings.output.colorspace = Some(colorspace.to_string());
        self.template.settings.output.color_primaries = Some(primaries.to_string());
        self.template.settings.output.color_trc = Some(trc.to_string());
        self
    }

    /// Add custom FFmpeg parameters
    pub fn custom_params(mut self, params: Vec<String>) -> Self {
        self.template.settings.output.custom_params = Some(params);
        self
    }

    /// Enable two-pass encoding
    pub fn two_pass(mut self, enabled: bool) -> Self {
        self.template.settings.output.two_pass = Some(enabled);
        self
    }

    /// Set output settings active state
    pub fn output_active(mut self, active: bool) -> Self {
        self.template.settings.output.active = active;
        self
    }

    /// Set custom resolution priority
    pub fn custom_resolution_priority(mut self, priority: i32) -> Self {
        self.template.settings.output.custom_resolution_priority = Some(priority);
        self
    }

    /// Set aspect ratio locking
    pub fn lock_aspect_ratio(mut self, lock: bool) -> Self {
        self.template.settings.output.lock_aspect_ratio = Some(lock);
        self
    }

    /// Enable crop to fit
    pub fn crop_to_fit(mut self, crop: bool) -> Self {
        self.template.settings.output.crop_to_fit = crop;
        self
    }

    /// Set pixel aspect ratio
    pub fn pixel_aspect_ratio(mut self, par: i32) -> Self {
        self.template.settings.output.output_par = par;
        self
    }

    /// Set AI model engine (automatically sets appropriate flags)
    pub fn ai_engine(mut self, engine: &str) -> Self {
        // Reset all model flags first
        self.template.settings.enhance.is_artemis = false;
        self.template.settings.enhance.is_gaia = false;
        self.template.settings.enhance.is_theia = false;
        self.template.settings.enhance.is_proteus = false;
        self.template.settings.enhance.is_iris = false;

        // Set the appropriate flag based on engine
        match engine.to_lowercase().as_str() {
            "artemis" => self.template.settings.enhance.is_artemis = true,
            "gaia" => self.template.settings.enhance.is_gaia = true,
            "theia" => self.template.settings.enhance.is_theia = true,
            "proteus" => self.template.settings.enhance.is_proteus = true,
            "iris" => self.template.settings.enhance.is_iris = true,
            _ => self.template.settings.enhance.is_proteus = true, // Default to Proteus
        }
        self
    }

    /// Set focus fix level
    pub fn focus_fix_level(mut self, level: &str) -> Self {
        self.template.settings.enhance.focus_fix_level = Some(level.to_string());
        self
    }

    /// Enable second enhancement
    pub fn second_enhancement(mut self, enabled: bool, intermediate_resolution: Option<i32>) -> Self {
        self.template.settings.enhance.is_second_enhancement = Some(enabled);

        if enabled {
            // Create filter manager if it doesn't exist
            if self.template.settings.filter_manager.is_none() {
                self.template.settings.filter_manager = Some(crate::FilterManagerSettings {
                    second_enhancement_enabled: true,
                    second_enhancement_intermediate_resolution: intermediate_resolution.unwrap_or(3),
                });
            } else if let Some(ref mut fm) = self.template.settings.filter_manager {
                fm.second_enhancement_enabled = true;
                if let Some(res) = intermediate_resolution {
                    fm.second_enhancement_intermediate_resolution = res;
                }
            }
        }
        self
    }

    /// Set benchmark mode (disables all non-essential processing)
    pub fn benchmark_mode(mut self, enabled: bool) -> Self {
        if enabled {
            // Disable all non-essential processing for pure model benchmarking
            self.template.settings.stabilize.active = false;
            self.template.settings.grain.active = false;
            self.template.settings.motion_blur.active = false;

            // Use minimal output settings
            self.template.settings.output.active = false;

            // Clear audio settings for video-only benchmarking
            self.template.settings.output.audio_codec = None;
            self.template.settings.output.audio_bitrate = None;
            self.template.settings.output.audio_channels = None;
        }
        self
    }

    /// Create a benchmark template for specific AI engine and scale
    pub fn benchmark_template(engine: &str, scale: i32) -> Result<Template, TvaiError> {
        let (model, description) = match engine.to_lowercase().as_str() {
            "artemis" => ("alq-13", "Artemis animation optimization benchmark"),
            "iris" => ("iris-3", "Iris low-light processing benchmark"),
            "proteus" => ("prob-4", "Proteus general enhancement benchmark"),
            "gaia" => ("ghq-5", "Gaia natural scene benchmark"),
            "nyx" => ("nyx-2", "Nyx noise reduction benchmark"),
            "nyx_fast" => ("nxf-1", "Nyx Fast noise reduction benchmark"),
            "rhea" => ("rhea-1", "Rhea specialized enhancement benchmark"),
            "rxl" => ("rxl-1", "RXL ultra-high quality benchmark"),
            "hyperion" => ("hyp-1", "Hyperion HDR processing benchmark"),
            _ => return Err(TvaiError::ValidationError(format!("Unknown benchmark engine: {}", engine))),
        };

        TemplateBuilder::new(&format!("Benchmark {} {}X", engine, scale))
            .description(description)
            .enable_enhancement(model)
            .enhancement_params(0, 0, 0) // No additional processing
            .benchmark_mode(true) // Enable benchmark mode
            .build()
    }

    /// Enable grain effect
    pub fn enable_grain(mut self, amount: i32, size: i32) -> Self {
        self.template.settings.grain.active = true;
        self.template.settings.grain.grain = amount;
        self.template.settings.grain.grain_size = size;
        self
    }

    /// Build the template
    pub fn build(mut self) -> Result<Template, TvaiError> {
        self.template.validate_and_complete()?;
        Ok(self.template)
    }
}

/// Predefined template presets
pub struct TemplatePresets;

impl TemplatePresets {
    /// Create a 4K upscaling template
    pub fn upscale_to_4k() -> Result<Template, TvaiError> {
        TemplateBuilder::new("Upscale to 4K")
            .description("Upscale video to 4K resolution with AI enhancement")
            .enable_enhancement("prob-4")
            .output_settings(7, 0.0) // 4K output
            .build()
    }

    /// Create a 60fps conversion template
    pub fn convert_to_60fps() -> Result<Template, TvaiError> {
        TemplateBuilder::new("Convert to 60 FPS")
            .description("Convert video to 60 FPS using frame interpolation")
            .enable_frame_interpolation("chf-3", 1.0)
            .output_settings(0, 60.0) // Original size, 60 FPS
            .build()
    }

    /// Create a noise removal template
    pub fn remove_noise() -> Result<Template, TvaiError> {
        TemplateBuilder::new("Remove Noise")
            .description("Remove noise from video using AI")
            .enable_enhancement("nyx-3")
            .enhancement_params(50, 0, 0) // High denoise, no detail/sharpen
            .build()
    }

    /// Create a stabilization template
    pub fn stabilize_video() -> Result<Template, TvaiError> {
        TemplateBuilder::new("Stabilize Video")
            .description("Stabilize shaky video with auto crop")
            .enable_stabilization(50, 0) // Medium smoothness, auto crop
            .build()
    }

    /// Create a slow motion template
    pub fn slow_motion_4x() -> Result<Template, TvaiError> {
        TemplateBuilder::new("4x Slow Motion")
            .description("Create 4x slow motion effect")
            .enable_frame_interpolation("apo-8", 4.0)
            .build()
    }

    /// Create a comprehensive enhancement template
    pub fn comprehensive_enhancement() -> Result<Template, TvaiError> {
        TemplateBuilder::new("Comprehensive Enhancement")
            .description("Complete video enhancement with upscaling, denoising, and stabilization")
            .enable_enhancement("prob-4")
            .enhancement_params(30, 20, 10) // Moderate denoise, detail, and sharpen
            .enable_stabilization(60, 1) // High smoothness, full frame
            .output_settings(6, 0.0) // FHD output
            .build()
    }

    /// Create a high-quality NVENC template
    pub fn high_quality_nvenc() -> Result<Template, TvaiError> {
        TemplateBuilder::new("High Quality NVENC")
            .description("High quality encoding with NVIDIA NVENC")
            .enable_enhancement("prob-4")
            .resolution(3840, 2160) // 4K
            .video_codec("hevc_nvenc", Some(18)) // H.265 with high quality
            .preset("slow")
            .profile_level("main10", Some("5.1"))
            .pixel_format("yuv420p10le") // 10-bit
            .audio_settings("aac", 256, 2) // High quality audio
            .hardware_acceleration("cuda", Some("0"))
            .build()
    }

    /// Create an HDR template
    pub fn hdr_processing() -> Result<Template, TvaiError> {
        TemplateBuilder::new("HDR Processing")
            .description("Process HDR content with proper color settings")
            .enable_enhancement("hyp-1") // Hyperion model for HDR
            .resolution(3840, 2160)
            .video_codec("hevc_nvenc", Some(16))
            .pixel_format("yuv420p10le")
            .color_settings("bt2020nc", "bt2020", "smpte2084")
            .custom_params(vec![
                "-color_range tv".to_string(),
                "-max_muxing_queue_size 1024".to_string(),
            ])
            .build()
    }

    /// Create a streaming optimized template
    pub fn streaming_optimized() -> Result<Template, TvaiError> {
        TemplateBuilder::new("Streaming Optimized")
            .description("Optimized for live streaming and fast encoding")
            .enable_enhancement("prob-4")
            .enhancement_params(15, 10, 20) // Light processing for speed
            .resolution(1920, 1080)
            .video_codec("h264_nvenc", Some(23))
            .preset("fast")
            .profile_level("high", Some("4.0"))
            .audio_settings("aac", 128, 2)
            .custom_params(vec![
                "-tune zerolatency".to_string(),
                "-rc vbr".to_string(),
            ])
            .build()
    }

    /// Create a mobile-optimized template
    pub fn mobile_optimized() -> Result<Template, TvaiError> {
        TemplateBuilder::new("Mobile Optimized")
            .description("Optimized for mobile devices with small file sizes")
            .enable_enhancement("prob-4")
            .enhancement_params(20, 15, 5)
            .resolution(1280, 720) // 720p
            .video_codec("libx264", Some(28)) // Higher CRF for smaller files
            .preset("fast")
            .profile_level("baseline", Some("3.1")) // Compatible profile
            .audio_settings("aac", 96, 2) // Lower audio bitrate
            .build()
    }

    /// Create an archival quality template
    pub fn archival_quality() -> Result<Template, TvaiError> {
        TemplateBuilder::new("Archival Quality")
            .description("Maximum quality for archival purposes")
            .enable_enhancement("prob-4")
            .enhancement_params(40, 50, 15) // High quality settings
            .enable_stabilization(80, 1)
            .resolution(3840, 2160)
            .video_codec("libx265", Some(12)) // Very high quality
            .preset("veryslow") // Maximum compression efficiency
            .profile_level("main10", Some("5.1"))
            .pixel_format("yuv420p10le")
            .audio_settings("flac", 0, 2) // Lossless audio
            .two_pass(true)
            .build()
    }

    /// Create a social media template with aspect ratio handling
    pub fn social_media_square() -> Result<Template, TvaiError> {
        TemplateBuilder::new("Social Media Square")
            .description("Square format for social media with smart cropping")
            .enable_enhancement("prob-4")
            .enhancement_params(20, 25, 15) // Moderate enhancement
            .resolution(1080, 1080) // Square format
            .video_codec("libx264", Some(25))
            .preset("fast") // Quick encoding for social media
            .crop_to_fit(true) // Crop to exact square
            .lock_aspect_ratio(false) // Allow cropping
            .custom_resolution_priority(1) // High priority for custom resolution
            .pixel_aspect_ratio(2) // 16:9 source handling
            .audio_settings("aac", 128, 2)
            .build()
    }

    /// Create a letterbox template that preserves aspect ratio
    pub fn letterbox_preserve() -> Result<Template, TvaiError> {
        TemplateBuilder::new("Letterbox Preserve")
            .description("Preserve aspect ratio with letterboxing")
            .enable_enhancement("prob-4")
            .resolution(1920, 1080) // Target FHD
            .video_codec("libx264", Some(23))
            .lock_aspect_ratio(true) // Preserve aspect ratio
            .crop_to_fit(false) // Use padding instead of cropping
            .custom_resolution_priority(0) // Normal priority
            .build()
    }

    /// Create a template with output settings disabled
    pub fn minimal_processing() -> Result<Template, TvaiError> {
        TemplateBuilder::new("Minimal Processing")
            .description("Minimal processing with basic output")
            .enable_enhancement("prob-4")
            .enhancement_params(10, 5, 0) // Very light processing
            .output_active(false) // Disable advanced output settings
            .build()
    }

    /// Create an animation/cartoon optimized template
    pub fn animation_enhance() -> Result<Template, TvaiError> {
        TemplateBuilder::new("Animation Enhancement")
            .description("Optimized for animation and cartoon content using Artemis AI")
            .enable_enhancement("art-2") // Artemis model
            .ai_engine("artemis") // Set Artemis flags
            .enhancement_params(15, 40, 25) // Low noise, high detail, good sharpening
            .resolution(1920, 1080)
            .video_codec("libx264", Some(20)) // High quality for animation
            .preset("slow")
            .build()
    }

    /// Create a natural scene optimized template
    pub fn natural_scene_enhance() -> Result<Template, TvaiError> {
        TemplateBuilder::new("Natural Scene Enhancement")
            .description("Optimized for natural landscapes using Gaia AI")
            .enable_enhancement("gai-2") // Gaia model
            .ai_engine("gaia") // Set Gaia flags
            .enhancement_params(20, 35, 15) // Moderate noise, high detail, light sharpening
            .resolution(3840, 2160) // 4K for nature content
            .video_codec("hevc_nvenc", Some(18))
            .preset("slow")
            .build()
    }

    /// Create a detail recovery template
    pub fn detail_recovery() -> Result<Template, TvaiError> {
        TemplateBuilder::new("Detail Recovery")
            .description("Maximum detail recovery using Theia AI")
            .enable_enhancement("the-2") // Theia model
            .ai_engine("theia") // Set Theia flags
            .enhancement_params(10, 60, 40) // Low noise, maximum detail, high sharpening
            .focus_fix_level("High") // High focus fix
            .second_enhancement(true, Some(4)) // Enable second pass at 2x resolution
            .build()
    }

    /// Create a low light optimized template
    pub fn low_light_enhance() -> Result<Template, TvaiError> {
        TemplateBuilder::new("Low Light Enhancement")
            .description("Optimized for low light and noisy footage using Iris AI")
            .enable_enhancement("nyx-3") // Iris/Nyx model for noise
            .ai_engine("iris") // Set Iris flags
            .enhancement_params(60, 20, 5) // High noise reduction, moderate detail
            .focus_fix_level("Medium") // Medium focus fix for low light
            .build()
    }

    /// Create a general purpose template with Proteus
    pub fn general_purpose_proteus() -> Result<Template, TvaiError> {
        TemplateBuilder::new("General Purpose Proteus")
            .description("General purpose enhancement using Proteus AI")
            .enable_enhancement("prob-4") // Proteus model
            .ai_engine("proteus") // Set Proteus flags (default)
            .enhancement_params(25, 30, 20) // Balanced settings
            .enable_stabilization(60, 1) // Add stabilization
            .resolution(1920, 1080)
            .build()
    }

    /// Create a web-optimized template
    pub fn web_optimized() -> Result<Template, TvaiError> {
        TemplateBuilder::new("Web Optimized")
            .description("Optimized for web streaming with WebM container")
            .enable_enhancement("prob-4")
            .enhancement_params(15, 20, 10) // Light processing for web
            .resolution(1920, 1080)
            .video_codec("libvpx-vp9", Some(30)) // VP9 for WebM
            .container_format("webm") // Auto-selects Vorbis audio
            .audio_settings_optimized("vorbis", "medium")
            .preset("fast")
            .build()
    }

    /// Create a professional master template
    pub fn professional_master() -> Result<Template, TvaiError> {
        TemplateBuilder::new("Professional Master")
            .description("Professional quality with lossless audio")
            .enable_enhancement("prob-4")
            .enhancement_params(30, 40, 20) // High quality settings
            .resolution(3840, 2160) // 4K
            .video_codec("libx265", Some(15)) // High quality H.265
            .container_format("mov") // Professional container
            .audio_settings_optimized("pcm", "highest") // Lossless audio
            .preset("veryslow")
            .build()
    }

    /// Create a broadcast template
    pub fn broadcast_ready() -> Result<Template, TvaiError> {
        TemplateBuilder::new("Broadcast Ready")
            .description("Broadcast standard with AC3 surround sound")
            .enable_enhancement("prob-4")
            .enhancement_params(20, 25, 15) // Broadcast quality
            .resolution(1920, 1080)
            .video_codec("libx264", Some(18)) // Broadcast quality
            .container_format("mp4")
            .audio_settings_optimized("ac3", "high") // 5.1 surround
            .preset("medium")
            .build()
    }

    /// Create benchmark templates for performance testing
    pub fn benchmark_artemis_2x() -> Result<Template, TvaiError> {
        TemplateBuilder::new("Benchmark Artemis 2X")
            .description("Artemis 2X upscaling benchmark")
            .enable_enhancement("alq-13")
            .enhancement_params(0, 0, 0) // Pure model performance
            .build()
    }

    pub fn benchmark_proteus_4x() -> Result<Template, TvaiError> {
        TemplateBuilder::new("Benchmark Proteus 4X")
            .description("Proteus 4X upscaling benchmark")
            .enable_enhancement("prob-4")
            .enhancement_params(0, 0, 0) // Pure model performance
            .build()
    }

    pub fn benchmark_apollo_slowmo() -> Result<Template, TvaiError> {
        TemplateBuilder::new("Benchmark Apollo 4X Slowmo")
            .description("Apollo 4X slow motion benchmark")
            .enable_enhancement("prob-4")
            .enable_frame_interpolation("apo-8", 4.0) // 4X slow motion
            .build()
    }

    pub fn benchmark_hyperion_hdr() -> Result<Template, TvaiError> {
        TemplateBuilder::new("Benchmark Hyperion HDR")
            .description("Hyperion HDR processing benchmark")
            .enable_enhancement("hyp-1")
            .enhancement_params(0, 0, 0) // Pure HDR processing
            .build()
    }
}

impl Default for TvaiSdk {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_sdk_creation() {
        let sdk = TvaiSdk::new();
        assert_eq!(sdk.get_templates().len(), 0);
    }
}
