crawlrs 0.2.0

crawlrs - Enterprise-grade web scraping and crawling platform built with Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
// Copyright (c) 2025-2026 Kirky.X🌠
// SPDX-License-Identifier: Apache-2.0

use crate::domain::models::search_result::SearchResult;
use std::collections::hash_map::DefaultHasher;
use std::collections::HashSet;
use std::hash::{Hash, Hasher};

/// 去重策略
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum DeduplicationStrategy {
    /// 仅基于URL去重
    UrlOnly,
    /// 仅基于标题去重
    TitleOnly,
    /// URL和标题组合去重
    UrlAndTitle,
    /// 智能去重 (URL + 标题相似度 + 内容指纹)
    Smart,
}

/// 内容指纹配置
#[derive(Debug, Clone)]
pub struct ContentFingerprintConfig {
    /// 是否启用内容指纹
    pub enabled: bool,
    /// 指纹算法 (hash, simhash)
    pub algorithm: FingerprintAlgorithm,
    /// 指纹长度
    pub fingerprint_size: usize,
    /// SimHash 海明距离阈值 (0-64)
    pub simhash_threshold: u8,
}

impl Default for ContentFingerprintConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            algorithm: FingerprintAlgorithm::SimHash,
            fingerprint_size: 64,
            simhash_threshold: 10, // 海明距离阈值
        }
    }
}

/// 指纹算法
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum FingerprintAlgorithm {
    /// 简单哈希
    Hash,
    /// SimHash (局部敏感哈希)
    SimHash,
}

/// 去重配置
#[derive(Debug, Clone)]
pub struct DeduplicationConfig {
    /// 去重策略
    pub strategy: DeduplicationStrategy,
    /// 标题相似度阈值 (0.0-1.0)
    pub title_similarity_threshold: f32,
    /// 内容相似度阈值 (0.0-1.0)
    pub content_similarity_threshold: f32,
    /// 内容指纹配置
    pub fingerprint_config: ContentFingerprintConfig,
    /// 是否区分大小写
    pub case_sensitive: bool,
    /// 是否忽略查询参数
    pub ignore_query_params: bool,
    /// 是否忽略片段标识符
    pub ignore_fragments: bool,
}

impl Default for DeduplicationConfig {
    fn default() -> Self {
        Self {
            strategy: DeduplicationStrategy::Smart,
            title_similarity_threshold: 0.85,
            content_similarity_threshold: 0.8,
            fingerprint_config: ContentFingerprintConfig::default(),
            case_sensitive: false,
            ignore_query_params: true,
            ignore_fragments: true,
        }
    }
}

/// 结果去重器
///
/// 使用 SimHash + 海明距离检测相似标题。
///
/// # 复杂度
///
/// - URL/标题精确匹配:O(1)(HashSet 查找)
/// - SimHash 相似度检测:O(n) 每次查找,n = unique fingerprints 数量
/// - 整体去重:O(n²)(每个结果都要遍历所有已见指纹)
///
/// 当结果集规模较大(> 10k)时,建议通过 `DeduplicationConfig`
/// 关闭 `fingerprint_config.enabled` 或使用 `UrlAndTitle`/`UrlOnly` 策略
/// 退化到 O(n)。
pub struct ResultDeduplicator {
    config: DeduplicationConfig,
    seen_urls: HashSet<String>,
    seen_titles: HashSet<String>,
    seen_fingerprints: HashSet<u64>,
}

impl ResultDeduplicator {
    /// 创建新的去重器
    pub fn new(config: DeduplicationConfig) -> Self {
        Self {
            config,
            seen_urls: HashSet::new(),
            seen_titles: HashSet::new(),
            seen_fingerprints: HashSet::new(),
        }
    }

    /// 使用默认配置创建去重器
    pub fn with_default_config() -> Self {
        Self::new(DeduplicationConfig::default())
    }

    /// 处理URL,应用清理规则
    fn normalize_url(&self, url: &str) -> String {
        let mut normalized = url.to_string();

        // 移除片段标识符
        if self.config.ignore_fragments {
            if let Some(pos) = normalized.rfind('#') {
                normalized.truncate(pos);
            }
        }

        // 移除查询参数。
        // 豁免:百度 /link 中转 URL 的真实 URL 编码在 query 里,剥除后所有
        // 结果坍缩为同一 key(每查询最多存活 1 条百度结果)。保留 query 使
        // 各中转链接互异,跨引擎同内容交给标题 SimHash 去重兜底。
        let is_baidu_link = normalized.contains("baidu.com/link");
        if self.config.ignore_query_params && !is_baidu_link {
            if let Some(pos) = normalized.rfind('?') {
                normalized.truncate(pos);
            }
        }

        // 转换为小写(如果不区分大小写)
        if !self.config.case_sensitive {
            normalized = normalized.to_lowercase();
        }

        // 移除末尾的斜杠
        normalized = normalized.trim_end_matches('/').to_string();

        normalized
    }

    /// 处理标题,应用清理规则
    fn normalize_title(&self, title: &str) -> String {
        let mut normalized = title.to_string();

        // 移除多余的空白字符
        normalized = normalized.split_whitespace().collect::<Vec<_>>().join(" ");

        // 转换为小写(如果不区分大小写)
        if !self.config.case_sensitive {
            normalized = normalized.to_lowercase();
        }

        normalized
    }

    /// 生成内容指纹
    fn generate_fingerprint(&self, content: &str) -> u64 {
        match self.config.fingerprint_config.algorithm {
            FingerprintAlgorithm::Hash => {
                let mut hasher = DefaultHasher::new();
                content.hash(&mut hasher);
                hasher.finish()
            }
            FingerprintAlgorithm::SimHash => {
                // 简化的SimHash实现
                self.simhash(content)
            }
        }
    }

    /// 简化的SimHash实现
    fn simhash(&self, content: &str) -> u64 {
        let words: Vec<&str> = content.split_whitespace().collect();
        let mut hash_bits = vec![0i32; self.config.fingerprint_config.fingerprint_size];

        for word in words {
            let mut hasher = DefaultHasher::new();
            word.hash(&mut hasher);
            let word_hash = hasher.finish();

            for (i, bit) in hash_bits
                .iter_mut()
                .enumerate()
                .take(self.config.fingerprint_config.fingerprint_size)
            {
                if (word_hash >> (i % 64)) & 1 == 1 {
                    *bit += 1;
                } else {
                    *bit -= 1;
                }
            }
        }

        let mut fingerprint = 0u64;
        for (i, &bit) in hash_bits
            .iter()
            .enumerate()
            .take(self.config.fingerprint_config.fingerprint_size.min(64))
        {
            if bit > 0 {
                fingerprint |= 1 << i;
            }
        }

        fingerprint
    }

    /// 计算海明距离(两个64位指纹之间的不同位数)
    #[inline]
    fn hamming_distance(hash1: u64, hash2: u64) -> u8 {
        let xor = hash1 ^ hash2;
        xor.count_ones() as u8
    }

    /// 使用 SimHash 检测相似性
    ///
    /// 先检查精确匹配(O(1)),未命中则遍历已见指纹计算海明距离(O(n),n = 已见指纹数)。
    /// 整体复杂度随结果集增长呈 O(n²)。
    #[inline]
    fn is_similar_by_fingerprint(&self, fingerprint: u64) -> bool {
        // 检查精确匹配(O(1))
        if self.seen_fingerprints.contains(&fingerprint) {
            return true;
        }

        // SimHash 海明距离检测(O(n),n = 已见指纹数)
        for &existing_fingerprint in self.seen_fingerprints.iter() {
            let distance = Self::hamming_distance(fingerprint, existing_fingerprint);
            if distance <= self.config.fingerprint_config.simhash_threshold {
                return true;
            }
        }

        false
    }

    /// 过滤重复结果
    ///
    /// 根据配置的 `strategy` 进行 URL/标题精确匹配(O(1))或
    /// SimHash 相似度检测(整体 O(n²))。
    pub fn deduplicate(&mut self, results: Vec<SearchResult>) -> Vec<SearchResult> {
        let mut unique_results = Vec::new();

        // 预分配 HashSet 容量以减少 rehash
        let expected = results.len().min(1000);
        self.seen_urls.reserve(expected);
        self.seen_titles.reserve(expected);
        self.seen_fingerprints.reserve(expected);

        for result in results {
            let normalized_url = self.normalize_url(&result.url);
            let normalized_title = self.normalize_title(&result.title);

            if self.is_duplicate(&normalized_url, &normalized_title) {
                continue;
            }

            self.remember_unique(&normalized_url, &normalized_title);
            unique_results.push(result);
        }

        unique_results
    }

    /// 按配置策略判断规范化后的 URL/标题是否重复
    fn is_duplicate(&self, normalized_url: &str, normalized_title: &str) -> bool {
        // 使用 HashSet 进行快速去重检测
        let url_exists = self.seen_urls.contains(normalized_url);
        let title_exists = self.seen_titles.contains(normalized_title);

        // 根据策略判断是否重复
        match self.config.strategy {
            DeduplicationStrategy::UrlOnly => url_exists,
            DeduplicationStrategy::TitleOnly => title_exists,
            DeduplicationStrategy::UrlAndTitle => {
                // 语义:URL 或标题任一精确匹配即视为重复
                // 不使用 fingerprint(与 Smart 策略区分)
                url_exists || title_exists
            }
            DeduplicationStrategy::Smart => {
                // URL 完全匹配
                url_exists
                    // 标题完全匹配
                    || title_exists
                    // 使用 SimHash 检测相似标题(O(n²),n = unique fingerprints)
                    || (self.config.fingerprint_config.enabled
                        && self.is_similar_by_fingerprint(self.generate_fingerprint(normalized_title)))
            }
        }
    }

    /// 记录已见 URL/标题;Smart 策略额外记录标题指纹
    fn remember_unique(&mut self, normalized_url: &str, normalized_title: &str) {
        self.seen_urls.insert(normalized_url.to_string());
        self.seen_titles.insert(normalized_title.to_string());

        // 仅在 Smart 策略下记录 fingerprint(其他策略从不读取 seen_fingerprints)
        // 避免在 UrlOnly/TitleOnly/UrlAndTitle 策略下的死写入(修复)
        if matches!(self.config.strategy, DeduplicationStrategy::Smart)
            && self.config.fingerprint_config.enabled
        {
            let fingerprint = self.generate_fingerprint(normalized_title);
            self.seen_fingerprints.insert(fingerprint);
        }
    }

    /// 批量去重多个引擎的结果
    pub fn deduplicate_multi_engine(
        &mut self,
        engine_results: Vec<(String, Vec<SearchResult>)>,
    ) -> Vec<SearchResult> {
        let mut all_results = Vec::new();

        // 合并所有结果
        for (engine_name, results) in engine_results {
            for mut result in results {
                result.engine = engine_name.clone();
                all_results.push(result);
            }
        }

        // 去重
        self.deduplicate(all_results)
    }

    /// 重置去重器状态
    pub fn reset(&mut self) {
        self.seen_urls.clear();
        self.seen_titles.clear();
        self.seen_fingerprints.clear();
    }

    /// 获取去重统计信息
    pub fn get_stats(&self) -> DeduplicationStats {
        DeduplicationStats {
            seen_urls_count: self.seen_urls.len(),
            seen_titles_count: self.seen_titles.len(),
            seen_fingerprints_count: self.seen_fingerprints.len(),
        }
    }
}

/// 去重统计信息
#[derive(Debug, Clone)]
pub struct DeduplicationStats {
    pub seen_urls_count: usize,
    pub seen_titles_count: usize,
    pub seen_fingerprints_count: usize,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::domain::models::search_result::SearchResult;

    fn create_test_result(url: &str, title: &str, description: Option<&str>) -> SearchResult {
        SearchResult {
            title: title.to_string(),
            url: url.to_string(),
            description: description.map(|d| d.to_string()),
            engine: "test".to_string(),
            score: 0.0,
            published_time: None,
        }
    }

    #[test]
    fn test_url_deduplication() {
        let mut dedup = ResultDeduplicator::with_default_config();
        dedup.config.strategy = DeduplicationStrategy::UrlOnly;

        let results = vec![
            create_test_result("https://example.com/page1", "Title 1", None),
            create_test_result("https://example.com/page1", "Title 2", None), // 相同URL
            create_test_result("https://example.com/page2", "Title 3", None),
        ];

        let deduplicated = dedup.deduplicate(results);
        assert_eq!(deduplicated.len(), 2);
        assert_eq!(deduplicated[0].title, "Title 1");
        assert_eq!(deduplicated[1].title, "Title 3");
    }

    #[test]
    fn test_title_deduplication() {
        let mut dedup = ResultDeduplicator::with_default_config();
        dedup.config.strategy = DeduplicationStrategy::TitleOnly;
        dedup.config.title_similarity_threshold = 0.9;

        let results = vec![
            create_test_result("https://example.com/page1", "Rust Programming Guide", None),
            create_test_result("https://example.com/page2", "Rust Programming Guide", None), // 相同标题
            create_test_result(
                "https://example.com/page3",
                "Python Programming Guide",
                None,
            ),
        ];

        let deduplicated = dedup.deduplicate(results);
        assert_eq!(deduplicated.len(), 2);
        assert_eq!(deduplicated[0].title, "Rust Programming Guide");
        assert_eq!(deduplicated[1].title, "Python Programming Guide");
    }

    #[test]
    fn test_smart_deduplication() {
        let mut dedup = ResultDeduplicator::with_default_config();
        dedup.config.strategy = DeduplicationStrategy::Smart;
        dedup.config.title_similarity_threshold = 0.9;

        let results = vec![
            create_test_result(
                "https://example.com/page1",
                "Rust Programming Guide",
                Some("Learn Rust programming"),
            ),
            create_test_result(
                "https://example.com/page2",
                "Rust Programming Guide",
                Some("Learn Rust programming language"),
            ), // 完全相同的标题
            create_test_result(
                "https://example.com/page3",
                "Python Programming Guide",
                Some("Learn Python programming"),
            ),
        ];

        let deduplicated = dedup.deduplicate(results);
        assert_eq!(deduplicated.len(), 2);
    }

    #[test]
    fn test_url_normalization() {
        let dedup = ResultDeduplicator::with_default_config();

        assert_eq!(
            dedup.normalize_url("https://example.com/path?param=value#fragment"),
            "https://example.com/path"
        );
        assert_eq!(
            dedup.normalize_url("https://EXAMPLE.com/PATH/"),
            "https://example.com/path"
        );
    }

    // normalize_url 补充测试

    #[test]
    fn test_normalize_url_empty_string() {
        // 边界情况:空字符串返回空字符串
        let dedup = ResultDeduplicator::with_default_config();
        assert_eq!(dedup.normalize_url(""), "");
    }

    #[test]
    fn test_normalize_url_only_fragment() {
        // 测试仅包含片段标识符的 URL 被清空
        let dedup = ResultDeduplicator::with_default_config();
        assert_eq!(
            dedup.normalize_url("https://example.com#section"),
            "https://example.com"
        );
    }

    #[test]
    fn test_normalize_url_only_query() {
        // 测试仅包含查询参数的 URL 被移除查询部分
        let dedup = ResultDeduplicator::with_default_config();
        assert_eq!(
            dedup.normalize_url("https://example.com?a=1&b=2"),
            "https://example.com"
        );
    }

    #[test]
    fn test_normalize_url_case_sensitive_config() {
        // 测试区分大小写配置保留原始大小写
        let config = DeduplicationConfig {
            case_sensitive: true,
            ..DeduplicationConfig::default()
        };
        let dedup = ResultDeduplicator::new(config);
        assert_eq!(
            dedup.normalize_url("https://EXAMPLE.com/PATH/"),
            "https://EXAMPLE.com/PATH"
        );
    }

    #[test]
    fn test_normalize_url_keep_query_when_disabled() {
        // 测试禁用查询参数忽略时保留查询字符串和片段
        let config = DeduplicationConfig {
            ignore_query_params: false,
            ignore_fragments: false,
            ..DeduplicationConfig::default()
        };
        let dedup = ResultDeduplicator::new(config);
        assert_eq!(
            dedup.normalize_url("https://example.com/path?a=1#frag"),
            "https://example.com/path?a=1#frag"
        );
    }

    // normalize_title 测试

    #[test]
    fn test_normalize_title_whitespace_collapsed() {
        // 测试多余空白字符被压缩为单个空格
        let dedup = ResultDeduplicator::with_default_config();
        assert_eq!(
            dedup.normalize_title("Rust    Programming   Guide"),
            "rust programming guide"
        );
    }

    #[test]
    fn test_normalize_title_leading_trailing_whitespace_trimmed() {
        // 测试首尾空白被移除
        let dedup = ResultDeduplicator::with_default_config();
        assert_eq!(dedup.normalize_title("  Rust Guide  "), "rust guide");
    }

    #[test]
    fn test_normalize_title_case_sensitive_config() {
        // 测试区分大小写配置保留原始大小写
        let config = DeduplicationConfig {
            case_sensitive: true,
            ..DeduplicationConfig::default()
        };
        let dedup = ResultDeduplicator::new(config);
        assert_eq!(
            dedup.normalize_title("Rust Programming Guide"),
            "Rust Programming Guide"
        );
    }

    #[test]
    fn test_normalize_title_empty_string() {
        // 边界情况:空字符串返回空字符串
        let dedup = ResultDeduplicator::with_default_config();
        assert_eq!(dedup.normalize_title(""), "");
    }

    // generate_fingerprint 测试

    #[test]
    fn test_generate_fingerprint_deterministic() {
        // 测试相同内容产生相同指纹
        let dedup = ResultDeduplicator::with_default_config();
        let fp1 = dedup.generate_fingerprint("rust programming language");
        let fp2 = dedup.generate_fingerprint("rust programming language");
        assert_eq!(fp1, fp2, "same content should produce same fingerprint");
    }

    #[test]
    fn test_generate_fingerprint_different_content() {
        // 测试不同内容产生不同指纹
        let dedup = ResultDeduplicator::with_default_config();
        let fp1 = dedup.generate_fingerprint("rust programming language");
        let fp2 = dedup.generate_fingerprint("python scripting language");
        assert_ne!(
            fp1, fp2,
            "different content should produce different fingerprint"
        );
    }

    #[test]
    fn test_generate_fingerprint_empty_content() {
        // 边界情况:空内容不 panic 且返回确定值
        let dedup = ResultDeduplicator::with_default_config();
        let fp = dedup.generate_fingerprint("");
        // 空内容应产生确定的指纹(全 0 或某固定值)
        let fp2 = dedup.generate_fingerprint("");
        assert_eq!(fp, fp2, "empty content should be deterministic");
    }

    #[test]
    fn test_generate_fingerprint_hash_algorithm() {
        // 测试 Hash 算法模式
        let config = DeduplicationConfig {
            fingerprint_config: ContentFingerprintConfig {
                algorithm: FingerprintAlgorithm::Hash,
                ..ContentFingerprintConfig::default()
            },
            ..DeduplicationConfig::default()
        };
        let dedup = ResultDeduplicator::new(config);
        let fp1 = dedup.generate_fingerprint("test content");
        let fp2 = dedup.generate_fingerprint("test content");
        assert_eq!(fp1, fp2, "Hash algorithm should be deterministic");
    }

    // hamming_distance 测试

    #[test]
    fn test_hamming_distance_identical_hashes() {
        // 测试相同哈希的海明距离为 0
        let hash = 0b1010_1010u64;
        assert_eq!(ResultDeduplicator::hamming_distance(hash, hash), 0);
    }

    #[test]
    fn test_hamming_distance_one_bit_difference() {
        // 测试相差一位的海明距离为 1
        let hash1 = 0b1000u64;
        let hash2 = 0b1001u64;
        assert_eq!(ResultDeduplicator::hamming_distance(hash1, hash2), 1);
    }

    #[test]
    fn test_hamming_distance_all_bits_different() {
        // 测试所有位都不同的海明距离为 64
        assert_eq!(ResultDeduplicator::hamming_distance(0u64, u64::MAX), 64);
    }

    // deduplicate 边界情况

    #[test]
    fn test_deduplicate_empty_input() {
        // 边界情况:空输入返回空输出
        let mut dedup = ResultDeduplicator::with_default_config();
        let results: Vec<SearchResult> = vec![];
        let deduplicated = dedup.deduplicate(results);
        assert!(deduplicated.is_empty());
    }

    #[test]
    fn test_deduplicate_single_result_preserved() {
        // 边界情况:单个结果保留
        let mut dedup = ResultDeduplicator::with_default_config();
        let results = vec![create_test_result("https://example.com", "Title", None)];
        let deduplicated = dedup.deduplicate(results);
        assert_eq!(deduplicated.len(), 1);
    }

    #[test]
    fn test_deduplicate_all_duplicates_keeps_one() {
        // 边界情况:全部重复时只保留一个
        let mut dedup = ResultDeduplicator::with_default_config();
        let results = vec![
            create_test_result("https://example.com", "Same Title", None),
            create_test_result("https://example.com", "Same Title", None),
            create_test_result("https://example.com", "Same Title", None),
        ];
        let deduplicated = dedup.deduplicate(results);
        assert_eq!(deduplicated.len(), 1);
    }

    // reset 测试

    #[test]
    fn test_reset_clears_all_state() {
        // 测试 reset 清空所有已见集合,使之前重复的结果不再被视为重复
        let mut dedup = ResultDeduplicator::with_default_config();
        let results = vec![
            create_test_result("https://example.com", "Title 1", None),
            create_test_result("https://example.com", "Title 1", None),
        ];

        let first_pass = dedup.deduplicate(results.clone());
        assert_eq!(first_pass.len(), 1);

        // reset 后同样的结果应再次通过
        dedup.reset();
        let stats = dedup.get_stats();
        assert_eq!(stats.seen_urls_count, 0);
        assert_eq!(stats.seen_titles_count, 0);
        assert_eq!(stats.seen_fingerprints_count, 0);

        let second_pass = dedup.deduplicate(results);
        assert_eq!(
            second_pass.len(),
            1,
            "after reset, first result should pass again"
        );
    }

    // get_stats 测试

    #[test]
    fn test_get_stats_after_deduplication() {
        // 测试去重后统计数据正确反映已见集合大小
        let mut dedup = ResultDeduplicator::with_default_config();
        let results = vec![
            create_test_result("https://example.com/1", "Title 1", None),
            create_test_result("https://example.com/2", "Title 2", None),
            create_test_result("https://example.com/1", "Title 1", None), // 重复
        ];

        dedup.deduplicate(results);
        let stats = dedup.get_stats();
        assert_eq!(stats.seen_urls_count, 2, "should have 2 unique URLs");
        assert_eq!(stats.seen_titles_count, 2, "should have 2 unique titles");
    }

    // deduplicate_multi_engine 测试

    #[test]
    fn test_deduplicate_multi_engine_merges_and_deduplicates() {
        // 测试多引擎结果合并后去重,且引擎名被正确设置
        let mut dedup = ResultDeduplicator::with_default_config();
        let engine_results = vec![
            (
                "google".to_string(),
                vec![
                    create_test_result("https://example.com/1", "Rust Guide", None),
                    create_test_result("https://example.com/2", "Go Guide", None),
                ],
            ),
            (
                "bing".to_string(),
                vec![
                    create_test_result("https://example.com/1", "Rust Guide", None), // 跨引擎重复
                    create_test_result("https://example.com/3", "Python Guide", None),
                ],
            ),
        ];

        let deduplicated = dedup.deduplicate_multi_engine(engine_results);
        assert_eq!(
            deduplicated.len(),
            3,
            "should have 3 unique results after cross-engine dedup"
        );
        assert_eq!(deduplicated[0].engine, "google");
        assert_eq!(deduplicated[2].engine, "bing");
    }

    // 策略组合测试

    #[test]
    fn test_url_and_title_strategy() {
        // 测试 UrlAndTitle 策略:URL 或标题任一匹配即视为重复
        let mut dedup = ResultDeduplicator::with_default_config();
        dedup.config.strategy = DeduplicationStrategy::UrlAndTitle;

        let results = vec![
            create_test_result("https://example.com/1", "Title A", None),
            create_test_result("https://example.com/2", "Title A", None), // 标题相同
            create_test_result("https://example.com/3", "Title C", None),
        ];

        let deduplicated = dedup.deduplicate(results);
        assert_eq!(
            deduplicated.len(),
            2,
            "same title should trigger dedup in UrlAndTitle strategy"
        );
    }

    // is_similar_by_fingerprint: hamming distance 路径

    #[test]
    fn test_smart_deduplication_similar_by_hamming_distance() {
        // 设置 simhash_threshold=64 使任意两个不同指纹的海明距离都 <= threshold
        // 从而触发 is_similar_by_fingerprint 中的 hamming distance 检测路径(非精确匹配)
        let mut dedup = ResultDeduplicator::with_default_config();
        dedup.config.strategy = DeduplicationStrategy::Smart;
        dedup.config.fingerprint_config.simhash_threshold = 64;

        let results = vec![
            create_test_result("https://example.com/1", "Rust Programming Guide", None),
            create_test_result("https://example.com/2", "Completely Different Topic", None),
        ];

        let deduplicated = dedup.deduplicate(results);
        // 第二个结果应被 hamming distance 检测为相似而被去重
        assert_eq!(
            deduplicated.len(),
            1,
            "hamming distance path should detect similarity"
        );
    }

    #[test]
    fn test_url_and_title_strategy_does_not_use_fingerprint() {
        // UrlAndTitle 策略仅做精确匹配,不使用 fingerprint 检测相似性
        // 即使 simhash_threshold=64,不同标题也不应被去重
        let mut dedup = ResultDeduplicator::with_default_config();
        dedup.config.strategy = DeduplicationStrategy::UrlAndTitle;
        dedup.config.fingerprint_config.simhash_threshold = 64;

        let results = vec![
            create_test_result("https://example.com/1", "Rust Guide", None),
            create_test_result("https://example.com/2", "Python Tutorial", None),
        ];

        let deduplicated = dedup.deduplicate(results);
        assert_eq!(
            deduplicated.len(),
            2,
            "UrlAndTitle should NOT use hamming distance (only exact URL/title match)"
        );
    }

    // HTTP vs HTTPS and www normalization tests

    #[test]
    fn test_normalize_url_strips_trailing_slash() {
        let dedup = ResultDeduplicator::with_default_config();
        assert_eq!(
            dedup.normalize_url("https://example.com/path/"),
            "https://example.com/path"
        );
    }

    #[test]
    fn test_deduplicate_same_url_different_schemes_kept_separate() {
        // URL normalization does NOT strip scheme (http vs https are different)
        // This is intentional — http and https may serve different content
        let mut dedup = ResultDeduplicator::with_default_config();
        dedup.config.strategy = DeduplicationStrategy::UrlOnly;

        let results = vec![
            create_test_result("http://example.com/page", "Title HTTP", None),
            create_test_result("https://example.com/page", "Title HTTPS", None),
        ];

        let deduplicated = dedup.deduplicate(results);
        // Both are kept because scheme is part of the normalized URL
        assert_eq!(deduplicated.len(), 2);
    }

    #[test]
    fn test_deduplicate_www_vs_non_www_kept_separate() {
        // www and non-www are treated as different hosts by normalization
        let mut dedup = ResultDeduplicator::with_default_config();
        dedup.config.strategy = DeduplicationStrategy::UrlOnly;

        let results = vec![
            create_test_result("https://www.example.com/page", "Title WWW", None),
            create_test_result("https://example.com/page", "Title No WWW", None),
        ];

        let deduplicated = dedup.deduplicate(results);
        assert_eq!(deduplicated.len(), 2);
    }

    #[test]
    fn test_deduplicate_tracking_params_removed() {
        // Query params are removed by default normalization
        let mut dedup = ResultDeduplicator::with_default_config();
        dedup.config.strategy = DeduplicationStrategy::UrlOnly;

        let results = vec![
            create_test_result(
                "https://example.com/page?utm_source=google",
                "Title 1",
                None,
            ),
            create_test_result("https://example.com/page?utm_source=bing", "Title 2", None),
        ];

        let deduplicated = dedup.deduplicate(results);
        // Both normalize to "https://example.com/page" → deduped to 1
        assert_eq!(deduplicated.len(), 1);
    }

    #[test]
    fn test_deduplicate_fragment_differences_removed() {
        let mut dedup = ResultDeduplicator::with_default_config();
        dedup.config.strategy = DeduplicationStrategy::UrlOnly;

        let results = vec![
            create_test_result("https://example.com/page#section1", "Title 1", None),
            create_test_result("https://example.com/page#section2", "Title 2", None),
        ];

        let deduplicated = dedup.deduplicate(results);
        assert_eq!(deduplicated.len(), 1);
    }

    #[test]
    fn test_deduplicate_case_insensitive_url() {
        let mut dedup = ResultDeduplicator::with_default_config();
        dedup.config.strategy = DeduplicationStrategy::UrlOnly;

        let results = vec![
            create_test_result("https://EXAMPLE.com/Page", "Title Upper", None),
            create_test_result("https://example.com/page", "Title Lower", None),
        ];

        let deduplicated = dedup.deduplicate(results);
        assert_eq!(
            deduplicated.len(),
            1,
            "URLs should match case-insensitively"
        );
    }

    // r2 复查:baidu /link 归一化豁免

    /// 百度中转链接的真实 URL 编码在 query 里——剥除 query 会让全部结果
    /// 坍缩为同一 key(每查询最多存活 1 条)。豁免后各中转链接互异,
    /// 跨引擎同内容由标题 SimHash 兜底。
    #[test]
    fn test_baidu_link_urls_not_collapsed_by_query_strip() {
        let mut d = ResultDeduplicator::with_default_config();
        let merged = vec![
            SearchResult {
                title: "Result A".to_string(),
                url: "https://www.baidu.com/link?url=aaa111".to_string(),
                description: None,
                engine: "baidu".to_string(),
                score: 0.9,
                published_time: None,
            },
            SearchResult {
                title: "Result B".to_string(),
                url: "https://www.baidu.com/link?url=bbb222".to_string(),
                description: None,
                engine: "baidu".to_string(),
                score: 0.8,
                published_time: None,
            },
        ];
        let out = d.deduplicate(merged);
        assert_eq!(
            out.len(),
            2,
            "distinct baidu /link redirect URLs must not collapse into one"
        );
    }
}