#[cfg(test)]
mod priority_order_matching_logic_tests {
    use crate::data::models::template::{SegmentMatchingRule, TrackSegment};
    use crate::data::models::material::MaterialSegment;
    use crate::data::models::ai_classification::AiClassification;
    use chrono::Utc;

    /// 创建测试用的AI分类
    fn create_test_classifications() -> Vec<AiClassification> {
        vec![
            AiClassification {
                id: "cat_quanshen".to_string(),
                name: "全身".to_string(),
                prompt_text: "全身镜头".to_string(),
                description: Some("完整的人物全身镜头".to_string()),
                is_active: true,
                sort_order: 1,
                weight: 10,
                created_at: Utc::now(),
                updated_at: Utc::now(),
            },
            AiClassification {
                id: "cat_shangbanshen".to_string(),
                name: "上半身".to_string(),
                prompt_text: "上半身镜头".to_string(),
                description: Some("人物上半身镜头".to_string()),
                is_active: true,
                sort_order: 2,
                weight: 9,
                created_at: Utc::now(),
                updated_at: Utc::now(),
            },
            AiClassification {
                id: "cat_zhongduan".to_string(),
                name: "中段特写".to_string(),
                prompt_text: "中段特写镜头".to_string(),
                description: Some("人物中段特写镜头".to_string()),
                is_active: true,
                sort_order: 3,
                weight: 8,
                created_at: Utc::now(),
                updated_at: Utc::now(),
            },
            AiClassification {
                id: "cat_xiabanshen".to_string(),
                name: "下半身".to_string(),
                prompt_text: "下半身镜头".to_string(),
                description: Some("人物下半身镜头".to_string()),
                is_active: true,
                sort_order: 4,
                weight: 7,
                created_at: Utc::now(),
                updated_at: Utc::now(),
            },
        ]
    }

    /// 创建测试用的素材片段
    fn create_test_material_segments() -> Vec<(MaterialSegment, String)> {
        vec![
            (
                MaterialSegment {
                    id: "seg_1".to_string(),
                    material_id: "mat_1".to_string(),
                    segment_index: 0,
                    start_time: 0.0,
                    end_time: 5.0, // 5秒
                    duration: 5.0,
                    file_path: "/path/to/video1.mp4".to_string(),
                    file_size: 1024000,
                    thumbnail_path: None,
                    usage_count: 0,
                    is_used: false,
                    last_used_at: None,
                    created_at: Utc::now(),
                },
                "全身".to_string(), // 分类名称
            ),
            (
                MaterialSegment {
                    id: "seg_2".to_string(),
                    material_id: "mat_2".to_string(),
                    segment_index: 0,
                    start_time: 0.0,
                    end_time: 5.0,
                    duration: 5.0,
                    file_path: "/path/to/video2.mp4".to_string(),
                    file_size: 1024000,
                    thumbnail_path: None,
                    usage_count: 0,
                    is_used: false,
                    last_used_at: None,
                    created_at: Utc::now(),
                },
                "上半身".to_string(),
            ),
            (
                MaterialSegment {
                    id: "seg_3".to_string(),
                    material_id: "mat_3".to_string(),
                    segment_index: 0,
                    start_time: 0.0,
                    end_time: 5.0,
                    duration: 5.0,
                    file_path: "/path/to/video3.mp4".to_string(),
                    file_size: 1024000,
                    thumbnail_path: None,
                    usage_count: 0,
                    is_used: false,
                    last_used_at: None,
                    created_at: Utc::now(),
                },
                "中段特写".to_string(),
            ),
            (
                MaterialSegment {
                    id: "seg_4".to_string(),
                    material_id: "mat_4".to_string(),
                    segment_index: 0,
                    start_time: 0.0,
                    end_time: 5.0,
                    duration: 5.0,
                    file_path: "/path/to/video4.mp4".to_string(),
                    file_size: 1024000,
                    thumbnail_path: None,
                    usage_count: 0,
                    is_used: false,
                    last_used_at: None,
                    created_at: Utc::now(),
                },
                "下半身".to_string(),
            ),
        ]
    }

    /// 创建测试用的轨道片段
    fn create_test_track_segment(matching_rule: SegmentMatchingRule) -> TrackSegment {
        TrackSegment {
            id: "track_seg_1".to_string(),
            track_id: "track_1".to_string(),
            template_material_id: None,
            name: "测试片段".to_string(),
            start_time: 0,
            end_time: 5000000,
            duration: 5000000,
            segment_index: 0,
            properties: None,
            matching_rule,
            created_at: Utc::now(),
            updated_at: Utc::now(),
        }
    }

    #[test]
    fn test_priority_order_matching_only_selected_categories() {
        // 测试：只有用户选中的分类参与匹配
        
        // 用户只选择了"全身"和"上半身"两个分类
        let selected_category_ids = vec![
            "cat_quanshen".to_string(),
            "cat_shangbanshen".to_string(),
        ];
        
        let matching_rule = SegmentMatchingRule::PriorityOrder {
            category_ids: selected_category_ids.clone(),
        };
        
        // 验证匹配规则包含正确的分类
        match &matching_rule {
            SegmentMatchingRule::PriorityOrder { category_ids } => {
                assert_eq!(category_ids.len(), 2);
                assert!(category_ids.contains(&"cat_quanshen".to_string()));
                assert!(category_ids.contains(&"cat_shangbanshen".to_string()));
                assert!(!category_ids.contains(&"cat_zhongduan".to_string()));
                assert!(!category_ids.contains(&"cat_xiabanshen".to_string()));
            }
            _ => panic!("Expected PriorityOrder rule"),
        }
    }

    #[test]
    fn test_priority_order_weight_sorting() {
        // 测试：权重排序逻辑
        
        let classifications = create_test_classifications();
        
        // 按权重降序排序
        let mut sorted_classifications = classifications.clone();
        sorted_classifications.sort_by(|a, b| b.weight.cmp(&a.weight));
        
        // 验证排序结果
        assert_eq!(sorted_classifications[0].name, "全身");
        assert_eq!(sorted_classifications[0].weight, 10);
        assert_eq!(sorted_classifications[1].name, "上半身");
        assert_eq!(sorted_classifications[1].weight, 9);
        assert_eq!(sorted_classifications[2].name, "中段特写");
        assert_eq!(sorted_classifications[2].weight, 8);
        assert_eq!(sorted_classifications[3].name, "下半身");
        assert_eq!(sorted_classifications[3].weight, 7);
    }

    #[test]
    fn test_priority_order_filtering_logic() {
        // 测试：分类过滤逻辑
        
        let classifications = create_test_classifications();
        let selected_category_ids = vec![
            "cat_quanshen".to_string(),
            "cat_shangbanshen".to_string(),
        ];
        
        // 模拟匹配逻辑：只处理选中的分类
        let filtered_classifications: Vec<_> = classifications
            .into_iter()
            .filter(|classification| selected_category_ids.contains(&classification.id))
            .collect();
        
        // 验证过滤结果
        assert_eq!(filtered_classifications.len(), 2);
        assert!(filtered_classifications.iter().any(|c| c.name == "全身"));
        assert!(filtered_classifications.iter().any(|c| c.name == "上半身"));
        assert!(!filtered_classifications.iter().any(|c| c.name == "中段特写"));
        assert!(!filtered_classifications.iter().any(|c| c.name == "下半身"));
    }

    #[test]
    fn test_priority_order_matching_sequence() {
        // 测试：匹配顺序逻辑
        
        let classifications = create_test_classifications();
        let material_segments = create_test_material_segments();
        let selected_category_ids = vec![
            "cat_quanshen".to_string(),
            "cat_shangbanshen".to_string(),
        ];
        
        // 模拟匹配过程：按权重顺序尝试匹配
        let mut matched_segment: Option<&(MaterialSegment, String)> = None;
        
        // 按权重降序排序分类
        let mut sorted_classifications = classifications.clone();
        sorted_classifications.sort_by(|a, b| b.weight.cmp(&a.weight));
        
        // 按顺序尝试匹配每个选中的分类
        for classification in sorted_classifications {
            if !selected_category_ids.contains(&classification.id) {
                continue; // 跳过未选中的分类
            }
            
            // 查找匹配的素材片段
            if let Some(segment) = material_segments.iter().find(|(_, category)| category == &classification.name) {
                matched_segment = Some(segment);
                break; // 找到第一个匹配的就停止
            }
        }
        
        // 验证匹配结果
        assert!(matched_segment.is_some());
        let (segment, category) = matched_segment.unwrap();
        assert_eq!(category, "全身"); // 应该匹配到权重最高的"全身"分类
        assert_eq!(segment.id, "seg_1");
    }

    #[test]
    fn test_priority_order_fallback_to_lower_weight() {
        // 测试：当高权重分类无素材时，回退到低权重分类
        
        let classifications = create_test_classifications();
        let selected_category_ids = vec![
            "cat_quanshen".to_string(),
            "cat_shangbanshen".to_string(),
        ];
        
        // 创建只有"上半身"素材的场景（没有"全身"素材）
        let material_segments = vec![
            (
                MaterialSegment {
                    id: "seg_2".to_string(),
                    material_id: "mat_2".to_string(),
                    segment_index: 0,
                    start_time: 0.0,
                    end_time: 5.0,
                    duration: 5.0,
                    file_path: "/path/to/video2.mp4".to_string(),
                    file_size: 1024000,
                    thumbnail_path: None,
                    usage_count: 0,
                    is_used: false,
                    last_used_at: None,
                    created_at: Utc::now(),
                },
                "上半身".to_string(),
            ),
        ];
        
        // 模拟匹配过程
        let mut matched_segment: Option<&(MaterialSegment, String)> = None;
        let mut sorted_classifications = classifications.clone();
        sorted_classifications.sort_by(|a, b| b.weight.cmp(&a.weight));
        
        for classification in sorted_classifications {
            if !selected_category_ids.contains(&classification.id) {
                continue;
            }
            
            if let Some(segment) = material_segments.iter().find(|(_, category)| category == &classification.name) {
                matched_segment = Some(segment);
                break;
            }
        }
        
        // 验证匹配结果：应该匹配到"上半身"（因为"全身"没有可用素材）
        assert!(matched_segment.is_some());
        let (segment, category) = matched_segment.unwrap();
        assert_eq!(category, "上半身");
        assert_eq!(segment.id, "seg_2");
    }

    #[test]
    fn test_priority_order_no_match_for_unselected_categories() {
        // 测试：未选中的分类不参与匹配，即使有可用素材
        
        let classifications = create_test_classifications();
        let selected_category_ids = vec![
            "cat_quanshen".to_string(), // 只选择"全身"
        ];
        
        // 创建只有"中段特写"和"下半身"素材的场景
        let material_segments = vec![
            (
                MaterialSegment {
                    id: "seg_3".to_string(),
                    material_id: "mat_3".to_string(),
                    segment_index: 0,
                    start_time: 0.0,
                    end_time: 5.0,
                    duration: 5.0,
                    file_path: "/path/to/video3.mp4".to_string(),
                    file_size: 1024000,
                    thumbnail_path: None,
                    usage_count: 0,
                    is_used: false,
                    last_used_at: None,
                    created_at: Utc::now(),
                },
                "中段特写".to_string(),
            ),
            (
                MaterialSegment {
                    id: "seg_4".to_string(),
                    material_id: "mat_4".to_string(),
                    segment_index: 0,
                    start_time: 0.0,
                    end_time: 5.0,
                    duration: 5.0,
                    file_path: "/path/to/video4.mp4".to_string(),
                    file_size: 1024000,
                    thumbnail_path: None,
                    usage_count: 0,
                    is_used: false,
                    last_used_at: None,
                    created_at: Utc::now(),
                },
                "下半身".to_string(),
            ),
        ];
        
        // 模拟匹配过程
        let mut matched_segment: Option<&(MaterialSegment, String)> = None;
        let mut sorted_classifications = classifications.clone();
        sorted_classifications.sort_by(|a, b| b.weight.cmp(&a.weight));
        
        for classification in sorted_classifications {
            if !selected_category_ids.contains(&classification.id) {
                continue; // 跳过未选中的分类
            }
            
            if let Some(segment) = material_segments.iter().find(|(_, category)| category == &classification.name) {
                matched_segment = Some(segment);
                break;
            }
        }
        
        // 验证匹配结果：应该没有匹配到任何素材（因为只选择了"全身"，但没有"全身"素材）
        assert!(matched_segment.is_none());
    }
}
