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
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
// Copyright (c) 2025-2026 Kirky.X🌠
// SPDX-License-Identifier: Apache-2.0

use crate::config::SearchSettings;
use crate::domain::services::searxng::{ReqwestSearxngTransport, SearxngInstanceService};
use crate::engines::engine_client::EngineClient;
use std::sync::Arc;
use std::time::Duration;

use super::{
    engine_trait::{SearchEngine, SearchRequest},
    error::SearchError,
    response::{Response, ResponseItem},
    types::SearchEngineType,
};

pub mod baidu;
pub mod bing;
pub mod exa;
pub mod html_parser;
pub mod searxng;
pub mod shared_utils;
pub mod sogou;
pub mod tavily;

pub use baidu::BaiduSearchEngine;
pub use bing::BingSearchEngine;
pub use exa::{ExaConfig, ExaSearchEngine};
pub use searxng::SearxngSearchEngine;
pub use shared_utils::{parse_first_selector, safe_parse_selector};
pub use sogou::SogouSearchEngine;
pub use tavily::{TavilyConfig, TavilySearchEngine};

/// Trait for SearchClient - enables dependency injection
#[async_trait::async_trait]
pub trait SearchClientTrait: Send + Sync {
    /// Search with default engine
    async fn search(&self, query: &str) -> SearchCommand;

    /// Search with specific engine
    async fn search_with_engine(
        &self,
        query: &str,
        engine: SearchEngineType,
    ) -> Result<Response<ResponseItem>, SearchError>;

    /// Get the default engine type
    fn default_engine(&self) -> SearchEngineType;
}

#[derive(Clone)]
struct SearchClientInner {
    engines: Vec<Arc<dyn SearchEngine>>,
    default_engine: SearchEngineType,
}

fn default_engine_type() -> SearchEngineType {
    SearchEngineType::Bing
}

/// 搜索客户端
#[derive(Clone)]
pub struct SearchClient {
    inner: Arc<SearchClientInner>,
}

impl SearchClient {
    /// Create a new SearchClient
    pub fn new(engine_client: Arc<EngineClient>) -> Self {
        let mut inner = SearchClientInner {
            engines: Vec::new(),
            default_engine: default_engine_type(),
        };

        Self::register_default_engines(&mut inner, &engine_client);

        SearchClient {
            inner: Arc::new(inner),
        }
    }

    /// Register the built-in scraping-backed engines (bing/baidu/sogou).
    fn register_default_engines(inner: &mut SearchClientInner, engine_client: &Arc<EngineClient>) {
        inner
            .engines
            .push(Arc::new(BingSearchEngine::new(engine_client.clone())) as Arc<dyn SearchEngine>);
        inner
            .engines
            .push(Arc::new(BaiduSearchEngine::new(engine_client.clone())) as Arc<dyn SearchEngine>);
        inner
            .engines
            .push(Arc::new(SogouSearchEngine::new(engine_client.clone())) as Arc<dyn SearchEngine>);
    }

    /// Create a SearchClient with engines assembled from [`SearchSettings`].
    ///
    /// 始终注册内置引擎(bing/baidu/sogou);API 引擎(exa/tavily)仅在配置了
    /// 非空 `api_key` 时注册:
    ///
    /// - Exa: `search.exa.api_key`(env: `CRAWLRS__SEARCH__EXA__API_KEY`)
    /// - Tavily: `search.tavily.api_key`(env: `CRAWLRS__SEARCH__TAVILY__API_KEY`)
    ///
    /// SearXNG 仅在 `search.searxng.enabled == true` **且**实例生命周期服务存在时注册
    /// (两条件任一不满足即跳过,显式 `engine="searxng"` 得到 `NoEngineAvailable`)。
    ///
    /// 未配置凭据不是错误——跳过注册并输出 info 日志;此后显式请求
    /// `engine="exa"` / `engine="tavily"` 会得到 `SearchError::NoEngineAvailable`。
    pub fn with_configured_engines(
        engine_client: Arc<EngineClient>,
        http_client: Arc<reqwest::Client>,
        settings: &SearchSettings,
        searxng_instances: Option<Arc<dyn SearxngInstanceService>>,
    ) -> Self {
        let mut inner = SearchClientInner {
            engines: Vec::new(),
            default_engine: default_engine_type(),
        };

        Self::register_builtin_engines(&mut inner, &engine_client, &settings.engines);
        Self::register_exa_engine(&mut inner, &http_client, settings);
        Self::register_tavily_engine(&mut inner, &http_client, settings);
        Self::register_searxng_engine(&mut inner, &http_client, settings, searxng_instances);

        inner.default_engine =
            Self::resolve_default_engine(&inner.engines, settings.default_engine.as_deref());

        SearchClient {
            inner: Arc::new(inner),
        }
    }

    /// 按 `search.exa.api_key` 注册 Exa 引擎(空 key 跳过并记录 info)。
    fn register_exa_engine(
        inner: &mut SearchClientInner,
        http_client: &Arc<reqwest::Client>,
        settings: &SearchSettings,
    ) {
        match settings.exa.api_key().filter(|key| !key.trim().is_empty()) {
            Some(api_key) => {
                let mut config = ExaConfig {
                    api_key: api_key.to_string(),
                    ..ExaConfig::default()
                };
                if let Some(base_url) = settings.exa.base_url().filter(|url| !url.trim().is_empty())
                {
                    config.endpoint = base_url.to_string();
                }
                inner.engines.push(Arc::new(ExaSearchEngine::new(
                    http_client.as_ref().clone(),
                    config,
                )) as Arc<dyn SearchEngine>);
                log::info!("{}", crate::i18n::tr_log("search-exa-registered"));
            }
            None => log::info!("{}", crate::i18n::tr_log("search-exa-skipped")),
        }
    }

    /// 按 `search.tavily.api_key` 注册 Tavily 引擎(空 key 跳过并记录 info)。
    fn register_tavily_engine(
        inner: &mut SearchClientInner,
        http_client: &Arc<reqwest::Client>,
        settings: &SearchSettings,
    ) {
        match settings
            .tavily
            .api_key()
            .filter(|key| !key.trim().is_empty())
        {
            Some(api_key) => {
                let mut config = TavilyConfig {
                    api_key: api_key.to_string(),
                    ..TavilyConfig::default()
                };
                if let Some(base_url) = settings
                    .tavily
                    .base_url()
                    .filter(|url| !url.trim().is_empty())
                {
                    config.endpoint = base_url.to_string();
                }
                inner.engines.push(Arc::new(TavilySearchEngine::new(
                    http_client.as_ref().clone(),
                    config,
                )) as Arc<dyn SearchEngine>);
                log::info!("{}", crate::i18n::tr_log("search-tavily-registered"));
            }
            None => log::info!("{}", crate::i18n::tr_log("search-tavily-skipped")),
        }
    }

    /// SearXNG:enabled && 实例服务存在时才注册(否则单引擎路径显性 NoEngineAvailable)。
    fn register_searxng_engine(
        inner: &mut SearchClientInner,
        http_client: &Arc<reqwest::Client>,
        settings: &SearchSettings,
        searxng_instances: Option<Arc<dyn SearxngInstanceService>>,
    ) {
        match (settings.searxng.enabled, searxng_instances) {
            (true, Some(service)) => {
                let transport: Arc<dyn crate::domain::services::searxng::SearxngTransport> =
                    Arc::new(ReqwestSearxngTransport::new(
                        http_client.clone(),
                        settings.searxng.user_agent.clone(),
                    ));
                inner.engines.push(Arc::new(SearxngSearchEngine::new(
                    service,
                    transport,
                    Duration::from_secs(settings.timeout_seconds),
                    settings.searxng.max_failover_attempts,
                )) as Arc<dyn SearchEngine>);
                log::info!(
                    "SearXNG search engine registered (pool_target={})",
                    settings.searxng.pool_target
                );
            }
            (true, None) => {
                log::warn!(
                    "search.searxng.enabled=true but instance service is absent; \
                     SearXNG engine not registered"
                );
            }
            (false, _) => {
                log::info!("SearXNG search engine skipped (search.searxng.enabled=false)");
            }
        }
    }

    /// 按 `SearchEnginesSettings` 开关注册内置引擎(smart 聚合与单引擎路径共用此注册集)。
    ///
    /// 关闭的引擎跳过注册并输出 info 日志;全部关闭时输出 warn(此后
    /// smart 聚合无引擎可用、单引擎路径显性报 `NoEngineAvailable`)。
    fn register_builtin_engines(
        inner: &mut SearchClientInner,
        engine_client: &Arc<EngineClient>,
        switches: &crate::config::SearchEnginesSettings,
    ) {
        type BuiltinEngineFactory = fn(&Arc<EngineClient>) -> Arc<dyn SearchEngine>;
        let wanted: &[(&str, bool, BuiltinEngineFactory)] = &[
            ("bing", switches.bing_enabled, |c| {
                Arc::new(BingSearchEngine::new(c.clone())) as Arc<dyn SearchEngine>
            }),
            ("baidu", switches.baidu_enabled, |c| {
                Arc::new(BaiduSearchEngine::new(c.clone())) as Arc<dyn SearchEngine>
            }),
            ("sogou", switches.sogou_enabled, |c| {
                Arc::new(SogouSearchEngine::new(c.clone())) as Arc<dyn SearchEngine>
            }),
        ];
        for (name, enabled, build) in wanted {
            if *enabled {
                inner.engines.push(build(engine_client));
            } else {
                log::info!(
                    "{}",
                    crate::i18n::tr_log_args(
                        "search-engine-disabled-by-config",
                        &[("engine", (*name).to_string())],
                    )
                );
            }
        }
        if inner.engines.is_empty() {
            log::warn!(
                "{}",
                crate::i18n::tr_log("search-all-builtin-engines-disabled")
            );
        }
    }

    /// 解析配置的默认引擎:合法且已注册则采用,否则回退 bing 并输出 warn。
    fn resolve_default_engine(
        engines: &[Arc<dyn SearchEngine>],
        configured: Option<&str>,
    ) -> SearchEngineType {
        let Some(name) = configured.map(str::trim).filter(|s| !s.is_empty()) else {
            return default_engine_type();
        };
        match SearchEngineType::from_name(name) {
            Some(engine_type) if engines.iter().any(|e| e.engine_type() == engine_type) => {
                engine_type
            }
            Some(_) => {
                log::warn!(
                    "{}",
                    crate::i18n::tr_log_args(
                        "search-default-engine-not-registered",
                        &[("engine", name.to_string())],
                    )
                );
                default_engine_type()
            }
            None => {
                log::warn!(
                    "{}",
                    crate::i18n::tr_log_args(
                        "search-default-engine-unknown",
                        &[("engine", name.to_string())],
                    )
                );
                default_engine_type()
            }
        }
    }

    pub fn register_engine(&mut self, engine: Arc<dyn SearchEngine>) {
        Arc::make_mut(&mut self.inner).engines.push(engine);
    }

    /// Create a SearchClient with a custom set of engines.
    ///
    /// Enables test injection of mock engines and production scenarios that
    /// need a curated engine subset. The caller is responsible for providing
    /// at least one engine; an empty slice yields a client whose `search()`
    /// always fails with `SearchError::NoEngineAvailable`.
    pub fn new_with_engines(
        engines: Vec<Arc<dyn SearchEngine>>,
        default_engine: SearchEngineType,
    ) -> Self {
        let inner = SearchClientInner {
            engines,
            default_engine,
        };
        SearchClient {
            inner: Arc::new(inner),
        }
    }

    pub fn search(&self, query: &str) -> SearchCommand {
        SearchCommand::new(self.clone(), query)
    }

    pub async fn search_with_engine(
        &self,
        query: &str,
        engine: SearchEngineType,
    ) -> Result<Response<ResponseItem>, SearchError> {
        let request = SearchRequest::new(query).with_engine(engine);
        let eng = self
            .inner
            .engines
            .iter()
            .find(|e| e.engine_type() == engine)
            .ok_or_else(|| SearchError::NoEngineAvailable)?;

        eng.search(&request).await
    }

    pub fn default_engine(&self) -> SearchEngineType {
        self.inner.default_engine
    }
}

#[async_trait::async_trait]
impl SearchClientTrait for SearchClient {
    async fn search(&self, query: &str) -> SearchCommand {
        SearchCommand::new(self.clone(), query)
    }

    async fn search_with_engine(
        &self,
        query: &str,
        engine: SearchEngineType,
    ) -> Result<Response<ResponseItem>, SearchError> {
        let request = SearchRequest::new(query).with_engine(engine);
        let eng = self
            .inner
            .engines
            .iter()
            .find(|e| e.engine_type() == engine)
            .ok_or_else(|| SearchError::NoEngineAvailable)?;

        eng.search(&request).await
    }

    fn default_engine(&self) -> SearchEngineType {
        self.inner.default_engine
    }
}

/// 搜索命令构建器
#[must_use]
pub struct SearchCommand {
    client: SearchClient,
    query: String,
    engine: Option<SearchEngineType>,
    limit: u32,
    offset: u32,
}

impl SearchCommand {
    pub fn new(client: SearchClient, query: &str) -> Self {
        Self {
            client,
            query: query.to_string(),
            engine: None,
            limit: 10,
            offset: 0,
        }
    }

    pub fn bing(mut self) -> Self {
        self.engine = Some(SearchEngineType::Bing);
        self
    }

    pub fn baidu(mut self) -> Self {
        self.engine = Some(SearchEngineType::Baidu);
        self
    }

    pub fn sogou(mut self) -> Self {
        self.engine = Some(SearchEngineType::Sogou);
        self
    }

    pub fn with_engine(mut self, engine: &str) -> Self {
        self.engine = SearchEngineType::from_name(engine);
        self
    }

    pub fn limit(mut self, n: u32) -> Self {
        self.limit = n;
        self
    }

    pub fn offset(mut self, n: u32) -> Self {
        self.offset = n;
        self
    }

    pub async fn execute(&self) -> Result<Response<ResponseItem>, SearchError> {
        let engine = self.engine.unwrap_or(self.client.default_engine());
        let request = SearchRequest {
            query: self.query.clone(),
            engine: Some(engine),
            limit: self.limit,
            offset: self.offset,
            lang: None,
            country: None,
        };

        let eng = self
            .client
            .inner
            .engines
            .iter()
            .find(|e| e.engine_type() == engine)
            .ok_or_else(|| SearchError::NoEngineAvailable)?;

        eng.search(&request).await
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Create a SearchClient with all engines registered (for testing)
    fn create_test_search_client() -> SearchClient {
        use crate::engines::engine_client::EngineClient;
        let engine_client = Arc::new(EngineClient::new());
        SearchClient::new(engine_client)
    }

    #[tokio::test]
    async fn test_search_command_builder() {
        let client = create_test_search_client();
        let cmd = client.search("test query").bing().limit(5);
        assert_eq!(cmd.query, "test query");
        assert_eq!(cmd.engine, Some(SearchEngineType::Bing));
        assert_eq!(cmd.limit, 5);
    }

    #[tokio::test]
    async fn test_search_request_builder() {
        let req = SearchRequest::new("hello")
            .with_engine(SearchEngineType::Bing)
            .with_limit(20)
            .with_offset(10);

        assert_eq!(req.query, "hello");
        assert_eq!(req.engine, Some(SearchEngineType::Bing));
        assert_eq!(req.limit, 20);
        assert_eq!(req.offset, 10);
    }

    #[tokio::test]
    async fn test_all_engines_registered() {
        let client = create_test_search_client();
        assert_eq!(client.inner.engines.len(), 3);
    }

    // ========== Mock SearchEngine for client tests ==========

    use crate::search::types::EngineHealth;

    struct MockClientEngine {
        name: &'static str,
        engine_type: SearchEngineType,
        items: Vec<ResponseItem>,
    }

    impl MockClientEngine {
        fn new(
            name: &'static str,
            engine_type: SearchEngineType,
            items: Vec<ResponseItem>,
        ) -> Self {
            Self {
                name,
                engine_type,
                items,
            }
        }
    }

    #[async_trait::async_trait]
    impl SearchEngine for MockClientEngine {
        fn name(&self) -> &'static str {
            self.name
        }

        fn engine_type(&self) -> SearchEngineType {
            self.engine_type
        }

        fn health(&self) -> EngineHealth {
            EngineHealth::Healthy
        }

        async fn search(
            &self,
            _request: &SearchRequest,
        ) -> Result<Response<ResponseItem>, SearchError> {
            Ok(Response {
                items: self.items.clone(),
                total_results: Some(self.items.len() as u64),
                engine: self.engine_type,
            })
        }
    }

    fn make_mock_items(engine_type: SearchEngineType, count: usize) -> Vec<ResponseItem> {
        (0..count)
            .map(|i| ResponseItem {
                title: format!("Result {}", i + 1),
                url: format!("https://example.com/{}", i),
                description: format!("Description {}", i + 1),
                engine: engine_type,
            })
            .collect()
    }

    // ========== new_with_engines tests ==========

    #[test]
    fn test_new_with_engines_creates_client_with_custom_engines() {
        let engines: Vec<Arc<dyn SearchEngine>> = vec![
            Arc::new(MockClientEngine::new(
                "bing",
                SearchEngineType::Bing,
                make_mock_items(SearchEngineType::Bing, 2),
            )),
            Arc::new(MockClientEngine::new(
                "baidu",
                SearchEngineType::Baidu,
                make_mock_items(SearchEngineType::Baidu, 1),
            )),
        ];
        let client = SearchClient::new_with_engines(engines, SearchEngineType::Bing);
        assert_eq!(client.inner.engines.len(), 2);
        assert_eq!(client.default_engine(), SearchEngineType::Bing);
    }

    #[test]
    fn test_new_with_engines_empty_engines() {
        let client = SearchClient::new_with_engines(vec![], SearchEngineType::Bing);
        assert_eq!(client.inner.engines.len(), 0);
        assert_eq!(client.default_engine(), SearchEngineType::Bing);
    }

    // ========== register_engine tests ==========

    #[test]
    fn test_register_engine_adds_to_client() {
        let engines: Vec<Arc<dyn SearchEngine>> = vec![Arc::new(MockClientEngine::new(
            "bing",
            SearchEngineType::Bing,
            make_mock_items(SearchEngineType::Bing, 1),
        ))];
        let mut client = SearchClient::new_with_engines(engines, SearchEngineType::Bing);
        assert_eq!(client.inner.engines.len(), 1);

        client.register_engine(Arc::new(MockClientEngine::new(
            "bing",
            SearchEngineType::Bing,
            make_mock_items(SearchEngineType::Bing, 1),
        )));
        assert_eq!(client.inner.engines.len(), 2);
    }

    // ========== with_configured_engines tests ==========

    fn build_configured_client(settings: &SearchSettings) -> SearchClient {
        build_configured_client_with_searxng(settings, None)
    }

    fn build_configured_client_with_searxng(
        settings: &SearchSettings,
        searxng: Option<Arc<dyn SearxngInstanceService>>,
    ) -> SearchClient {
        let engine_client = Arc::new(EngineClient::new());
        let http_client = Arc::new(reqwest::Client::new());
        SearchClient::with_configured_engines(engine_client, http_client, settings, searxng)
    }

    fn test_searxng_service() -> Arc<dyn SearxngInstanceService> {
        use crate::domain::services::searxng::test_support::{
            shared_repo, test_settings, ScriptedTransport,
        };
        use crate::domain::services::searxng::SearxngInstanceServiceImpl;
        Arc::new(SearxngInstanceServiceImpl::new(
            shared_repo(),
            Arc::new(ScriptedTransport::new(vec![])),
            test_settings(),
        ))
    }

    fn registered_engine_types(client: &SearchClient) -> Vec<SearchEngineType> {
        client
            .inner
            .engines
            .iter()
            .map(|e| e.engine_type())
            .collect()
    }

    #[test]
    fn test_with_configured_engines_without_api_keys_skips_exa_and_tavily() {
        let client = build_configured_client(&SearchSettings::default());
        let types = registered_engine_types(&client);

        assert_eq!(
            client.inner.engines.len(),
            3,
            "only bing/baidu/sogou should be registered without api keys"
        );
        assert!(
            !types.contains(&SearchEngineType::Exa),
            "exa should not be registered without api_key"
        );
        assert!(
            !types.contains(&SearchEngineType::Tavily),
            "tavily should not be registered without api_key"
        );
    }

    #[test]
    fn test_with_configured_engines_honors_engine_switches() {
        let mut settings = SearchSettings::default();
        settings.engines.baidu_enabled = false;
        settings.engines.sogou_enabled = false;

        let client = build_configured_client(&settings);
        let types = registered_engine_types(&client);

        assert_eq!(
            client.inner.engines.len(),
            1,
            "only bing should be registered when baidu/sogou are disabled"
        );
        assert_eq!(types, vec![SearchEngineType::Bing]);
    }

    #[test]
    fn test_with_configured_engines_default_engine_from_settings() {
        let settings = SearchSettings {
            default_engine: Some("baidu".to_string()),
            ..Default::default()
        };

        let client = build_configured_client(&settings);
        assert_eq!(
            client.default_engine(),
            SearchEngineType::Baidu,
            "configured default_engine must be honored on the single-engine fallback path"
        );
    }

    #[test]
    fn test_with_configured_engines_unknown_default_engine_falls_back_to_bing() {
        let settings = SearchSettings {
            default_engine: Some("definitely-not-an-engine".to_string()),
            ..Default::default()
        };

        let client = build_configured_client(&settings);
        assert_eq!(client.default_engine(), SearchEngineType::Bing);
    }

    #[test]
    fn test_with_configured_engines_unregistered_default_engine_falls_back_to_bing() {
        // exa 合法但未配置凭据 → 未注册 → 回退 bing(而非指向不可用引擎)
        let settings = SearchSettings {
            default_engine: Some("exa".to_string()),
            ..Default::default()
        };

        let client = build_configured_client(&settings);
        assert_eq!(client.default_engine(), SearchEngineType::Bing);
    }

    #[test]
    fn test_with_configured_engines_with_searxng_enabled_registers_engine() {
        let mut settings = SearchSettings::default();
        settings.searxng.enabled = true;

        let client = build_configured_client_with_searxng(&settings, Some(test_searxng_service()));
        let types = registered_engine_types(&client);

        assert_eq!(client.inner.engines.len(), 4);
        assert!(
            types.contains(&SearchEngineType::Searxng),
            "searxng should register when enabled and the service exists"
        );
        assert_eq!(
            SearchEngineType::from_name("searxng"),
            Some(SearchEngineType::Searxng)
        );
        // 按名称可寻址(单引擎路径)
        assert!(client.inner.engines.iter().any(|e| e.name() == "SearxNG"));
    }

    #[test]
    fn test_with_configured_engines_searxng_disabled_skips_engine() {
        let settings = SearchSettings::default(); // enabled=false
        let client = build_configured_client_with_searxng(&settings, Some(test_searxng_service()));
        assert!(!registered_engine_types(&client).contains(&SearchEngineType::Searxng));
    }

    #[test]
    fn test_with_configured_engines_searxng_without_service_skips_engine() {
        let mut settings = SearchSettings::default();
        settings.searxng.enabled = true;
        let client = build_configured_client(&settings);
        assert!(
            !registered_engine_types(&client).contains(&SearchEngineType::Searxng),
            "enabled without an instance service must not register the engine"
        );
    }

    #[tokio::test]
    async fn test_searxng_single_engine_path_is_addressable() {
        let mut settings = SearchSettings::default();
        settings.searxng.enabled = true;
        let client = build_configured_client_with_searxng(&settings, Some(test_searxng_service()));

        // 引擎已注册(单引擎路径可寻址);空池时返回 NoEngineAvailable 而非找不到引擎
        let result = client
            .search_with_engine("test", SearchEngineType::Searxng)
            .await;
        match result {
            Err(SearchError::NoEngineAvailable) => {}
            other => panic!("expected NoEngineAvailable from an empty pool, got {other:?}"),
        }
    }

    #[test]
    fn test_with_configured_engines_with_exa_api_key_registers_exa() {
        let mut settings = SearchSettings::default();
        settings.exa.api_key = Some("test-exa-key".to_string());

        let client = build_configured_client(&settings);
        let types = registered_engine_types(&client);

        assert_eq!(client.inner.engines.len(), 4);
        assert!(
            types.contains(&SearchEngineType::Exa),
            "exa should be registered when api_key is configured"
        );
        // SearchCommand::with_engine("exa") 依赖 from_name 解析路径
        assert_eq!(
            SearchEngineType::from_name("exa"),
            Some(SearchEngineType::Exa)
        );
    }

    #[test]
    fn test_with_configured_engines_with_tavily_api_key_registers_tavily() {
        let mut settings = SearchSettings::default();
        settings.tavily.api_key = Some("test-tavily-key".to_string());

        let client = build_configured_client(&settings);
        let types = registered_engine_types(&client);

        assert_eq!(client.inner.engines.len(), 4);
        assert!(
            types.contains(&SearchEngineType::Tavily),
            "tavily should be registered when api_key is configured"
        );
        assert_eq!(
            SearchEngineType::from_name("tavily"),
            Some(SearchEngineType::Tavily)
        );
    }

    #[test]
    fn test_with_configured_engines_with_both_api_keys_registers_all() {
        let mut settings = SearchSettings::default();
        settings.exa.api_key = Some("test-exa-key".to_string());
        settings.tavily.api_key = Some("test-tavily-key".to_string());

        let client = build_configured_client(&settings);
        let types = registered_engine_types(&client);

        assert_eq!(client.inner.engines.len(), 5);
        assert!(types.contains(&SearchEngineType::Exa));
        assert!(types.contains(&SearchEngineType::Tavily));
    }

    #[test]
    fn test_with_configured_engines_empty_api_key_string_skips_registration() {
        let mut settings = SearchSettings::default();
        settings.exa.api_key = Some(String::new());
        settings.tavily.api_key = Some("   ".to_string());

        let client = build_configured_client(&settings);

        assert_eq!(
            client.inner.engines.len(),
            3,
            "blank api_key should be treated as not configured"
        );
        assert!(!registered_engine_types(&client).contains(&SearchEngineType::Exa));
        assert!(!registered_engine_types(&client).contains(&SearchEngineType::Tavily));
    }

    #[tokio::test]
    async fn test_with_engine_exa_unregistered_returns_no_engine_available() {
        let client = build_configured_client(&SearchSettings::default());

        // with_engine("exa") 解析为 Some(Exa),但引擎未注册 → 显性 NoEngineAvailable
        let result = client.search("test").with_engine("exa").execute().await;
        assert!(result.is_err());
        match result.unwrap_err() {
            SearchError::NoEngineAvailable => {}
            other => panic!("Expected NoEngineAvailable, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_search_with_engine_tavily_unregistered_returns_no_engine_available() {
        let client = build_configured_client(&SearchSettings::default());

        let result = client
            .search_with_engine("test", SearchEngineType::Tavily)
            .await;
        assert!(result.is_err());
        match result.unwrap_err() {
            SearchError::NoEngineAvailable => {}
            other => panic!("Expected NoEngineAvailable, got {:?}", other),
        }
    }

    // ========== search_with_engine tests ==========

    #[tokio::test]
    async fn test_search_with_engine_success() {
        let engines: Vec<Arc<dyn SearchEngine>> = vec![Arc::new(MockClientEngine::new(
            "bing",
            SearchEngineType::Bing,
            make_mock_items(SearchEngineType::Bing, 3),
        ))];
        let client = SearchClient::new_with_engines(engines, SearchEngineType::Bing);

        let response = client
            .search_with_engine("test", SearchEngineType::Bing)
            .await
            .expect("search_with_engine should succeed");
        assert_eq!(response.items.len(), 3);
        assert_eq!(response.engine, SearchEngineType::Bing);
        assert_eq!(response.total_results, Some(3));
    }

    #[tokio::test]
    async fn test_search_with_engine_no_match_returns_no_engine_available() {
        let engines: Vec<Arc<dyn SearchEngine>> = vec![Arc::new(MockClientEngine::new(
            "bing",
            SearchEngineType::Bing,
            make_mock_items(SearchEngineType::Bing, 1),
        ))];
        let client = SearchClient::new_with_engines(engines, SearchEngineType::Bing);

        let result = client
            .search_with_engine("test", SearchEngineType::Baidu)
            .await;
        assert!(result.is_err());
        match result.unwrap_err() {
            SearchError::NoEngineAvailable => {}
            other => panic!("Expected NoEngineAvailable, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_search_with_engine_empty_client_returns_no_engine_available() {
        let client = SearchClient::new_with_engines(vec![], SearchEngineType::Bing);
        let result = client
            .search_with_engine("test", SearchEngineType::Bing)
            .await;
        assert!(result.is_err());
        match result.unwrap_err() {
            SearchError::NoEngineAvailable => {}
            other => panic!("Expected NoEngineAvailable, got {:?}", other),
        }
    }

    // ========== default_engine tests ==========

    #[test]
    fn test_default_engine_returns_configured_type() {
        let client = SearchClient::new_with_engines(vec![], SearchEngineType::Baidu);
        assert_eq!(client.default_engine(), SearchEngineType::Baidu);
    }

    #[test]
    fn test_default_engine_from_new_client() {
        let client = create_test_search_client();
        assert_eq!(client.default_engine(), SearchEngineType::Bing);
    }

    // ========== SearchCommand builder tests ==========

    #[tokio::test]
    async fn test_search_command_bing_builder() {
        let client = create_test_search_client();
        let cmd = client.search("query").bing();
        assert_eq!(cmd.engine, Some(SearchEngineType::Bing));
    }

    #[tokio::test]
    async fn test_search_command_baidu_builder() {
        let client = create_test_search_client();
        let cmd = client.search("query").baidu();
        assert_eq!(cmd.engine, Some(SearchEngineType::Baidu));
    }

    #[tokio::test]
    async fn test_search_command_sogou_builder() {
        let client = create_test_search_client();
        let cmd = client.search("query").sogou();
        assert_eq!(cmd.engine, Some(SearchEngineType::Sogou));
    }

    #[tokio::test]
    async fn test_search_command_with_engine_string_valid() {
        let client = create_test_search_client();
        let cmd = client.search("query").with_engine("bing");
        assert_eq!(cmd.engine, Some(SearchEngineType::Bing));
    }

    #[tokio::test]
    async fn test_search_command_with_engine_string_invalid() {
        let client = create_test_search_client();
        let cmd = client.search("query").with_engine("yahoo");
        assert_eq!(cmd.engine, None);
    }

    #[tokio::test]
    async fn test_search_command_offset_builder() {
        let client = create_test_search_client();
        let cmd = client.search("query").offset(20);
        assert_eq!(cmd.offset, 20);
    }

    #[tokio::test]
    async fn test_search_command_chained_builders() {
        let client = create_test_search_client();
        let cmd = client.search("rust").bing().limit(15).offset(5);
        assert_eq!(cmd.query, "rust");
        assert_eq!(cmd.engine, Some(SearchEngineType::Bing));
        assert_eq!(cmd.limit, 15);
        assert_eq!(cmd.offset, 5);
    }

    // ========== SearchCommand::execute tests ==========

    #[tokio::test]
    async fn test_execute_success_with_matching_engine() {
        let engines: Vec<Arc<dyn SearchEngine>> = vec![Arc::new(MockClientEngine::new(
            "bing",
            SearchEngineType::Bing,
            make_mock_items(SearchEngineType::Bing, 2),
        ))];
        let client = SearchClient::new_with_engines(engines, SearchEngineType::Bing);

        let response = client
            .search("test")
            .bing()
            .execute()
            .await
            .expect("execute should succeed with matching engine");
        assert_eq!(response.items.len(), 2);
        assert_eq!(response.engine, SearchEngineType::Bing);
    }

    #[tokio::test]
    async fn test_execute_no_matching_engine_returns_error() {
        let engines: Vec<Arc<dyn SearchEngine>> = vec![Arc::new(MockClientEngine::new(
            "bing",
            SearchEngineType::Bing,
            make_mock_items(SearchEngineType::Bing, 1),
        ))];
        let client = SearchClient::new_with_engines(engines, SearchEngineType::Bing);

        let result = client.search("test").baidu().execute().await;
        assert!(result.is_err());
        match result.unwrap_err() {
            SearchError::NoEngineAvailable => {}
            other => panic!("Expected NoEngineAvailable, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_execute_uses_default_engine_when_none_specified() {
        let engines: Vec<Arc<dyn SearchEngine>> = vec![Arc::new(MockClientEngine::new(
            "bing",
            SearchEngineType::Bing,
            make_mock_items(SearchEngineType::Bing, 1),
        ))];
        let client = SearchClient::new_with_engines(engines, SearchEngineType::Bing);

        // No engine specified, should use default (Bing)
        let response = client
            .search("test")
            .execute()
            .await
            .expect("execute should use default engine");
        assert_eq!(response.items.len(), 1);
        assert_eq!(response.engine, SearchEngineType::Bing);
    }

    #[tokio::test]
    async fn test_execute_with_empty_client_returns_no_engine_available() {
        let client = SearchClient::new_with_engines(vec![], SearchEngineType::Bing);
        let result = client.search("test").execute().await;
        assert!(result.is_err());
        match result.unwrap_err() {
            SearchError::NoEngineAvailable => {}
            other => panic!("Expected NoEngineAvailable, got {:?}", other),
        }
    }

    // ========== SearchClientTrait impl tests ==========

    #[tokio::test]
    async fn test_trait_impl_search_returns_command() {
        let client = create_test_search_client();
        let cmd = SearchClientTrait::search(&client, "query").await;
        assert_eq!(cmd.query, "query");
    }

    #[tokio::test]
    async fn test_trait_impl_search_with_engine_success() {
        let engines: Vec<Arc<dyn SearchEngine>> = vec![Arc::new(MockClientEngine::new(
            "bing",
            SearchEngineType::Bing,
            make_mock_items(SearchEngineType::Bing, 1),
        ))];
        let client = SearchClient::new_with_engines(engines, SearchEngineType::Bing);

        let response =
            SearchClientTrait::search_with_engine(&client, "test", SearchEngineType::Bing)
                .await
                .expect("trait search_with_engine should succeed");
        assert_eq!(response.items.len(), 1);
    }

    #[tokio::test]
    async fn test_trait_impl_search_with_engine_no_match() {
        let engines: Vec<Arc<dyn SearchEngine>> = vec![Arc::new(MockClientEngine::new(
            "bing",
            SearchEngineType::Bing,
            make_mock_items(SearchEngineType::Bing, 1),
        ))];
        let client = SearchClient::new_with_engines(engines, SearchEngineType::Bing);

        let result =
            SearchClientTrait::search_with_engine(&client, "test", SearchEngineType::Baidu).await;
        assert!(result.is_err());
    }

    #[test]
    fn test_trait_impl_default_engine() {
        let client = SearchClient::new_with_engines(vec![], SearchEngineType::Sogou);
        assert_eq!(
            SearchClientTrait::default_engine(&client),
            SearchEngineType::Sogou
        );
    }
}

// ========== Shared Utilities ==========

// Shared utilities for search engine clients
// Provides common utilities to eliminate code duplication across search engine implementations.

use url::Url;

/// Encode a search query for use in URLs
pub fn encode_search_query(query: &str) -> String {
    urlencoding::encode(query).to_string()
}

/// Build a simple paginated search URL
pub fn build_search_url(
    base_url: &str,
    query_param: &str,
    query: &str,
    page: u32,
    results_per_page: u32,
) -> String {
    let encoded_query = encode_search_query(query);
    let offset = (page - 1) * results_per_page;
    format!(
        "{}?{}={}&start={}",
        base_url, query_param, encoded_query, offset
    )
}

/// Validate and normalize a URL from search results
pub fn validate_result_url(url: &str, allowed_schemes: &[&str]) -> Option<String> {
    if url.is_empty() {
        return None;
    }
    if !url.starts_with("http://") && !url.starts_with("https://") {
        return None;
    }
    match Url::parse(url) {
        Ok(parsed) => {
            if allowed_schemes.contains(&parsed.scheme()) {
                Some(url.to_string())
            } else {
                None
            }
        }
        Err(_) => None,
    }
}

#[cfg(test)]
mod shared_tests {
    use super::*;

    #[test]
    fn test_encode_search_query() {
        let encoded = encode_search_query("hello world");
        assert!(encoded.contains("hello%20world"));
    }

    #[test]
    fn test_build_search_url() {
        let url = build_search_url("https://example.com/search", "q", "test", 2, 10);
        assert!(url.contains("q=test"));
        assert!(url.contains("start=10"));
    }

    #[test]
    fn test_validate_result_url_valid() {
        let result = validate_result_url("https://example.com", &["http", "https"]);
        assert_eq!(result, Some("https://example.com".to_string()));
    }

    #[test]
    fn test_validate_result_url_invalid_scheme() {
        let result = validate_result_url("ftp://example.com", &["http", "https"]);
        assert!(result.is_none());
    }

    #[test]
    fn test_validate_result_url_empty_returns_none() {
        let result = validate_result_url("", &["http", "https"]);
        assert!(result.is_none(), "empty URL should return None");
    }

    #[test]
    fn test_validate_result_url_no_scheme_returns_none() {
        let result = validate_result_url("example.com", &["http", "https"]);
        assert!(
            result.is_none(),
            "URL without http/https prefix should return None"
        );
    }

    #[test]
    fn test_validate_result_url_plain_string_returns_none() {
        let result = validate_result_url("not-a-url", &["http", "https"]);
        assert!(result.is_none(), "plain string should return None");
    }

    #[test]
    fn test_validate_result_url_http_with_only_https_allowed() {
        let result = validate_result_url("http://example.com", &["https"]);
        assert!(
            result.is_none(),
            "http URL with only https allowed should return None"
        );
    }

    #[test]
    fn test_validate_result_url_https_with_only_http_allowed() {
        let result = validate_result_url("https://example.com", &["http"]);
        assert!(
            result.is_none(),
            "https URL with only http allowed should return None"
        );
    }

    #[test]
    fn test_validate_result_url_with_path() {
        let result = validate_result_url("https://example.com/path/to/page", &["http", "https"]);
        assert_eq!(result, Some("https://example.com/path/to/page".to_string()));
    }

    #[test]
    fn test_validate_result_url_http_no_host_returns_none() {
        // Cover line 673: "http://" passes the starts_with check but
        // Url::parse fails with EmptyHost, triggering the Err(_) => None branch.
        let result = validate_result_url("http://", &["http", "https"]);
        assert_eq!(result, None);
    }
}