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

/// 水印模板实体模型
/// 遵循 Tauri 开发规范的数据模型设计原则
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WatermarkTemplate {
    pub id: String,
    pub name: String,
    pub file_path: String,
    pub thumbnail_path: Option<String>,
    pub category: WatermarkCategory,
    pub watermark_type: WatermarkType,
    pub file_size: u64,
    pub width: Option<u32>,
    pub height: Option<u32>,
    pub description: Option<String>,
    pub tags: Vec<String>,
    pub is_active: bool,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}

/// 水印类型枚举
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum WatermarkType {
    Image,      // 图片水印 (PNG, JPG)
    Vector,     // 矢量水印 (SVG)
    Text,       // 文字水印
    Animated,   // 动态水印 (GIF, 动画)
}

/// 水印分类枚举
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum WatermarkCategory {
    Logo,       // 品牌标识
    Copyright,  // 版权标识
    Signature,  // 签名
    Decoration, // 装饰性
    Custom,     // 自定义
}

/// 水印检测结果
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WatermarkDetectionResult {
    pub id: String,
    pub material_id: String,
    pub detection_method: DetectionMethod,
    pub detections: Vec<WatermarkDetection>,
    pub confidence_score: f64,
    pub processing_time_ms: u64,
    pub created_at: DateTime<Utc>,
}

/// 单个水印检测信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WatermarkDetection {
    pub region: BoundingBox,
    pub confidence: f64,
    pub watermark_type: Option<WatermarkType>,
    pub template_id: Option<String>, // 匹配的模板ID（如果使用模板匹配）
    pub description: Option<String>,
}

/// 边界框定义
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BoundingBox {
    pub x: u32,
    pub y: u32,
    pub width: u32,
    pub height: u32,
}

/// 检测方法枚举
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum DetectionMethod {
    TemplateMatching,   // 模板匹配
    EdgeDetection,      // 边缘检测
    FrequencyAnalysis,  // 频域分析
    TransparencyDetection, // 透明度检测
    Combined,           // 组合检测
}

/// 水印配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WatermarkConfig {
    pub watermark_type: WatermarkType,
    pub position: WatermarkPosition,
    pub opacity: f32,           // 透明度 0.0-1.0
    pub scale: f32,             // 缩放比例
    pub rotation: f32,          // 旋转角度（度）
    pub animation: Option<WatermarkAnimation>,
    pub blend_mode: BlendMode,
    pub quality_level: QualityLevel,
}

/// 水印位置配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum WatermarkPosition {
    TopLeft,
    TopCenter,
    TopRight,
    MiddleLeft,
    Center,
    MiddleRight,
    BottomLeft,
    BottomCenter,
    BottomRight,
    Custom { x: f32, y: f32 },  // 相对位置 0.0-1.0
    Dynamic(DynamicPositionRule), // 动态位置
}

/// 动态位置规则
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DynamicPositionRule {
    pub avoid_faces: bool,      // 避开人脸
    pub avoid_text: bool,       // 避开文字
    pub follow_motion: bool,    // 跟随运动
    pub corner_preference: Vec<Corner>, // 角落偏好
    pub min_distance_from_edge: u32, // 距离边缘最小像素
}

/// 角落枚举
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum Corner {
    TopLeft,
    TopRight,
    BottomLeft,
    BottomRight,
}

/// 水印动画配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WatermarkAnimation {
    pub animation_type: AnimationType,
    pub duration_ms: u32,
    pub loop_count: Option<u32>, // None表示无限循环
    pub easing: EasingFunction,
}

/// 动画类型
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum AnimationType {
    FadeIn,         // 淡入
    FadeOut,        // 淡出
    SlideIn,        // 滑入
    SlideOut,       // 滑出
    Rotate,         // 旋转
    Scale,          // 缩放
    Pulse,          // 脉冲
    Custom(String), // 自定义动画
}

/// 缓动函数
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum EasingFunction {
    Linear,
    EaseIn,
    EaseOut,
    EaseInOut,
    Bounce,
    Elastic,
}

/// 混合模式
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum BlendMode {
    Normal,
    Multiply,
    Screen,
    Overlay,
    SoftLight,
    HardLight,
    ColorDodge,
    ColorBurn,
}

/// 质量级别
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum QualityLevel {
    Low,        // 快速处理，质量较低
    Medium,     // 平衡处理，中等质量
    High,       // 高质量处理，速度较慢
    Lossless,   // 无损处理，最高质量
}

/// 水印移除配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WatermarkRemovalConfig {
    pub method: RemovalMethod,
    pub quality_level: QualityLevel,
    pub preserve_aspect_ratio: bool,
    pub target_regions: Option<Vec<BoundingBox>>, // 指定移除区域
    pub inpainting_model: Option<String>, // AI修复模型
    pub blur_radius: Option<f32>,         // 模糊半径
    pub crop_margin: Option<u32>,         // 裁剪边距
}

/// 移除方法
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum RemovalMethod {
    Inpainting,     // AI修复
    Blurring,       // 模糊处理
    Cropping,       // 裁剪移除
    Masking,        // 遮罩覆盖
    ContentAware,   // 内容感知填充
    Clone,          // 克隆修复
}

/// 水印检测配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WatermarkDetectionConfig {
    pub similarity_threshold: f64,      // 相似度阈值 0.0-1.0
    pub min_watermark_size: (u32, u32), // 最小水印尺寸
    pub max_watermark_size: (u32, u32), // 最大水印尺寸
    pub detection_regions: Vec<DetectionRegion>, // 检测区域
    pub frame_sample_rate: u32,         // 视频帧采样率
    pub methods: Vec<DetectionMethod>,  // 使用的检测方法
    pub template_ids: Option<Vec<String>>, // 指定模板ID列表
}

/// 检测区域
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum DetectionRegion {
    FullFrame,      // 全帧检测
    Corners,        // 四角检测
    Edges,          // 边缘检测
    Center,         // 中心区域
    Custom(BoundingBox), // 自定义区域
}

/// 批量水印处理任务
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchWatermarkTask {
    pub task_id: String,
    pub operation: WatermarkOperation,
    pub material_ids: Vec<String>,
    pub config: serde_json::Value, // 动态配置，根据operation类型解析
    pub status: BatchTaskStatus,
    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 WatermarkOperation {
    Detect,
    Remove,
    Add,
    DetectAndRemove,
    Replace, // 检测并替换
}

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

/// 批量处理进度
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchProgress {
    pub total_items: u32,
    pub processed_items: u32,
    pub failed_items: u32,
    pub current_item: Option<String>, // 当前处理的素材ID
    pub progress_percentage: f32,     // 进度百分比 0.0-100.0
    pub estimated_remaining_ms: Option<u64>, // 预估剩余时间（毫秒）
    pub errors: Vec<String>,          // 错误信息列表
    pub detection_results: Vec<WatermarkDetectionResult>, // 检测结果列表
    pub processing_results: Vec<WatermarkProcessingResult>, // 处理结果列表
}

/// 水印处理结果
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WatermarkProcessingResult {
    pub material_id: String,
    pub operation: WatermarkOperation,
    pub success: bool,
    pub output_path: Option<String>,
    pub processing_time_ms: u64,
    pub error_message: Option<String>,
    pub metadata: Option<serde_json::Value>, // 额外的处理元数据
}

impl Default for WatermarkConfig {
    fn default() -> Self {
        Self {
            watermark_type: WatermarkType::Image,
            position: WatermarkPosition::BottomRight,
            opacity: 0.8,
            scale: 1.0,
            rotation: 0.0,
            animation: None,
            blend_mode: BlendMode::Normal,
            quality_level: QualityLevel::Medium,
        }
    }
}

impl Default for WatermarkDetectionConfig {
    fn default() -> Self {
        Self {
            similarity_threshold: 0.8,
            min_watermark_size: (32, 32),
            max_watermark_size: (512, 512),
            detection_regions: vec![
                DetectionRegion::Corners,
                DetectionRegion::Center,
            ],
            frame_sample_rate: 30, // 每30帧采样一次
            methods: vec![
                DetectionMethod::TemplateMatching,
                DetectionMethod::EdgeDetection,
            ],
            template_ids: None,
        }
    }
}

impl Default for WatermarkRemovalConfig {
    fn default() -> Self {
        Self {
            method: RemovalMethod::Inpainting,
            quality_level: QualityLevel::Medium,
            preserve_aspect_ratio: true,
            target_regions: None,
            inpainting_model: None,
            blur_radius: Some(5.0),
            crop_margin: Some(10),
        }
    }
}
