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

/// 素材使用类型枚举
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum MaterialUsageType {
    /// 模板匹配使用
    TemplateMatching,
    /// 手动编辑使用
    ManualEdit,
    /// 其他用途
    Other,
}

impl Default for MaterialUsageType {
    fn default() -> Self {
        Self::TemplateMatching
    }
}

/// 素材使用记录实体模型
/// 记录素材片段在各种场景下的使用情况
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MaterialUsageRecord {
    pub id: String,
    pub material_segment_id: String,
    pub material_id: String,
    pub project_id: String,
    pub template_matching_result_id: String,
    pub template_id: String,
    pub binding_id: String,
    pub track_segment_id: String,
    pub usage_type: MaterialUsageType,
    pub usage_context: Option<String>, // JSON格式的使用上下文信息
    pub created_at: DateTime<Utc>,
}

impl MaterialUsageRecord {
    /// 创建新的素材使用记录实例
    pub fn new(
        material_segment_id: String,
        material_id: String,
        project_id: String,
        template_matching_result_id: String,
        template_id: String,
        binding_id: String,
        track_segment_id: String,
        usage_type: MaterialUsageType,
        usage_context: Option<String>,
    ) -> Self {
        Self {
            id: uuid::Uuid::new_v4().to_string(),
            material_segment_id,
            material_id,
            project_id,
            template_matching_result_id,
            template_id,
            binding_id,
            track_segment_id,
            usage_type,
            usage_context,
            created_at: Utc::now(),
        }
    }

    /// 创建模板匹配使用记录
    pub fn new_template_matching(
        material_segment_id: String,
        material_id: String,
        project_id: String,
        template_matching_result_id: String,
        template_id: String,
        binding_id: String,
        track_segment_id: String,
        match_score: f64,
        match_reason: String,
    ) -> Self {
        let usage_context = serde_json::json!({
            "match_score": match_score,
            "match_reason": match_reason,
            "usage_timestamp": Utc::now().to_rfc3339()
        }).to_string();

        Self::new(
            material_segment_id,
            material_id,
            project_id,
            template_matching_result_id,
            template_id,
            binding_id,
            track_segment_id,
            MaterialUsageType::TemplateMatching,
            Some(usage_context),
        )
    }

    /// 验证记录的有效性
    pub fn validate(&self) -> Result<(), String> {
        if self.material_segment_id.is_empty() {
            return Err("素材片段ID不能为空".to_string());
        }
        if self.material_id.is_empty() {
            return Err("素材ID不能为空".to_string());
        }
        if self.project_id.is_empty() {
            return Err("项目ID不能为空".to_string());
        }
        if self.template_matching_result_id.is_empty() {
            return Err("模板匹配结果ID不能为空".to_string());
        }
        Ok(())
    }
}

/// 素材使用统计信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MaterialUsageStats {
    pub material_id: String,
    pub material_name: String,
    pub total_segments: u32,
    pub used_segments: u32,
    pub unused_segments: u32,
    pub total_usage_count: u32,
    pub last_used_at: Option<DateTime<Utc>>,
    pub usage_rate: f64, // 使用率 (used_segments / total_segments)
}

impl MaterialUsageStats {
    /// 创建新的素材使用统计实例
    pub fn new(
        material_id: String,
        material_name: String,
        total_segments: u32,
        used_segments: u32,
        total_usage_count: u32,
        last_used_at: Option<DateTime<Utc>>,
    ) -> Self {
        let unused_segments = total_segments.saturating_sub(used_segments);
        let usage_rate = if total_segments > 0 {
            used_segments as f64 / total_segments as f64
        } else {
            0.0
        };

        Self {
            material_id,
            material_name,
            total_segments,
            used_segments,
            unused_segments,
            total_usage_count,
            last_used_at,
            usage_rate,
        }
    }
}

/// 项目素材使用概览
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProjectMaterialUsageOverview {
    pub project_id: String,
    pub total_materials: u32,
    pub total_segments: u32,
    pub used_segments: u32,
    pub unused_segments: u32,
    pub total_usage_count: u32,
    pub overall_usage_rate: f64,
    pub materials_stats: Vec<MaterialUsageStats>,
}

impl ProjectMaterialUsageOverview {
    /// 创建新的项目素材使用概览实例
    pub fn new(
        project_id: String,
        materials_stats: Vec<MaterialUsageStats>,
    ) -> Self {
        let total_materials = materials_stats.len() as u32;
        let total_segments: u32 = materials_stats.iter().map(|s| s.total_segments).sum();
        let used_segments: u32 = materials_stats.iter().map(|s| s.used_segments).sum();
        let unused_segments = total_segments.saturating_sub(used_segments);
        let total_usage_count: u32 = materials_stats.iter().map(|s| s.total_usage_count).sum();
        let overall_usage_rate = if total_segments > 0 {
            used_segments as f64 / total_segments as f64
        } else {
            0.0
        };

        Self {
            project_id,
            total_materials,
            total_segments,
            used_segments,
            unused_segments,
            total_usage_count,
            overall_usage_rate,
            materials_stats,
        }
    }
}

/// 创建素材使用记录请求
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateMaterialUsageRecordRequest {
    pub material_segment_id: String,
    pub material_id: String,
    pub project_id: String,
    pub template_matching_result_id: String,
    pub template_id: String,
    pub binding_id: String,
    pub track_segment_id: String,
    pub usage_type: MaterialUsageType,
    pub usage_context: Option<String>,
}

impl CreateMaterialUsageRecordRequest {
    /// 验证请求的有效性
    pub fn validate(&self) -> Result<(), String> {
        if self.material_segment_id.is_empty() {
            return Err("素材片段ID不能为空".to_string());
        }
        if self.material_id.is_empty() {
            return Err("素材ID不能为空".to_string());
        }
        if self.project_id.is_empty() {
            return Err("项目ID不能为空".to_string());
        }
        Ok(())
    }

    /// 转换为素材使用记录实体
    pub fn to_entity(self) -> MaterialUsageRecord {
        MaterialUsageRecord::new(
            self.material_segment_id,
            self.material_id,
            self.project_id,
            self.template_matching_result_id,
            self.template_id,
            self.binding_id,
            self.track_segment_id,
            self.usage_type,
            self.usage_context,
        )
    }
}
