use serde::{Deserialize, Serialize};
use chrono::{DateTime, Utc};
use std::path::PathBuf;

/// 缩略图生成配置
/// 遵循 Tauri 开发规范的数据模型设计原则
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ThumbnailConfig {
    pub time_points: Vec<TimePoint>,
    pub size: ThumbnailSize,
    pub format: ImageFormat,
    pub quality: u8,
    pub output_dir: PathBuf,
    pub naming_pattern: String,
    pub preserve_aspect_ratio: bool,
}

/// 时间点配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum TimePoint {
    Fixed(f64),                    // 固定时间点（秒）
    Percentage(f32),               // 百分比位置 (0.0-1.0)
    Multiple(Vec<f64>),            // 多个时间点
    SmartDetection(u32),           // 智能场景检测（帧数）
}

/// 缩略图尺寸配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ThumbnailSize {
    pub width: u32,
    pub height: u32,
    pub preset: Option<SizePreset>,
}

/// 预设尺寸
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum SizePreset {
    Tiny,       // 160x120
    Small,      // 320x240
    Medium,     // 640x480
    Large,      // 1280x720
    FullHD,     // 1920x1080
    Custom,     // 自定义尺寸
}

/// 图片格式
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum ImageFormat {
    Jpg,
    Png,
    WebP,
}

/// 时间轴缩略图配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TimelineConfig {
    pub frame_count: u32,
    pub layout: TimelineLayout,
    pub show_timestamps: bool,
    pub spacing: u32,
    pub background_color: Option<String>,
    pub border_width: Option<u32>,
}

/// 时间轴布局
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum TimelineLayout {
    Horizontal,
    Vertical,
    Grid { columns: u32 },
}

/// 批量缩略图任务
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchThumbnailTask {
    pub task_id: String,
    pub video_files: Vec<PathBuf>,
    pub config: ThumbnailConfig,
    pub timeline_config: Option<TimelineConfig>,
    pub status: TaskStatus,
    pub progress: BatchProgress,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
    pub started_at: Option<DateTime<Utc>>,
    pub completed_at: Option<DateTime<Utc>>,
}

/// 任务状态
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum TaskStatus {
    Pending,    // 等待中
    Running,    // 执行中
    Completed,  // 已完成
    Failed,     // 失败
    Cancelled,  // 已取消
    Paused,     // 已暂停
}

/// 批量处理进度
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchProgress {
    pub total_files: u32,
    pub processed_files: u32,
    pub failed_files: u32,
    pub current_file: Option<String>,
    pub progress_percentage: f32,
    pub estimated_remaining_ms: Option<u64>,
    pub processing_speed: Option<f32>, // 文件/秒
    pub errors: Vec<String>,
    pub results: Vec<ThumbnailGenerationResult>,
}

/// 缩略图生成结果
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ThumbnailGenerationResult {
    pub video_path: String,
    pub success: bool,
    pub output_paths: Vec<String>,
    pub timeline_path: Option<String>,
    pub processing_time_ms: u64,
    pub error_message: Option<String>,
    pub metadata: ThumbnailMetadata,
}

/// 缩略图元数据
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ThumbnailMetadata {
    pub video_duration: f64,
    pub video_resolution: (u32, u32),
    pub thumbnail_count: u32,
    pub total_file_size: u64,
    pub timestamps_used: Vec<f64>,
}

/// 视频文件信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VideoFile {
    pub path: PathBuf,
    pub name: String,
    pub size: u64,
    pub duration: Option<f64>,
    pub resolution: Option<(u32, u32)>,
    pub format: Option<String>,
    pub is_valid: bool,
}

/// 场景检测结果
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SceneDetectionResult {
    pub video_path: String,
    pub scenes: Vec<SceneInfo>,
    pub best_frames: Vec<f64>,
    pub detection_method: SceneDetectionMethod,
    pub confidence_scores: Vec<f32>,
}

/// 场景信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SceneInfo {
    pub start_time: f64,
    pub end_time: f64,
    pub duration: f64,
    pub confidence: f32,
    pub representative_frame: f64,
}

/// 场景检测方法
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum SceneDetectionMethod {
    ContentBased,   // 基于内容的场景检测
    MotionBased,    // 基于运动的场景检测
    ColorBased,     // 基于颜色的场景检测
    Combined,       // 组合检测
}

/// 缩略图生成选项
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ThumbnailGenerationOptions {
    pub enable_retry: bool,
    pub max_retries: u32,
    pub retry_delay_ms: u64,
    pub enable_parallel: bool,
    pub max_concurrent: u32,
    pub enable_cache: bool,
    pub cache_duration_hours: u32,
    pub enable_validation: bool,
    pub min_file_size: u64,
}

// 默认实现
impl Default for ThumbnailConfig {
    fn default() -> Self {
        Self {
            time_points: vec![TimePoint::Percentage(0.5)], // 默认50%位置
            size: ThumbnailSize::default(),
            format: ImageFormat::Jpg,
            quality: 85,
            output_dir: PathBuf::from("thumbnails"),
            naming_pattern: "{filename}_{timestamp}.{ext}".to_string(),
            preserve_aspect_ratio: true,
        }
    }
}

impl Default for ThumbnailSize {
    fn default() -> Self {
        Self {
            width: 320,
            height: 240,
            preset: Some(SizePreset::Small),
        }
    }
}

impl Default for TimelineConfig {
    fn default() -> Self {
        Self {
            frame_count: 10,
            layout: TimelineLayout::Horizontal,
            show_timestamps: true,
            spacing: 2,
            background_color: Some("#000000".to_string()),
            border_width: Some(1),
        }
    }
}

impl Default for ThumbnailGenerationOptions {
    fn default() -> Self {
        Self {
            enable_retry: true,
            max_retries: 3,
            retry_delay_ms: 1000,
            enable_parallel: true,
            max_concurrent: 4,
            enable_cache: true,
            cache_duration_hours: 24,
            enable_validation: true,
            min_file_size: 1024, // 1KB
        }
    }
}

impl SizePreset {
    pub fn to_dimensions(&self) -> (u32, u32) {
        match self {
            SizePreset::Tiny => (160, 120),
            SizePreset::Small => (320, 240),
            SizePreset::Medium => (640, 480),
            SizePreset::Large => (1280, 720),
            SizePreset::FullHD => (1920, 1080),
            SizePreset::Custom => (320, 240), // 默认值
        }
    }
}

impl ImageFormat {
    pub fn extension(&self) -> &'static str {
        match self {
            ImageFormat::Jpg => "jpg",
            ImageFormat::Png => "png",
            ImageFormat::WebP => "webp",
        }
    }
    
    pub fn mime_type(&self) -> &'static str {
        match self {
            ImageFormat::Jpg => "image/jpeg",
            ImageFormat::Png => "image/png",
            ImageFormat::WebP => "image/webp",
        }
    }
}
