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
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
// Copyright (c) 2025-2026 Kirky.X🌠
// SPDX-License-Identifier: Apache-2.0

//! FlareSolverr Engine - Uses FlareSolverr API to bypass Cloudflare and other anti-bot protections
//!
//! FlareSolverr is a proxy server that uses Selenium with undetected-chromedriver
//! to bypass Cloudflare protection and other anti-bot measures.
//!
//! 本模块合并了原 `FireEngineCdp`(CDP 模式)和 `FireEngineTls`(TLS 模式)
//! 两个独立引擎,统一为 `FlareSolverrEngine` + `FlareSolverrMode` 模式枚举。
//! 三种模式(Full / Cdp / Tls)共享同一个 FlareSolverr API 客户端实现,
//! 仅在 support_score 和 name 上有差异,Tls 模式额外拒绝截图请求。
//!
//! ## 范围外说明(ProxyProvider 接入)
//!
//! 本引擎仍使用单 `proxy_url`(`Option<&str>`)而非 `ProxyProvider` trait。
//! 这是明确标注的范围外项:
//! - FlareSolverr 通过 HTTP API 调用外部服务,proxy_url 仅记录到 `X-Proxy-URL` header
//!   供 FlareSolverr 服务自身识别代理(不同于 ReqwestEngine 直接通过 reqwest::Proxy 使用代理)
//! - 接入 ProxyProvider 需要 FlareSolverr 服务端支持代理轮换语义,超出范围
//! - 后续如需接入,可在 `with_mode_and_proxy` / `with_url` 等构造函数中扩展
//!
//! This engine is particularly useful for:
//! - Google search (bypasses CAPTCHA)
//! - Cloudflare-protected sites
//! - Sites with strong anti-bot measures

use crate::engines::engine_client::{
    EngineError, InternalScrapeRequest, InternalScrapeResponse, ScraperEngine,
};
use crate::utils::proxy::redact_proxy_url;
use async_trait::async_trait;
use log::{debug, error, info, warn};
use reqwest::Client;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;

/// FlareSolverrEngine TLS 模式默认 MRT(15 秒,对应 `EngineTimeoutSettings::tls_seconds`)。
///
/// TLS 模式专注 TLS 指纹对抗,速度较快,15 秒足够;
/// 超时即切下一引擎(瀑布式)。
const DEFAULT_FLARESOLVERR_TLS_MRT_SECONDS: u64 = 15;

/// FlareSolverrEngine CDP / Full 模式默认 MRT(30 秒,对应 `EngineTimeoutSettings::cdp_seconds`)。
///
/// CDP/Full 模式涉及完整浏览器自动化,30 秒覆盖绝大多数场景。
const DEFAULT_FLARESOLVERR_CDP_MRT_SECONDS: u64 = 30;

/// FlareSolverr 工作模式枚举
///
/// 合并原 `FireEngineCdp` / `FireEngineTls` / `FlareSolverrEngine` 三个引擎。
/// 所有模式共享 FlareSolverr API 调用逻辑,仅在以下方面有差异:
/// - `support_score`:不同模式的优先级策略
/// - `name`:用于路由器注册和日志
/// - `scrape`:Tls 模式拒绝截图请求
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum FlareSolverrMode {
    /// 完整模式(原 FlareSolverrEngine)
    ///
    /// 支持完整功能:JS 渲染、session 管理、CAPTCHA 检测、截图返回。
    /// 最适合 needs_js 请求(score=100)。
    #[default]
    Full,
    /// CDP 模式(原 FireEngineCdp)
    ///
    /// 支持完整浏览器自动化、JS 渲染、截图、TLS 指纹对抗。
    /// 成本较高,速度较慢。
    Cdp,
    /// TLS 模式(原 FireEngineTls)
    ///
    /// 专注于 TLS 指纹对抗,速度较快,不支持截图和复杂 JS 交互。
    /// 拒绝 needs_screenshot 请求。
    Tls,
}

impl FlareSolverrMode {
    /// 获取该模式下的引擎名称(用于 ScraperEngine::name)
    pub fn engine_name(&self) -> &'static str {
        match self {
            Self::Full => "flaresolverr",
            Self::Cdp => "flaresolverr_cdp",
            Self::Tls => "flaresolverr_tls",
        }
    }

    /// 是否支持 TLS 指纹对抗
    ///
    /// - Full: FlareSolverr 本身不直接暴露 TLS 指纹控制(保持原行为)
    /// - Cdp: 支持(通过浏览器自动化)
    /// - Tls: 支持(专门为 TLS 指纹对抗设计)
    pub fn supports_tls_fingerprint(&self) -> bool {
        match self {
            Self::Full => false,
            Self::Cdp | Self::Tls => true,
        }
    }

    /// 获取该模式下的默认 MRT(Maximum Response Time)。
    ///
    /// - `Full` / `Cdp`:30 秒(`cdp_seconds`,涉及完整浏览器)
    /// - `Tls`:15 秒(`tls_seconds`,仅 TLS 指纹对抗,速度较快)
    ///
    /// 引擎构造时若未注入 `mrt`,则使用此默认值。
    /// 生产环境应通过 [`FlareSolverrConfig::mrt`] 从 `EngineTimeoutSettings` 注入。
    pub fn default_mrt(&self) -> Duration {
        match self {
            Self::Full | Self::Cdp => Duration::from_secs(DEFAULT_FLARESOLVERR_CDP_MRT_SECONDS),
            Self::Tls => Duration::from_secs(DEFAULT_FLARESOLVERR_TLS_MRT_SECONDS),
        }
    }
}

/// FlareSolverr configuration
#[derive(Debug, Clone)]
pub struct FlareSolverrConfig {
    /// FlareSolverr server URL
    pub url: String,
    /// Request timeout in seconds
    pub timeout_seconds: u64,
    /// Default session ID (optional)
    pub session_id: Option<String>,
    /// 工作模式(默认 Full)
    pub mode: FlareSolverrMode,
    /// 代理 URL(用于 Cdp/Tls 模式记录到 X-Proxy-URL header)
    pub proxy_url: Option<String>,
    /// 单引擎最大响应时间(MRT)。
    ///
    /// `None` 时按 [`FlareSolverrMode::default_mrt`] 推导(Tls=15s,Cdp/Full=30s)。
    /// `Some(d)` 时使用注入值,生产环境应从 `EngineTimeoutSettings` 注入:
    /// - `tls_seconds` → Tls 模式
    /// - `cdp_seconds` → Cdp / Full 模式
    pub mrt: Option<Duration>,
}

/// FlareSolverr URL 验证失败时的安全降级占位符。
///
/// 该 URL 仅用于避免 SSRF 风险(不指向真实服务),
/// 生产环境必须通过 `config/default.toml` 或 `CRAWLRS__ENGINES__FLARESOLVERR__URL` 配置正确值。
const FALLBACK_URL: &str = "http://localhost:8191";

impl Default for FlareSolverrConfig {
    fn default() -> Self {
        // 生产环境应通过 Settings 注入 URL,而非读取遗留环境变量。
        // 此处仅作为安全降级路径:未配置时记录警告,使用占位符。
        let url = std::env::var("FLARESOLVERR_URL").unwrap_or_default();
        if url.is_empty() {
            log::warn!(
                "{}",
                crate::i18n::tr_log_args(
                    "flare-url-not-configured",
                    &[("fallback", FALLBACK_URL.to_string())],
                )
            );
        }

        let validated_url = validate_flaresolverr_url(&url).unwrap_or_else(|e| {
            log::warn!(
                "{}",
                crate::i18n::tr_log_args(
                    "flare-url-validation-failed",
                    &[
                        ("url", url.as_str().to_string()),
                        ("error", e.as_str().to_string()),
                        ("fallback", FALLBACK_URL.to_string()),
                    ],
                )
            );
            FALLBACK_URL.to_string()
        });

        Self {
            url: validated_url,
            timeout_seconds: 60,
            session_id: None,
            mode: FlareSolverrMode::default(),
            proxy_url: None,
            mrt: None,
        }
    }
}

/// Validate FlareSolverr URL - only allow http/https protocols
fn validate_flaresolverr_url(url: &str) -> Result<String, String> {
    let parsed = url::Url::parse(url).map_err(|_| "Invalid URL format".to_string())?;

    // Only allow http and https protocols
    match parsed.scheme() {
        "http" | "https" => Ok(url.to_string()),
        _ => Err(format!(
            "Invalid protocol '{}': FLARESOLVERR_URL must use http or https",
            parsed.scheme()
        )),
    }
}

/// 各构造路径共用的「URL 校验失败 → 回退占位符」warn 日志
/// (`mode` 为引擎模式修饰词,如 "CDP"/"TLS+MRT";无修饰词传空串)
fn log_flaresolverr_validation_fallback(mode: &str, error: &str) {
    let key = if mode.is_empty() {
        "flare-url-validation-fallback"
    } else {
        "flare-mode-url-validation-fallback"
    };
    log::warn!(
        "{}",
        crate::i18n::tr_log_args(
            key,
            &[
                ("mode", mode.to_string()),
                ("error", error.to_string()),
                ("fallback", FALLBACK_URL.to_string()),
            ],
        )
    );
}

/// FlareSolverr HTTP client
///
/// 统一的 FlareSolverr API 客户端,通过 `mode` 字段区分工作模式。
/// 取代原 `FireEngineCdp` / `FireEngineTls` / `FlareSolverrEngine` 三个独立 struct。
#[derive(Debug, Clone)]
pub struct FlareSolverrEngine {
    /// HTTP client for FlareSolverr API
    client: Arc<Client>,
    /// FlareSolverr configuration
    config: FlareSolverrConfig,
    /// Session ID for persistent sessions
    session_id: Option<String>,
}

impl FlareSolverrEngine {
    /// Create a new FlareSolverrEngine with default configuration (Full mode)
    pub fn new(client: Arc<Client>) -> Self {
        Self::with_config(client, FlareSolverrConfig::default())
    }

    /// Create a new FlareSolverrEngine from configuration URL (Full mode)
    ///
    /// URL 必须为 http/https 协议,否则使用默认占位符(避免 SSRF 风险)。
    pub fn with_url(client: Arc<Client>, url: impl Into<String>) -> Self {
        let validated = validate_flaresolverr_url(&url.into()).unwrap_or_else(|e| {
            log_flaresolverr_validation_fallback("", &e);
            FALLBACK_URL.to_string()
        });
        let config = FlareSolverrConfig {
            url: validated,
            timeout_seconds: 60,
            session_id: None,
            mode: FlareSolverrMode::Full,
            proxy_url: None,
            mrt: None,
        };
        Self::with_config(client, config)
    }

    /// Create a new FlareSolverrEngine with custom configuration
    pub fn with_config(client: Arc<Client>, config: FlareSolverrConfig) -> Self {
        let session_id = config.session_id.clone();

        Self {
            client,
            config,
            session_id,
        }
    }

    /// Create a FlareSolverrEngine in CDP mode with proxy
    ///
    /// 取代原 `FireEngineCdp::new` / `FireEngineCdp::with_proxy`。
    /// `proxy_url` 仅用于记录到 X-Proxy-URL header 供 FlareSolverr 识别代理。
    pub fn with_cdp_mode(client: Arc<Client>, proxy_url: Option<&str>) -> Self {
        Self::with_mode_and_proxy(client, FlareSolverrMode::Cdp, proxy_url)
    }

    /// Create a FlareSolverrEngine in CDP mode with URL and proxy
    ///
    /// 取代原 `FireEngineCdp::with_url_and_proxy`。
    /// URL 必须为 http/https 协议,否则使用默认占位符。
    pub fn with_cdp_mode_and_url(
        client: Arc<Client>,
        base_url: &str,
        proxy_url: Option<&str>,
    ) -> Self {
        let validated = validate_flaresolverr_url(base_url).unwrap_or_else(|e| {
            log_flaresolverr_validation_fallback("CDP", &e);
            FALLBACK_URL.to_string()
        });
        let config = FlareSolverrConfig {
            url: validated,
            timeout_seconds: 60,
            session_id: None,
            mode: FlareSolverrMode::Cdp,
            proxy_url: proxy_url.map(|s| s.to_string()),
            mrt: None,
        };
        Self::with_config(client, config)
    }

    /// Create a FlareSolverrEngine in TLS mode with proxy
    ///
    /// 取代原 `FireEngineTls::new` / `FireEngineTls::with_proxy`。
    pub fn with_tls_mode(client: Arc<Client>, proxy_url: Option<&str>) -> Self {
        Self::with_mode_and_proxy(client, FlareSolverrMode::Tls, proxy_url)
    }

    /// Create a FlareSolverrEngine in TLS mode with URL and proxy
    ///
    /// 取代原 `FireEngineTls::with_url_and_proxy`。
    /// URL 必须为 http/https 协议,否则使用默认占位符。
    pub fn with_tls_mode_and_url(
        client: Arc<Client>,
        base_url: &str,
        proxy_url: Option<&str>,
    ) -> Self {
        let validated = validate_flaresolverr_url(base_url).unwrap_or_else(|e| {
            log_flaresolverr_validation_fallback("TLS", &e);
            FALLBACK_URL.to_string()
        });
        let config = FlareSolverrConfig {
            url: validated,
            timeout_seconds: 60,
            session_id: None,
            mode: FlareSolverrMode::Tls,
            proxy_url: proxy_url.map(|s| s.to_string()),
            mrt: None,
        };
        Self::with_config(client, config)
    }

    /// Create a new FlareSolverrEngine from configuration URL with explicit MRT (Full mode)。
    ///
    /// 生产环境应从 `settings.timeouts.engines.cdp_seconds` 注入 `mrt`(Full 模式属 CDP 类)。
    /// URL 必须为 http/https 协议,否则使用默认占位符(避免 SSRF 风险)。
    #[must_use]
    pub fn with_url_and_mrt(
        client: Arc<Client>,
        url: impl Into<String>,
        mrt: Duration,
        timeout_seconds: u64,
    ) -> Self {
        let validated = validate_flaresolverr_url(&url.into()).unwrap_or_else(|e| {
            log_flaresolverr_validation_fallback("Full", &e);
            FALLBACK_URL.to_string()
        });
        let config = FlareSolverrConfig {
            url: validated,
            timeout_seconds,
            session_id: None,
            mode: FlareSolverrMode::Full,
            proxy_url: None,
            mrt: Some(mrt),
        };
        Self::with_config(client, config)
    }

    /// Create a FlareSolverrEngine in CDP mode with URL, proxy and explicit MRT。
    ///
    /// 生产环境应从 `settings.timeouts.engines.cdp_seconds` 注入 `mrt`。
    /// URL 必须为 http/https 协议,否则使用默认占位符。
    #[must_use]
    pub fn with_cdp_mode_url_and_mrt(
        client: Arc<Client>,
        base_url: &str,
        proxy_url: Option<&str>,
        mrt: Duration,
        timeout_seconds: u64,
    ) -> Self {
        let validated = validate_flaresolverr_url(base_url).unwrap_or_else(|e| {
            log_flaresolverr_validation_fallback("CDP+MRT", &e);
            FALLBACK_URL.to_string()
        });
        let config = FlareSolverrConfig {
            url: validated,
            timeout_seconds,
            session_id: None,
            mode: FlareSolverrMode::Cdp,
            proxy_url: proxy_url.map(|s| s.to_string()),
            mrt: Some(mrt),
        };
        Self::with_config(client, config)
    }

    /// Create a FlareSolverrEngine in TLS mode with URL, proxy and explicit MRT。
    ///
    /// 生产环境应从 `settings.timeouts.engines.tls_seconds` 注入 `mrt`。
    /// URL 必须为 http/https 协议,否则使用默认占位符。
    #[must_use]
    pub fn with_tls_mode_url_and_mrt(
        client: Arc<Client>,
        base_url: &str,
        proxy_url: Option<&str>,
        mrt: Duration,
        timeout_seconds: u64,
    ) -> Self {
        let validated = validate_flaresolverr_url(base_url).unwrap_or_else(|e| {
            log_flaresolverr_validation_fallback("TLS+MRT", &e);
            FALLBACK_URL.to_string()
        });
        let config = FlareSolverrConfig {
            url: validated,
            timeout_seconds,
            session_id: None,
            mode: FlareSolverrMode::Tls,
            proxy_url: proxy_url.map(|s| s.to_string()),
            mrt: Some(mrt),
        };
        Self::with_config(client, config)
    }

    /// 通用构造:根据 mode 和 proxy_url 创建实例(base_url 用默认或环境变量)
    fn with_mode_and_proxy(
        client: Arc<Client>,
        mode: FlareSolverrMode,
        proxy_url: Option<&str>,
    ) -> Self {
        // 环境变量 URL 也需校验协议,避免 SSRF 风险
        let raw_url = std::env::var("FLARESOLVERR_URL").unwrap_or_default();
        if raw_url.is_empty() {
            log::warn!(
                "{}",
                crate::i18n::tr_log_args(
                    "flare-url-not-configured-fallback",
                    &[("fallback", FALLBACK_URL.to_string())],
                )
            );
        }
        let validated = validate_flaresolverr_url(&raw_url).unwrap_or_else(|e| {
            log_flaresolverr_validation_fallback("", &e);
            FALLBACK_URL.to_string()
        });
        let config = FlareSolverrConfig {
            url: validated,
            timeout_seconds: 60,
            session_id: None,
            mode,
            proxy_url: proxy_url.map(|s| s.to_string()),
            mrt: None,
        };
        Self::with_config(client, config)
    }

    /// Create a builder for FlareSolverrEngine
    pub fn builder() -> FlareSolverrEngineBuilder {
        FlareSolverrEngineBuilder::default()
    }

    /// Get the current session ID
    pub fn session_id(&self) -> Option<&str> {
        self.session_id.as_deref()
    }

    /// Get the current working mode
    pub fn mode(&self) -> FlareSolverrMode {
        self.config.mode
    }

    /// 获取引擎级 MRT(用于测试验证)。
    ///
    /// 返回构造时注入的 `mrt`;若未注入则按 [`FlareSolverrMode::default_mrt`] 推导:
    /// - `Full` / `Cdp`:30 秒
    /// - `Tls`:15 秒
    #[must_use]
    pub fn mrt(&self) -> Duration {
        self.config
            .mrt
            .unwrap_or_else(|| self.config.mode.default_mrt())
    }

    /// Get the API URL for FlareSolverr
    /// Handles URLs with or without trailing /v1 to avoid duplication
    fn api_url(&self) -> String {
        let base_url = self.config.url.trim_end_matches('/');
        if base_url.ends_with("/v1") {
            base_url.to_string()
        } else {
            format!("{}/v1", base_url)
        }
    }

    /// Create a new session
    pub async fn create_session(&mut self) -> Result<String, EngineError> {
        #[derive(Serialize)]
        struct CreateSessionRequest {
            cmd: String,
            #[serde(skip_serializing_if = "Option::is_none")]
            session: Option<String>,
        }

        let request = CreateSessionRequest {
            cmd: "sessions.create".to_string(),
            session: None,
        };

        let response: SessionResponse = self
            .client
            .post(self.api_url())
            .json(&request)
            .send()
            .await
            .map_err(|e| EngineError::Other(format!("Failed to create session: {}", e)))?
            .json()
            .await
            .map_err(|e| EngineError::Other(format!("Failed to parse session response: {}", e)))?;

        if response.status == "ok" {
            if let Some(session_id) = response.session {
                self.session_id = Some(session_id.clone());
                info!("Created FlareSolverr session: {}", session_id);
                Ok(session_id)
            } else {
                Err(EngineError::Other("No session ID in response".to_string()))
            }
        } else {
            Err(EngineError::Other(format!(
                "Failed to create session: {}",
                response.message
            )))
        }
    }

    /// Destroy a session
    pub async fn destroy_session(&mut self, session_id: &str) -> Result<(), EngineError> {
        #[derive(Serialize)]
        struct DestroySessionRequest {
            cmd: String,
            session: String,
        }

        let request = DestroySessionRequest {
            cmd: "sessions.destroy".to_string(),
            session: session_id.to_string(),
        };

        let response: GenericResponse = self
            .client
            .post(self.api_url())
            .json(&request)
            .send()
            .await
            .map_err(|e| EngineError::Other(format!("Failed to destroy session: {}", e)))?
            .json()
            .await
            .map_err(|e| EngineError::Other(format!("Failed to parse response: {}", e)))?;

        if response.status == "ok" {
            self.session_id = None;
            debug!("Destroyed FlareSolverr session: {}", session_id);
            Ok(())
        } else {
            Err(EngineError::Other(format!(
                "Failed to destroy session: {}",
                response.message
            )))
        }
    }
}

/// Builder for FlareSolverrEngine
#[derive(Debug, Default)]
pub struct FlareSolverrEngineBuilder {
    config: FlareSolverrConfig,
}

impl FlareSolverrEngineBuilder {
    /// Set FlareSolverr URL
    pub fn with_url(mut self, url: &str) -> Self {
        self.config.url = url.to_string();
        self
    }

    /// Set request timeout
    pub fn with_timeout(mut self, seconds: u64) -> Self {
        self.config.timeout_seconds = seconds;
        self
    }

    /// Set default session ID
    pub fn with_session(mut self, session_id: &str) -> Self {
        self.config.session_id = Some(session_id.to_string());
        self
    }

    /// Set working mode
    pub fn with_mode(mut self, mode: FlareSolverrMode) -> Self {
        self.config.mode = mode;
        self
    }

    /// Set proxy URL (for Cdp/Tls modes)
    pub fn with_proxy(mut self, proxy_url: &str) -> Self {
        self.config.proxy_url = Some(proxy_url.to_string());
        self
    }

    /// Set engine MRT (Maximum Response Time).
    ///
    /// `None` 时按 [`FlareSolverrMode::default_mrt`] 推导。
    /// 生产环境应从 `EngineTimeoutSettings` 注入对应字段。
    pub fn with_mrt(mut self, mrt: Duration) -> Self {
        self.config.mrt = Some(mrt);
        self
    }

    /// Build the FlareSolverrEngine
    pub fn build(self, client: Arc<Client>) -> FlareSolverrEngine {
        FlareSolverrEngine::with_config(client, self.config)
    }
}

/// Response from FlareSolverr sessions.create
#[derive(Serialize, Deserialize, Debug)]
struct SessionResponse {
    status: String,
    message: String,
    session: Option<String>,
    #[serde(flatten)]
    _extra: HashMap<String, serde_json::Value>,
}

/// Generic response from FlareSolverr
#[derive(Serialize, Deserialize, Debug)]
struct GenericResponse {
    status: String,
    message: String,
    #[serde(flatten)]
    _extra: HashMap<String, serde_json::Value>,
}

/// Request to FlareSolverr
#[derive(Serialize, Debug)]
struct FlareSolverrRequest {
    cmd: String,
    url: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    session: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    max_timeout: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    return_screenshot: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    wait_in_seconds: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    disable_media: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    cookies: Option<Vec<Cookie>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    post_data: Option<String>,
    /// 自定义请求头(用于 Cdp/Tls 模式传递 X-Proxy-URL 等)
    #[serde(skip_serializing_if = "Option::is_none")]
    custom_headers: Option<HashMap<String, String>>,
}

/// Cookie for FlareSolverr
#[derive(Serialize, Deserialize, Debug, Clone)]
struct Cookie {
    name: String,
    value: String,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    domain: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    path: Option<String>,
}

/// Response from FlareSolverr
#[derive(Serialize, Deserialize, Debug)]
struct FlareSolverrResponse {
    status: String,
    message: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    solution: Option<FlareSolverrSolution>,
    #[serde(flatten)]
    _extra: HashMap<String, serde_json::Value>,
}

/// Solution from FlareSolverr
#[derive(Serialize, Deserialize, Debug)]
struct FlareSolverrSolution {
    url: String,
    status: u16,
    #[serde(skip_serializing_if = "Option::is_none")]
    headers: Option<HashMap<String, String>>,
    response: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    cookies: Option<Vec<Cookie>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    user_agent: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    screenshot: Option<String>,
    #[serde(default)]
    start_timestamp: i64,
    #[serde(default)]
    end_timestamp: i64,
}

/// 合并 custom headers:proxy 信息(X-Proxy-URL)+ 用户传入的 headers。
/// 用户 headers 优先级高于 X-Proxy-URL,避免冲突;不覆盖已设置的
/// X-Proxy-URL(proxy 信息优先)。
fn merge_custom_headers(
    mode: FlareSolverrMode,
    proxy_url: Option<&String>,
    user_headers: &HashMap<String, String>,
) -> HashMap<String, String> {
    let mut custom_headers: HashMap<String, String> = HashMap::new();

    if let Some(proxy) = proxy_url {
        custom_headers.insert("X-Proxy-URL".to_string(), proxy.clone());
        // 使用脱敏后的 proxy URL 打印日志(避免凭证泄露 - 安全修复)
        debug!(
            "{} using proxy: {}",
            mode.engine_name(),
            redact_proxy_url(proxy)
        );
    }

    // 合并用户传入的 headers(用户 headers 优先级高于 X-Proxy-URL,避免冲突)
    for (key, value) in user_headers {
        // 不覆盖已设置的 X-Proxy-URL(proxy 信息优先)
        if key != "X-Proxy-URL" {
            custom_headers.insert(key.clone(), value.clone());
        }
    }

    if !user_headers.is_empty() {
        debug!(
            "{} forwarded {} custom headers to FlareSolverr",
            mode.engine_name(),
            user_headers.len()
        );
    }

    custom_headers
}

/// 构造 request.get 请求体(截图 / 等待秒数按请求开关,headers 为空时不传)
fn build_fs_request(
    request: &InternalScrapeRequest,
    session: Option<String>,
    custom_headers: HashMap<String, String>,
) -> FlareSolverrRequest {
    FlareSolverrRequest {
        cmd: "request.get".to_string(),
        url: request.url.clone(),
        session,
        max_timeout: Some(request.timeout.as_millis() as u64),
        return_screenshot: if request.needs_screenshot {
            Some(true)
        } else {
            None
        },
        wait_in_seconds: if request.sync_wait_ms > 0 {
            Some(request.sync_wait_ms as u64 / 1000)
        } else {
            None
        },
        disable_media: None,
        cookies: None,
        post_data: None,
        custom_headers: if custom_headers.is_empty() {
            None
        } else {
            Some(custom_headers)
        },
    }
}

/// 构造 FlareSolverr API URL:去尾部斜杠,防重复 /v1
fn build_api_url(config_url: &str) -> String {
    let base_url = config_url.trim_end_matches('/');
    if base_url.ends_with("/v1") {
        base_url.to_string()
    } else {
        format!("{}/v1", base_url)
    }
}

/// 解析 FlareSolverr 响应 JSON(错误附带前 200 字符辅助排障)
fn parse_fs_response(raw_text: &str) -> Result<FlareSolverrResponse, EngineError> {
    serde_json::from_str(raw_text).map_err(|e| {
        EngineError::RequestFailed(format!(
            "Failed to parse FlareSolverr response: {} (first 200 chars: {:?})",
            e,
            &raw_text[..raw_text.len().min(200)]
        ))
    })
}

/// 校验 status 并取出 solution:非 ok 报错;solution 缺失报错
fn extract_solution(response: FlareSolverrResponse) -> Result<FlareSolverrSolution, EngineError> {
    if response.status != "ok" {
        error!("FlareSolverr error: {}", response.message);
        return Err(EngineError::RequestFailed(format!(
            "FlareSolverr error: {}",
            response.message
        )));
    }

    response.solution.ok_or_else(|| {
        EngineError::RequestFailed("No solution in FlareSolverr response".to_string())
    })
}

/// 检测 CAPTCHA / bot 检测页特征
fn is_captcha_page(html_content: &str) -> bool {
    html_content.contains("captcha")
        || html_content.contains("CAPTCHA")
        || html_content.contains("unusual traffic")
        || html_content.contains("Our systems have detected")
        || html_content.contains("recaptcha")
        || html_content.contains("verify you are human")
}

/// 组装内部响应:补默认 content-type 头,返回 HTML 内容
fn build_scrape_response(
    solution: FlareSolverrSolution,
    response_time_ms: u64,
) -> InternalScrapeResponse {
    let mut headers = solution.headers.unwrap_or_default();

    // Add content-type if not present
    if !headers.contains_key("content-type") {
        headers.insert("content-type".to_string(), "text/html".to_string());
    }

    // Build response - FlareSolverr returns HTML content
    InternalScrapeResponse {
        js_degraded: false,
        status_code: solution.status,
        content: solution.response,
        content_type: headers
            .get("content-type")
            .cloned()
            .unwrap_or_else(|| "text/html".to_string()),
        screenshot: solution.screenshot,
        headers,
        response_time_ms,
        final_url: None,
        captured_responses: Vec::new(),
    }
}

impl FlareSolverrEngine {
    /// 发送 `request.get` 到 FlareSolverr,取原始文本并解析出 solution
    /// (先取文本便于排查编码问题;长度进 debug 日志)
    async fn send_request(
        &self,
        api_url: &str,
        fs_request: &FlareSolverrRequest,
    ) -> Result<FlareSolverrSolution, EngineError> {
        // Send request to FlareSolverr
        let raw_response = self
            .client
            .post(api_url)
            .json(fs_request)
            .send()
            .await
            .map_err(|e| {
                // 服务不可达/网络抖动属于可重试的基础设施错误,允许 fallback 到下一引擎
                EngineError::RequestFailed(format!("FlareSolverr request failed: {}", e))
            })?;

        // Get raw text first to debug any encoding issues
        let raw_text = raw_response.text().await.map_err(|e| {
            EngineError::RequestFailed(format!("Failed to get response text: {}", e))
        })?;

        debug!("FlareSolverr raw response length: {}", raw_text.len());

        extract_solution(parse_fs_response(&raw_text)?)
    }

    /// CAPTCHA/反爬页拒绝:命中返回 `AntiBotDetected`(可重试,
    /// 允许 router fallback/升级到浏览器引擎)
    fn reject_captcha_page(solution: &FlareSolverrSolution) -> Result<(), EngineError> {
        // Check for CAPTCHA or bot detection pages
        if is_captcha_page(&solution.response) {
            warn!("FlareSolverr returned CAPTCHA/bot detection page");
            // 与 reqwest 路径的同类场景对齐:反爬命中是可重试错误,
            // 允许 router fallback/升级到浏览器引擎
            return Err(EngineError::AntiBotDetected(
                "FlareSolverr blocked by CAPTCHA or bot detection".to_string(),
            ));
        }
        Ok(())
    }

    /// Full 模式支持分数:JS 渲染与反爬保护强项 → 100;
    /// 非 JS 请求对受保护站点仍有用,但静态内容 Reqwest 更快 → 80
    fn full_mode_score(request: &InternalScrapeRequest) -> u8 {
        // FlareSolverr is excellent for JS rendering and anti-bot protection
        if request.needs_js {
            return 100;
        }
        // For non-JS requests, still useful for protected sites
        // But Reqwest would be faster for simple static content
        80
    }

    /// Cdp 模式支持分数(全功能但成本高)
    fn cdp_mode_score(request: &InternalScrapeRequest) -> u8 {
        // 如果需要 TLS 指纹且需要截图,这是最佳选择
        if request.needs_tls_fingerprint && request.needs_screenshot {
            return 100;
        }
        // 如果明确请求使用 Fire Engine
        if request.use_fire_engine {
            return 100;
        }
        // 如果需要截图,但不需要 TLS,Playwright 可能更好,但这个也能做
        if request.needs_screenshot {
            return 80;
        }
        // 如果需要 JS,支持
        if request.needs_js {
            return 90;
        }
        // 如果有交互动作,支持
        if !request.actions.is_empty() {
            return 90;
        }
        // 成本较高,默认优先级低
        40
    }

    /// Tls 模式支持分数(TLS 指纹优先,不支持截图)
    fn tls_mode_score(request: &InternalScrapeRequest) -> u8 {
        // 审查 F15:TLS 模式 scrape 会拒绝截图请求(返回
        // "FireEngineTls does not support screenshots"),评分必须一致返回 0,
        // 否则会被选为候选并以能力拒绝覆盖真实错误。
        if request.needs_screenshot {
            return 0;
        }
        // 如果明确请求使用 Fire Engine (TLS 模式)
        if request.use_fire_engine {
            return 95;
        }
        // 如果需要 TLS 指纹但不需要截图,TLS Engine 是最佳选择
        if request.needs_tls_fingerprint {
            return 90;
        }
        // 如果需要 JS,支持
        if request.needs_js {
            return 60;
        }
        // 如果有交互动作,支持但不是最佳
        if !request.actions.is_empty() {
            return 50;
        }
        // 成本低,速度快,默认优先级高
        70
    }
}

#[async_trait]
impl ScraperEngine for FlareSolverrEngine {
    /// Execute a scraping request using FlareSolverr
    async fn scrape(
        &self,
        request: &InternalScrapeRequest,
    ) -> Result<InternalScrapeResponse, EngineError> {
        if request.method != crate::engines::engine_client::HttpMethod::Get {
            return Err(EngineError::Other("Unsupported HTTP method".to_string()));
        }

        // 引擎层 SSRF 校验(与 handler/router 层独立的纵深防御):
        // FlareSolverr 是外部服务,目标 URL 由它自行解析并跟随重定向,
        // 入口不校验等于完全绕过整条 SSRF 防护链
        crate::engines::validators::validate_url(&request.url)
            .await
            .map_err(|e| EngineError::SsrfProtection(format!("SSRF protection: {}", e)))?;

        // Tls 模式拒绝截图请求(保持原 FireEngineTls 行为)
        if self.config.mode == FlareSolverrMode::Tls && request.needs_screenshot {
            return Err(EngineError::Other(
                "FireEngineTls does not support screenshots".to_string(),
            ));
        }

        let start_time = std::time::Instant::now();

        // Determine proxy to use: request-level override or engine-level default
        let proxy_url = request.proxy.as_ref().or(self.config.proxy_url.as_ref());

        // Prepare custom headers:合并 proxy 信息 + 用户传入的 headers
        // 不再静默丢弃用户 headers
        let custom_headers = merge_custom_headers(self.config.mode, proxy_url, &request.headers);

        let fs_request = build_fs_request(request, self.session_id.clone(), custom_headers);

        // Build the base URL for FlareSolverr API
        // Ensure no double slashes or duplicate /v1
        let api_url = build_api_url(&self.config.url);

        debug!(
            "FlareSolverr request: mode={}, url={}, session={:?}",
            self.config.mode.engine_name(),
            request.url,
            fs_request.session
        );

        // Send request to FlareSolverr
        let solution = self.send_request(&api_url, &fs_request).await?;

        Self::reject_captcha_page(&solution)?;

        let response_time_ms = start_time.elapsed().as_millis() as u64;

        let scrape_response = build_scrape_response(solution, response_time_ms);

        info!(
            "FlareSolverr success: mode={}, status={}, time={}ms, content_length={}",
            self.config.mode.engine_name(),
            scrape_response.status_code,
            response_time_ms,
            scrape_response.content.len()
        );

        Ok(scrape_response)
    }

    /// Calculate support score for the request
    ///
    /// 根据 `mode` 返回不同的优先级分数:
    /// - `Full`:原 FlareSolverrEngine 行为,needs_js=100, default=80
    /// - `Cdp`:原 FireEngineCdp 行为,全功能但成本高
    /// - `Tls`:原 FireEngineTls 行为,TLS 指纹优先,不支持截图
    fn support_score(&self, request: &InternalScrapeRequest) -> u8 {
        if request.method != crate::engines::engine_client::HttpMethod::Get {
            return 0;
        }

        match self.config.mode {
            FlareSolverrMode::Full => Self::full_mode_score(request),
            FlareSolverrMode::Cdp => Self::cdp_mode_score(request),
            FlareSolverrMode::Tls => Self::tls_mode_score(request),
        }
    }

    /// Get engine name
    fn name(&self) -> &'static str {
        self.config.mode.engine_name()
    }

    /// 是否支持 TLS 指纹对抗(根据 mode 返回)
    fn supports_tls_fingerprint(&self) -> bool {
        self.config.mode.supports_tls_fingerprint()
    }

    /// 覆写 MRT,按 mode 区分。
    ///
    /// - `Tls`:15 秒(`tls_seconds`,速度较快)
    /// - `Cdp` / `Full`:30 秒(`cdp_seconds`,涉及完整浏览器)
    ///
    /// 若构造时注入了 `mrt`,则使用注入值;否则按 mode 默认推导。
    /// router 顺序 fallback 路径用 `min(remaining, self.mrt)` 包裹单引擎调用,
    /// 超 MRT 即切下一引擎(瀑布式)。
    fn max_response_time(&self) -> Duration {
        self.mrt()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::engines::engine_client::HttpMethod;

    fn mk_req(url: &str) -> InternalScrapeRequest {
        InternalScrapeRequest {
            url: url.to_string(),
            method: HttpMethod::Get,
            headers: HashMap::new(),
            timeout: Duration::from_secs(30),
            needs_js: false,
            needs_screenshot: false,
            screenshot_config: None,
            mobile: false,
            proxy: None,
            skip_tls_verification: false,
            needs_tls_fingerprint: false,
            use_fire_engine: false,
            actions: Vec::new(),
            body: None,
            sync_wait_ms: 0,
            block_ads: false,
            block_media: false,
            session_id: None,
            wait_for: None,
            needs_mllm: false,
        }
    }

    fn engine() -> FlareSolverrEngine {
        FlareSolverrEngine::with_url(Arc::new(Client::new()), "http://127.0.0.1:8192")
    }

    #[test]
    fn mode_engine_name_maps_each_variant() {
        assert_eq!(FlareSolverrMode::Full.engine_name(), "flaresolverr");
        assert_eq!(FlareSolverrMode::Cdp.engine_name(), "flaresolverr_cdp");
        assert_eq!(FlareSolverrMode::Tls.engine_name(), "flaresolverr_tls");
        assert_eq!(FlareSolverrMode::default(), FlareSolverrMode::Full);
    }

    #[test]
    fn mode_supports_tls_fingerprint() {
        assert!(!FlareSolverrMode::Full.supports_tls_fingerprint());
        assert!(FlareSolverrMode::Cdp.supports_tls_fingerprint());
        assert!(FlareSolverrMode::Tls.supports_tls_fingerprint());
    }

    #[test]
    fn mode_default_mrt_by_variant() {
        assert_eq!(
            FlareSolverrMode::Full.default_mrt(),
            Duration::from_secs(30)
        );
        assert_eq!(FlareSolverrMode::Cdp.default_mrt(), Duration::from_secs(30));
        assert_eq!(FlareSolverrMode::Tls.default_mrt(), Duration::from_secs(15));
    }

    #[test]
    fn validate_flaresolverr_url_accepts_http_https() {
        assert_eq!(
            validate_flaresolverr_url("http://h:1").unwrap(),
            "http://h:1"
        );
        assert_eq!(validate_flaresolverr_url("https://h").unwrap(), "https://h");
    }

    #[test]
    fn validate_flaresolverr_url_rejects_bad_scheme_and_format() {
        assert!(validate_flaresolverr_url("ftp://h").is_err());
        assert!(validate_flaresolverr_url("not a url").is_err());
        assert!(validate_flaresolverr_url("").is_err());
    }

    #[test]
    fn with_url_valid_keeps_url_and_invalid_falls_back() {
        let good = FlareSolverrEngine::with_url(Arc::new(Client::new()), "http://127.0.0.1:8192");
        assert_eq!(good.config.url, "http://127.0.0.1:8192");
        assert_eq!(good.mode(), FlareSolverrMode::Full);
        let bad = FlareSolverrEngine::with_url(Arc::new(Client::new()), "ftp://nope");
        assert_eq!(bad.config.url, FALLBACK_URL);
    }

    #[test]
    fn mode_constructors_set_expected_mode() {
        let c = FlareSolverrEngine::with_cdp_mode_and_url(
            Arc::new(Client::new()),
            "http://127.0.0.1:8192",
            Some("http://proxy:8080"),
        );
        assert_eq!(c.mode(), FlareSolverrMode::Cdp);
        assert_eq!(c.config.proxy_url.as_deref(), Some("http://proxy:8080"));
        assert!(c.supports_tls_fingerprint());

        let t = FlareSolverrEngine::with_tls_mode_and_url(
            Arc::new(Client::new()),
            "http://127.0.0.1:8192",
            None,
        );
        assert_eq!(t.mode(), FlareSolverrMode::Tls);
        assert!(t.supports_tls_fingerprint());
    }

    #[test]
    fn constructors_with_explicit_mrt_override_default() {
        let full = FlareSolverrEngine::with_url_and_mrt(
            Arc::new(Client::new()),
            "http://127.0.0.1:8192",
            Duration::from_secs(7),
            42,
        );
        assert_eq!(full.mrt(), Duration::from_secs(7));
        assert_eq!(full.config.timeout_seconds, 42);

        let cdp = FlareSolverrEngine::with_cdp_mode_url_and_mrt(
            Arc::new(Client::new()),
            "http://127.0.0.1:8192",
            None,
            Duration::from_secs(9),
            30,
        );
        assert_eq!(cdp.mrt(), Duration::from_secs(9));

        let tls = FlareSolverrEngine::with_tls_mode_url_and_mrt(
            Arc::new(Client::new()),
            "http://127.0.0.1:8192",
            None,
            Duration::from_secs(5),
            20,
        );
        assert_eq!(tls.mrt(), Duration::from_secs(5));
        assert_eq!(tls.mode(), FlareSolverrMode::Tls);
    }

    #[test]
    fn mrt_defaults_per_mode_when_not_injected() {
        assert_eq!(
            FlareSolverrEngine::with_url(Arc::new(Client::new()), "http://h:1").mrt(),
            Duration::from_secs(30)
        );
        let tls =
            FlareSolverrEngine::with_tls_mode_and_url(Arc::new(Client::new()), "http://h:1", None);
        assert_eq!(tls.mrt(), Duration::from_secs(15));
    }

    #[test]
    fn builder_fluently_sets_all_fields() {
        let e = FlareSolverrEngine::builder()
            .with_url("http://127.0.0.1:8192")
            .with_timeout(77)
            .with_session("sess-1")
            .with_mode(FlareSolverrMode::Cdp)
            .with_proxy("http://p:1")
            .with_mrt(Duration::from_secs(11))
            .build(Arc::new(Client::new()));
        assert_eq!(e.mode(), FlareSolverrMode::Cdp);
        assert_eq!(e.session_id(), Some("sess-1"));
        assert_eq!(e.config.timeout_seconds, 77);
        assert_eq!(e.config.proxy_url.as_deref(), Some("http://p:1"));
        assert_eq!(e.mrt(), Duration::from_secs(11));
    }

    #[test]
    fn session_id_none_when_unset() {
        assert_eq!(engine().session_id(), None);
    }

    #[test]
    fn api_url_appends_v1_without_duplication() {
        let a = FlareSolverrEngine::with_url(Arc::new(Client::new()), "http://h:1/");
        assert_eq!(a.api_url(), "http://h:1/v1");
        let b = FlareSolverrEngine::with_config(
            Arc::new(Client::new()),
            FlareSolverrConfig {
                url: "http://h:1/v1".to_string(),
                timeout_seconds: 60,
                session_id: None,
                mode: FlareSolverrMode::Full,
                proxy_url: None,
                mrt: None,
            },
        );
        assert_eq!(b.api_url(), "http://h:1/v1");
    }

    #[test]
    fn name_and_max_response_time_and_tls_flag() {
        assert_eq!(engine().name(), "flaresolverr");
        let tls =
            FlareSolverrEngine::with_tls_mode_and_url(Arc::new(Client::new()), "http://h:1", None);
        assert_eq!(tls.name(), "flaresolverr_tls");
        assert_eq!(tls.max_response_time(), Duration::from_secs(15));
    }

    #[test]
    fn support_score_full_mode_branches() {
        let e = FlareSolverrEngine::with_url(Arc::new(Client::new()), "http://h:1");
        let mut post = mk_req("https://example.com");
        post.method = HttpMethod::Post;
        assert_eq!(e.support_score(&post), 0);
        assert_eq!(e.support_score(&mk_req("https://example.com")), 80);
        let mut js = mk_req("https://example.com");
        js.needs_js = true;
        assert_eq!(e.support_score(&js), 100);
    }

    #[test]
    fn support_score_cdp_mode_branches() {
        let e =
            FlareSolverrEngine::with_cdp_mode_and_url(Arc::new(Client::new()), "http://h:1", None);
        let mut tls_shot = mk_req("https://example.com");
        tls_shot.needs_tls_fingerprint = true;
        tls_shot.needs_screenshot = true;
        assert_eq!(e.support_score(&tls_shot), 100);
        let mut fire = mk_req("https://example.com");
        fire.use_fire_engine = true;
        assert_eq!(e.support_score(&fire), 100);
        let mut shot = mk_req("https://example.com");
        shot.needs_screenshot = true;
        assert_eq!(e.support_score(&shot), 80);
        let mut js = mk_req("https://example.com");
        js.needs_js = true;
        assert_eq!(e.support_score(&js), 90);
        assert_eq!(e.support_score(&mk_req("https://example.com")), 40);
    }

    #[test]
    fn support_score_tls_mode_branches() {
        let e =
            FlareSolverrEngine::with_tls_mode_and_url(Arc::new(Client::new()), "http://h:1", None);
        let mut fire = mk_req("https://example.com");
        fire.use_fire_engine = true;
        assert_eq!(e.support_score(&fire), 95);
        let mut tls = mk_req("https://example.com");
        tls.needs_tls_fingerprint = true;
        assert_eq!(e.support_score(&tls), 90);
        let mut js = mk_req("https://example.com");
        js.needs_js = true;
        assert_eq!(e.support_score(&js), 60);
        assert_eq!(e.support_score(&mk_req("https://example.com")), 70);
    }

    // scrape / session 行为测试(本地 axum mock + 公网 IP 字面量 request.url 过 SSRF)

    /// 公网 IP 字面量:SSRF 校验对非私网 IP 无需 DNS,确定性通过。
    const PUBLIC_TARGET: &str = "http://93.184.216.34";

    async fn start_mock(body: String) -> String {
        use axum::http::header::CONTENT_TYPE;
        use axum::routing::post;
        use axum::Router;
        use tokio::net::TcpListener;
        let app = Router::new().route(
            "/v1",
            post(move || {
                let b = body.clone();
                async move { ([(CONTENT_TYPE, "application/json")], b) }
            }),
        );
        let l = TcpListener::bind("127.0.0.1:0").await.expect("bind");
        let addr = l.local_addr().expect("addr");
        tokio::spawn(async move {
            let _ = axum::serve(l, app).await;
        });
        format!("http://{}", addr)
    }

    fn solution_json(response_body: &str) -> String {
        format!(
            r#"{{"status":"ok","message":"","solution":{{"url":"http://x","status":200,"response":"{}","headers":{{"content-type":"text/html"}},"cookies":[],"user_agent":"ua","screenshot":null,"start_timestamp":1,"end_timestamp":2}}}}"#,
            response_body
        )
    }

    #[tokio::test]
    async fn scrape_rejects_non_get() {
        let mut r = mk_req(PUBLIC_TARGET);
        r.method = HttpMethod::Post;
        let e = engine();
        let err = e.scrape(&r).await.expect_err("non-GET must err");
        assert!(matches!(err, EngineError::Other(_)));
    }

    #[tokio::test]
    async fn scrape_tls_mode_rejects_screenshot() {
        let e = FlareSolverrEngine::with_tls_mode_and_url(
            Arc::new(Client::new()),
            "http://127.0.0.1:1",
            None,
        );
        let mut r = mk_req(PUBLIC_TARGET);
        r.needs_screenshot = true;
        let err = e.scrape(&r).await.expect_err("tls+screenshot must err");
        assert!(matches!(err, EngineError::Other(_)));
    }

    #[tokio::test]
    async fn scrape_success_path_returns_solution() {
        let mock = start_mock(solution_json("<html>hello</html>")).await;
        let e = FlareSolverrEngine::with_url(Arc::new(Client::new()), &mock);
        let resp = e.scrape(&mk_req(PUBLIC_TARGET)).await.expect("scrape ok");
        assert_eq!(resp.status_code, 200);
        assert!(resp.content.contains("hello"));
        assert_eq!(resp.content_type, "text/html");
    }

    #[tokio::test]
    async fn scrape_error_status_maps_to_request_failed() {
        let mock = start_mock(r#"{"status":"error","message":"boom"}"#.to_string()).await;
        let e = FlareSolverrEngine::with_url(Arc::new(Client::new()), &mock);
        let err = e
            .scrape(&mk_req(PUBLIC_TARGET))
            .await
            .expect_err("error status");
        assert!(matches!(err, EngineError::RequestFailed(_)));
    }

    #[tokio::test]
    async fn scrape_captcha_page_maps_to_antibot() {
        let mock = start_mock(solution_json(
            "this page has a CAPTCHA to verify you are human",
        ))
        .await;
        let e = FlareSolverrEngine::with_url(Arc::new(Client::new()), &mock);
        let err = e.scrape(&mk_req(PUBLIC_TARGET)).await.expect_err("captcha");
        assert!(matches!(err, EngineError::AntiBotDetected(_)));
    }

    #[tokio::test]
    async fn scrape_ok_but_no_solution_is_request_failed() {
        let mock = start_mock(r#"{"status":"ok","message":""}"#.to_string()).await;
        let e = FlareSolverrEngine::with_url(Arc::new(Client::new()), &mock);
        let err = e
            .scrape(&mk_req(PUBLIC_TARGET))
            .await
            .expect_err("no solution");
        assert!(matches!(err, EngineError::RequestFailed(_)));
    }

    #[tokio::test]
    async fn scrape_invalid_json_is_request_failed() {
        let mock = start_mock("not-json".to_string()).await;
        let e = FlareSolverrEngine::with_url(Arc::new(Client::new()), &mock);
        let err = e
            .scrape(&mk_req(PUBLIC_TARGET))
            .await
            .expect_err("bad json");
        assert!(matches!(err, EngineError::RequestFailed(_)));
    }

    #[tokio::test]
    async fn create_session_ok_sets_id() {
        let mock =
            start_mock(r#"{"status":"ok","message":"","session":"abc-123"}"#.to_string()).await;
        let mut e = FlareSolverrEngine::with_url(Arc::new(Client::new()), &mock);
        let sid = e.create_session().await.expect("create session");
        assert_eq!(sid, "abc-123");
        assert_eq!(e.session_id(), Some("abc-123"));
    }

    #[tokio::test]
    async fn create_session_no_id_is_err() {
        let mock = start_mock(r#"{"status":"ok","message":""}"#.to_string()).await;
        let mut e = FlareSolverrEngine::with_url(Arc::new(Client::new()), &mock);
        assert!(e.create_session().await.is_err());
    }

    #[tokio::test]
    async fn create_session_error_status_is_err() {
        let mock = start_mock(r#"{"status":"error","message":"nope"}"#.to_string()).await;
        let mut e = FlareSolverrEngine::with_url(Arc::new(Client::new()), &mock);
        assert!(e.create_session().await.is_err());
    }

    #[tokio::test]
    async fn destroy_session_ok_clears_id() {
        let mock = start_mock(r#"{"status":"ok","message":""}"#.to_string()).await;
        let mut e = FlareSolverrEngine::builder()
            .with_url(&mock)
            .with_session("s1")
            .build(Arc::new(Client::new()));
        e.destroy_session("s1").await.expect("destroy ok");
        assert_eq!(e.session_id(), None);
    }

    #[tokio::test]
    async fn destroy_session_error_status_is_err() {
        let mock = start_mock(r#"{"status":"error","message":"x"}"#.to_string()).await;
        let mut e = FlareSolverrEngine::with_url(Arc::new(Client::new()), &mock);
        assert!(e.destroy_session("s1").await.is_err());
    }
}