spider 2.48.13

A web crawler and scraper, building blocks for data curation workloads.
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
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
use crate::compact_str::CompactString;
use crate::features::chrome_common::RequestInterceptConfiguration;
pub use crate::features::chrome_common::{
    AuthChallengeResponse, AuthChallengeResponseResponse, AutomationScripts, AutomationScriptsMap,
    CaptureScreenshotFormat, CaptureScreenshotParams, ClipViewport, ExecutionScripts,
    ExecutionScriptsMap, ScreenShotConfig, ScreenshotParams, Viewport, WaitFor, WaitForDelay,
    WaitForIdleNetwork, WaitForSelector, WebAutomation,
};
pub use crate::features::gemini_common::GeminiConfigs;
pub use crate::features::openai_common::GPTConfigs;
#[cfg(feature = "search")]
pub use crate::features::search::{
    SearchError, SearchOptions, SearchResult, SearchResults, TimeRange,
};
pub use crate::features::webdriver_common::{WebDriverBrowser, WebDriverConfig};
use crate::utils::get_domain_from_url;
use crate::utils::BasicCachePolicy;
use crate::website::CronType;
use reqwest::header::{AsHeaderName, HeaderMap, HeaderName, HeaderValue, IntoHeaderName};
use std::net::IpAddr;
use std::sync::Arc;
use std::time::Duration;

#[cfg(feature = "chrome")]
pub use spider_fingerprint::Fingerprint;

/// Redirect policy configuration for request
#[derive(Debug, Default, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum RedirectPolicy {
    #[default]
    #[cfg_attr(
        feature = "serde",
        serde(alias = "Loose", alias = "loose", alias = "LOOSE",)
    )]
    /// A loose policy that allows all request up to the redirect limit.
    Loose,
    #[cfg_attr(
        feature = "serde",
        serde(alias = "Strict", alias = "strict", alias = "STRICT",)
    )]
    /// A strict policy only allowing request that match the domain set for crawling.
    Strict,
    #[cfg_attr(
        feature = "serde",
        serde(alias = "None", alias = "none", alias = "NONE",)
    )]
    /// Prevent all redirects.
    None,
}

#[cfg(not(feature = "regex"))]
/// Allow list normal matching paths.
pub type AllowList = Vec<CompactString>;

#[cfg(feature = "regex")]
/// Allow list regex.
pub type AllowList = Box<regex::RegexSet>;

/// Whitelist or Blacklist
#[derive(Debug, Default, Clone)]
#[cfg_attr(not(feature = "regex"), derive(PartialEq, Eq))]
pub struct AllowListSet(pub AllowList);

#[cfg(feature = "chrome")]
/// Track the events made via chrome.
#[derive(Debug, PartialEq, Eq, Clone, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ChromeEventTracker {
    /// Track the responses.
    pub responses: bool,
    /// Track the requests.
    pub requests: bool,
    /// Track the changes between web automation.
    pub automation: bool,
}

#[cfg(feature = "chrome")]
impl ChromeEventTracker {
    /// Create a new chrome event tracker
    pub fn new(requests: bool, responses: bool) -> Self {
        ChromeEventTracker {
            requests,
            responses,
            automation: true,
        }
    }
}

#[cfg(feature = "sitemap")]
#[derive(Debug, Default)]
/// Determine if the sitemap modified to the whitelist.
pub struct SitemapWhitelistChanges {
    /// Added the default sitemap.xml whitelist.
    pub added_default: bool,
    /// Added the custom whitelist path.
    pub added_custom: bool,
}

#[cfg(feature = "sitemap")]
impl SitemapWhitelistChanges {
    /// Was the whitelist modified?
    pub(crate) fn modified(&self) -> bool {
        self.added_default || self.added_custom
    }
}

/// Determine allow proxy
#[derive(Debug, Default, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ProxyIgnore {
    /// Chrome proxy.
    Chrome,
    /// HTTP proxy.
    Http,
    #[default]
    /// Do not ignore
    No,
}

/// The networking proxy to use.
#[derive(Debug, Default, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct RequestProxy {
    /// The proxy address.
    pub addr: String,
    /// Ignore the proxy when running a request type.
    pub ignore: ProxyIgnore,
}

/// The protocol used to communicate with a backend.
#[cfg(feature = "parallel_backends")]
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum BackendProtocol {
    /// Chrome DevTools Protocol over WebSocket.
    Cdp,
    /// WebDriver (W3C) over HTTP.
    WebDriver,
}

/// The engine type for a parallel crawl backend.
#[cfg(feature = "parallel_backends")]
#[derive(Debug, Default, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum BackendEngine {
    #[default]
    /// LightPanda — communicates via CDP (same protocol as Chrome).
    LightPanda,
    /// Servo — communicates via WebDriver protocol.
    Servo,
    /// A custom backend. Set `protocol` on [`BackendEndpoint`] to tell
    /// spider whether to use CDP or WebDriver to communicate with it.
    Custom,
}

/// A parallel crawl backend endpoint.
///
/// Each backend can run either **remotely** (connect to a running instance via
/// `endpoint`) or **locally** (spider manages the engine process via
/// `binary_path`). Set `endpoint` for remote mode, `binary_path` for local.
#[cfg(feature = "parallel_backends")]
#[derive(Debug, Default, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(default))]
pub struct BackendEndpoint {
    /// The browser engine to use.
    pub engine: BackendEngine,
    /// Remote endpoint URL. For LightPanda: a CDP WebSocket URL
    /// (e.g. `"ws://127.0.0.1:9222"`). For Servo: a WebDriver HTTP URL
    /// (e.g. `"http://localhost:4444"`). When set, the engine is assumed to
    /// be already running at this address.
    pub endpoint: Option<String>,
    /// Path to the engine binary for local mode. When set (and `endpoint` is
    /// `None`), spider will spawn and manage the engine process. Uses PATH
    /// lookup if empty string.
    pub binary_path: Option<String>,
    /// Explicit protocol override. When `None`, inferred from `engine`:
    /// `LightPanda` → CDP, `Servo` → WebDriver, `Custom` → **required**.
    /// For custom backends, set this to tell spider how to communicate.
    pub protocol: Option<BackendProtocol>,
    /// Per-backend proxy address. When set, this backend routes its outbound
    /// requests through the given proxy (e.g. `"socks5://proxy1:1080"`,
    /// `"http://proxy2:8080"`). Overrides the global `ProxyRotator` for this
    /// backend. For CDP backends, creates an isolated browser context with
    /// the proxy. For WebDriver backends, sets the proxy capability.
    pub proxy: Option<String>,
}

/// Configuration for parallel crawl backends.
///
/// When enabled, races alternative browser engines (LightPanda, Servo) alongside
/// the primary crawl path. The best HTML response wins.
#[cfg(feature = "parallel_backends")]
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(default))]
pub struct ParallelBackendsConfig {
    /// Alternative backends to race against the primary crawl.
    pub backends: Vec<BackendEndpoint>,
    /// Grace period (ms) after first response to wait for better results.
    /// Allows slower backends to finish if they produce higher quality HTML.
    /// Default: 500.
    pub grace_period_ms: u64,
    /// Master switch. Default: `true` (enabled when config is present).
    pub enabled: bool,
    /// Quality score threshold (0–100). If the first response scores at or
    /// above this value, accept it immediately without waiting for the grace
    /// period. Default: 80.
    pub fast_accept_threshold: u16,
    /// Maximum consecutive errors before auto-disabling a backend for
    /// the remainder of the crawl. Default: 10.
    pub max_consecutive_errors: u16,
    /// Timeout (ms) for the initial TCP/WebSocket connection to a backend.
    /// Separate from `request_timeout` so that down backends fail fast
    /// without affecting navigation/fetch timeouts. Default: 5000 (5s).
    pub connect_timeout_ms: u64,
    /// Skip backend racing when the primary response has a binary
    /// `Content-Type` (image/*, audio/*, video/*, font/*, application/pdf,
    /// etc.). There is no HTML quality variance for binary resources.
    /// Default: `true`.
    pub skip_binary_content_types: bool,
    /// Maximum concurrent backend sessions across all URLs. Prevents memory
    /// spikes on large crawls. `0` means unlimited. Default: 8.
    pub max_concurrent_sessions: usize,
    /// Additional URL extensions to skip backend racing for, on top of the
    /// built-in asset list (images, fonts, videos, etc.). Case-insensitive.
    /// Example: `["xml", "rss"]`.
    pub skip_extensions: Vec<CompactString>,
}

#[cfg(feature = "parallel_backends")]
impl Default for ParallelBackendsConfig {
    fn default() -> Self {
        Self {
            backends: Vec::new(),
            grace_period_ms: 500,
            enabled: true,
            fast_accept_threshold: 80,
            max_consecutive_errors: 10,
            connect_timeout_ms: 5000,
            skip_binary_content_types: true,
            max_concurrent_sessions: 8,
            skip_extensions: Vec::new(),
        }
    }
}

/// User-configurable antibot detection patterns. Any match triggers `AntiBotTech::Custom`.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(default))]
pub struct CustomAntibotPatterns {
    /// Body substring patterns (matched against response bodies < 30KB).
    pub body: Vec<CompactString>,
    /// URL substring patterns.
    pub url: Vec<CompactString>,
    /// Header keys whose presence triggers antibot detection.
    pub header_keys: Vec<CompactString>,
}

/// Structure to configure `Website` crawler
/// ```rust
/// use spider::website::Website;
/// let mut website: Website = Website::new("https://choosealicense.com");
/// website.configuration.blacklist_url.insert(Default::default()).push("https://choosealicense.com/licenses/".to_string().into());
/// website.configuration.respect_robots_txt = true;
/// website.configuration.subdomains = true;
/// website.configuration.tld = true;
/// ```
#[derive(Debug, Default, Clone)]
#[cfg_attr(
    all(
        not(feature = "regex"),
        not(feature = "openai"),
        not(feature = "cache_openai"),
        not(feature = "gemini"),
        not(feature = "cache_gemini")
    ),
    derive(PartialEq)
)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(default))]
pub struct Configuration {
    /// Respect robots.txt file and not scrape not allowed files. This may slow down crawls if robots.txt file has a delay included.
    pub respect_robots_txt: bool,
    /// Allow sub-domains.
    pub subdomains: bool,
    /// Allow all tlds for domain.
    pub tld: bool,
    /// The max timeout for the crawl.
    pub crawl_timeout: Option<Duration>,
    /// Preserve the HTTP host header from being included.
    pub preserve_host_header: bool,
    /// List of pages to not crawl. [optional: regex pattern matching]
    pub blacklist_url: Option<Vec<CompactString>>,
    /// List of pages to only crawl. [optional: regex pattern matching]
    pub whitelist_url: Option<Vec<CompactString>>,
    /// User-Agent for request.
    pub user_agent: Option<Box<CompactString>>,
    /// Polite crawling delay in milli seconds.
    pub delay: u64,
    /// Request max timeout per page. By default the request times out in 15s. Set to None to disable.
    pub request_timeout: Option<Duration>,
    /// Use HTTP2 for connection. Enable if you know the website has http2 support.
    pub http2_prior_knowledge: bool,
    /// Use proxy list for performing network request.
    pub proxies: Option<Vec<RequestProxy>>,
    /// Headers to include with request.
    pub headers: Option<Box<SerializableHeaderMap>>,
    #[cfg(feature = "sitemap")]
    /// Include a sitemap in response of the crawl.
    pub sitemap_url: Option<Box<CompactString>>,
    #[cfg(feature = "sitemap")]
    /// Prevent including the sitemap links with the crawl.
    pub ignore_sitemap: bool,
    /// The max redirections allowed for request.
    pub redirect_limit: usize,
    /// The redirect policy type to use.
    pub redirect_policy: RedirectPolicy,
    #[cfg(feature = "cookies")]
    /// Cookie string to use for network requests ex: "foo=bar; Domain=blog.spider"
    pub cookie_str: String,
    #[cfg(feature = "wreq")]
    /// The type of request emulation. This does nothing without the flag `sync` enabled.
    pub emulation: Option<wreq_util::Emulation>,
    #[cfg(feature = "cron")]
    /// Cron string to perform crawls - use <https://crontab.guru/> to help generate a valid cron for needs.
    pub cron_str: String,
    #[cfg(feature = "cron")]
    /// The type of cron to run either crawl or scrape.
    pub cron_type: CronType,
    /// The max depth to crawl for a website. Defaults to 25 to help prevent infinite recursion.
    pub depth: usize,
    /// The depth to crawl pertaining to the root.
    pub depth_distance: usize,
    /// Use stealth mode for requests.
    pub stealth_mode: spider_fingerprint::configs::Tier,
    /// Configure the viewport for chrome and viewport headers.
    pub viewport: Option<Viewport>,
    /// Crawl budget for the paths. This helps prevent crawling extra pages and limiting the amount.
    pub budget: Option<hashbrown::HashMap<case_insensitive_string::CaseInsensitiveString, u32>>,
    /// If wild card budgeting is found for the website.
    pub wild_card_budgeting: bool,
    /// External domains to include case-insensitive.
    pub external_domains_caseless:
        Arc<hashbrown::HashSet<case_insensitive_string::CaseInsensitiveString>>,
    /// Collect all the resources found on the page.
    pub full_resources: bool,
    /// Dangerously accept invalid certficates.
    pub accept_invalid_certs: bool,
    /// The auth challenge response. The 'chrome_intercept' flag is also required in order to intercept the response.
    pub auth_challenge_response: Option<AuthChallengeResponse>,
    /// The OpenAI configs to use to help drive the chrome browser. This does nothing without the 'openai' flag.
    pub openai_config: Option<Box<GPTConfigs>>,
    /// The Gemini configs to use to help drive the chrome browser. This does nothing without the 'gemini' flag.
    pub gemini_config: Option<Box<GeminiConfigs>>,
    /// Remote multimodal automation config (vision + LLM-driven steps).
    /// Requires the `agent` feature for full functionality, uses stub type otherwise.
    pub remote_multimodal: Option<Box<crate::features::automation::RemoteMultimodalConfigs>>,
    /// Use a shared queue strategy when crawling. This can scale workloads evenly that do not need priority.
    pub shared_queue: bool,
    /// Return the page links in the subscription channels. This does nothing without the flag `sync` enabled.
    pub return_page_links: bool,
    /// Retry count to attempt to swap proxies etc.
    pub retry: u8,
    /// Custom antibot detection patterns. When set, these are matched in addition
    /// to the built-in patterns. Any match triggers `AntiBotTech::Custom`.
    pub custom_antibot: Option<CustomAntibotPatterns>,
    /// Skip spawning a control thread that can pause, start, and shutdown the crawl.
    pub no_control_thread: bool,
    /// The blacklist urls.
    blacklist: AllowListSet,
    /// The whitelist urls.
    whitelist: AllowListSet,
    /// Crawl budget for the paths. This helps prevent crawling extra pages and limiting the amount.
    pub(crate) inner_budget:
        Option<hashbrown::HashMap<case_insensitive_string::CaseInsensitiveString, u32>>,
    /// Expect only to handle HTML to save on resources. This mainly only blocks the crawling and returning of resources from the server.
    pub only_html: bool,
    /// The concurrency limits to apply.
    pub concurrency_limit: Option<usize>,
    /// Normalize the html de-deplucating the content.
    pub normalize: bool,
    /// Share the state of the crawl requires the 'disk' feature flag.
    pub shared: bool,
    /// Modify the headers to act like a real-browser
    pub modify_headers: bool,
    /// Modify the HTTP client headers only to act like a real-browser
    pub modify_http_client_headers: bool,
    /// Cache the page following HTTP caching rules.
    #[cfg(any(
        feature = "cache_request",
        feature = "chrome",
        feature = "chrome_remote_cache"
    ))]
    pub cache: bool,
    /// Skip browser rendering entirely if cached response exists.
    /// When enabled, returns cached HTML directly without launching Chrome.
    #[cfg(any(
        feature = "cache_request",
        feature = "chrome",
        feature = "chrome_remote_cache"
    ))]
    pub cache_skip_browser: bool,
    #[cfg(feature = "chrome")]
    /// Enable or disable service workers. Enabled by default.
    pub service_worker_enabled: bool,
    #[cfg(feature = "chrome")]
    /// Overrides default host system timezone with the specified one.
    #[cfg(feature = "chrome")]
    pub timezone_id: Option<Box<String>>,
    /// Overrides default host system locale with the specified one.
    #[cfg(feature = "chrome")]
    pub locale: Option<Box<String>>,
    /// Set a custom script to eval on each new document.
    #[cfg(feature = "chrome")]
    pub evaluate_on_new_document: Option<Box<String>>,
    #[cfg(feature = "chrome")]
    /// Dismiss dialogs.
    pub dismiss_dialogs: Option<bool>,
    #[cfg(feature = "chrome")]
    /// Wait for options for the page.
    pub wait_for: Option<WaitFor>,
    #[cfg(feature = "chrome")]
    /// Take a screenshot of the page.
    pub screenshot: Option<ScreenShotConfig>,
    #[cfg(feature = "chrome")]
    /// Track the events made via chrome.
    pub track_events: Option<ChromeEventTracker>,
    #[cfg(feature = "chrome")]
    /// Setup fingerprint ID on each document. This does nothing without the flag `chrome` enabled.
    pub fingerprint: Fingerprint,
    #[cfg(feature = "chrome")]
    /// The chrome connection url. Useful for targeting different headless instances. Defaults to using the env CHROME_URL.
    pub chrome_connection_url: Option<String>,
    /// Scripts to execute for individual pages, the full path of the url is required for an exact match. This is useful for running one off JS on pages like performing custom login actions.
    #[cfg(feature = "chrome")]
    pub execution_scripts: Option<ExecutionScripts>,
    /// Web automation scripts to run up to a duration of 60 seconds.
    #[cfg(feature = "chrome")]
    pub automation_scripts: Option<AutomationScripts>,
    /// Setup network interception for request. This does nothing without the flag `chrome_intercept` enabled.
    #[cfg(feature = "chrome")]
    pub chrome_intercept: RequestInterceptConfiguration,
    /// The referer to use.
    pub referer: Option<String>,
    /// Determine the max bytes per page.
    pub max_page_bytes: Option<f64>,
    /// Determine the max bytes per browser context.
    pub max_bytes_allowed: Option<u64>,
    #[cfg(feature = "chrome")]
    /// Disables log domain, prevents further log entries from being reported to the client. This does nothing without the flag `chrome` enabled.
    pub disable_log: bool,
    #[cfg(feature = "chrome")]
    /// Automatic locale and timezone handling via third party. This does nothing without the flag `chrome` enabled.
    pub auto_geolocation: bool,
    /// The cache policy to use.
    pub cache_policy: Option<BasicCachePolicy>,
    #[cfg(feature = "chrome")]
    /// Enables bypassing CSP. This does nothing without the flag `chrome` enabled.
    pub bypass_csp: bool,
    /// Bind the connections only on the network interface.
    pub network_interface: Option<String>,
    /// Bind to a local IP Address.
    pub local_address: Option<IpAddr>,
    /// The default http connect timeout
    pub default_http_connect_timeout: Option<Duration>,
    /// The default http read timeout
    pub default_http_read_timeout: Option<Duration>,
    #[cfg(feature = "webdriver")]
    /// WebDriver configuration for browser automation. This does nothing without the `webdriver` flag enabled.
    pub webdriver_config: Option<Box<WebDriverConfig>>,
    #[cfg(feature = "search")]
    /// Search provider configuration for web search integration. This does nothing without the `search` flag enabled.
    pub search_config: Option<Box<SearchConfig>>,
    #[cfg(feature = "spider_cloud")]
    /// Spider Cloud config. See <https://spider.cloud>.
    pub spider_cloud: Option<Box<SpiderCloudConfig>>,
    #[cfg(all(feature = "spider_cloud", feature = "chrome"))]
    /// Spider Browser Cloud config for remote CDP via `wss://browser.spider.cloud`.
    pub spider_browser: Option<Box<SpiderBrowserConfig>>,
    #[cfg(feature = "hedge")]
    /// Hedged request configuration for work-stealing on slow requests.
    /// When enabled, fires a duplicate request on a different proxy after a delay.
    pub hedge: Option<crate::utils::hedge::HedgeConfig>,
    #[cfg(feature = "auto_throttle")]
    /// Latency-based auto-throttle configuration. When enabled, dynamically
    /// adjusts per-domain crawl delay based on measured server response time.
    pub auto_throttle: Option<crate::utils::auto_throttle::AutoThrottleConfig>,
    #[cfg(feature = "etag_cache")]
    /// Enable ETag / conditional request caching. When true, stores ETag and
    /// Last-Modified headers from responses and sends If-None-Match /
    /// If-Modified-Since on subsequent requests to the same URL, allowing
    /// servers to respond with lightweight 304 Not Modified.
    pub etag_cache: bool,
    #[cfg(feature = "warc")]
    /// WARC output configuration. When set, the crawl writes a WARC 1.1 file
    /// containing all fetched pages as `response` records.
    pub warc: Option<crate::utils::warc::WarcConfig>,
    #[cfg(feature = "parallel_backends")]
    /// Parallel crawl backend configuration. Race LightPanda / Servo alongside
    /// the primary crawl path. Requires the `parallel_backends` feature.
    pub parallel_backends: Option<ParallelBackendsConfig>,
}

#[derive(Default, Debug, Clone, PartialEq, Eq)]
/// Serializable HTTP headers.
pub struct SerializableHeaderMap(pub HeaderMap);

impl SerializableHeaderMap {
    /// Innter HeaderMap.
    pub fn inner(&self) -> &HeaderMap {
        &self.0
    }
    /// Returns true if the map contains a value for the specified key.
    pub fn contains_key<K>(&self, key: K) -> bool
    where
        K: AsHeaderName,
    {
        self.0.contains_key(key)
    }
    /// Inserts a key-value pair into the map.
    pub fn insert<K>(
        &mut self,
        key: K,
        val: reqwest::header::HeaderValue,
    ) -> Option<reqwest::header::HeaderValue>
    where
        K: IntoHeaderName,
    {
        self.0.insert(key, val)
    }
    /// Extend a `HeaderMap` with the contents of another `HeaderMap`.
    pub fn extend<I>(&mut self, iter: I)
    where
        I: IntoIterator<Item = (Option<HeaderName>, HeaderValue)>,
    {
        self.0.extend(iter);
    }
}

/// Get a cloned copy of the `Referer` header as a `String` (if it exists and is valid UTF-8).
pub fn get_referer(header_map: &Option<Box<SerializableHeaderMap>>) -> Option<String> {
    match header_map {
        Some(header_map) => {
            header_map
                .0
                .get(crate::client::header::REFERER) // Retrieves the "Referer" HeaderValue if it exists
                .and_then(|value| value.to_str().ok()) // &str from HeaderValue
                .map(String::from) // Convert &str to String (owned)
        }
        _ => None,
    }
}

impl From<HeaderMap> for SerializableHeaderMap {
    fn from(header_map: HeaderMap) -> Self {
        SerializableHeaderMap(header_map)
    }
}

#[cfg(feature = "serde")]
impl serde::Serialize for SerializableHeaderMap {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let map: std::collections::BTreeMap<String, String> = self
            .0
            .iter()
            .map(|(k, v)| (k.to_string(), v.to_str().unwrap_or("").to_string()))
            .collect();
        map.serialize(serializer)
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for SerializableHeaderMap {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        use reqwest::header::{HeaderName, HeaderValue};
        use std::collections::BTreeMap;
        let map: BTreeMap<String, String> = BTreeMap::deserialize(deserializer)?;
        let mut headers = HeaderMap::with_capacity(map.len());
        for (k, v) in map {
            let key = HeaderName::from_bytes(k.as_bytes()).map_err(serde::de::Error::custom)?;
            let value = HeaderValue::from_str(&v).map_err(serde::de::Error::custom)?;
            headers.insert(key, value);
        }
        Ok(SerializableHeaderMap(headers))
    }
}

#[cfg(feature = "serde")]
impl serde::Serialize for AllowListSet {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        #[cfg(not(feature = "regex"))]
        {
            self.0.serialize(serializer)
        }

        #[cfg(feature = "regex")]
        {
            self.0
                .patterns()
                .iter()
                .collect::<Vec<&String>>()
                .serialize(serializer)
        }
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for AllowListSet {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        #[cfg(not(feature = "regex"))]
        {
            let vec = Vec::<CompactString>::deserialize(deserializer)?;
            Ok(AllowListSet(vec))
        }

        #[cfg(feature = "regex")]
        {
            let patterns = Vec::<String>::deserialize(deserializer)?;
            let regex_set = regex::RegexSet::new(&patterns).map_err(serde::de::Error::custom)?;
            Ok(AllowListSet(regex_set.into()))
        }
    }
}

/// Get the user agent from the top agent list randomly.
#[cfg(feature = "ua_generator")]
pub fn get_ua(chrome: bool) -> &'static str {
    if chrome {
        ua_generator::ua::spoof_chrome_ua()
    } else {
        ua_generator::ua::spoof_ua()
    }
}

/// Get the user agent via cargo package + version.
#[cfg(not(feature = "ua_generator"))]
pub fn get_ua(_chrome: bool) -> &'static str {
    use std::env;

    lazy_static! {
        static ref AGENT: &'static str =
            concat!(env!("CARGO_PKG_NAME"), '/', env!("CARGO_PKG_VERSION"));
    };

    AGENT.as_ref()
}

impl Configuration {
    /// Represents crawl configuration for a website.
    #[cfg(not(feature = "chrome"))]
    pub fn new() -> Self {
        Self {
            delay: 0,
            depth: 25,
            redirect_limit: 7,
            request_timeout: Some(Duration::from_secs(120)),
            only_html: true,
            modify_headers: true,
            ..Default::default()
        }
    }

    /// Represents crawl configuration for a website.
    #[cfg(feature = "chrome")]
    pub fn new() -> Self {
        Self {
            delay: 0,
            depth: 25,
            redirect_limit: 7,
            request_timeout: Some(Duration::from_secs(120)),
            chrome_intercept: RequestInterceptConfiguration::new(cfg!(
                feature = "chrome_intercept"
            )),
            user_agent: Some(Box::new(get_ua(true).into())),
            only_html: true,
            cache: true,
            modify_headers: true,
            service_worker_enabled: true,
            fingerprint: Fingerprint::Basic,
            auto_geolocation: false,
            ..Default::default()
        }
    }

    /// Build a `RemoteMultimodalEngine` from `RemoteMultimodalConfigs`.
    /// Requires the `agent` feature.
    #[cfg(feature = "agent")]
    pub fn build_remote_multimodal_engine(
        &self,
    ) -> Option<crate::features::automation::RemoteMultimodalEngine> {
        let cfgs = self.remote_multimodal.as_ref()?;
        let sem = cfgs
            .concurrency_limit
            .filter(|&n| n > 0)
            .map(|n| std::sync::Arc::new(tokio::sync::Semaphore::new(n)));

        #[allow(unused_mut)]
        let mut engine = crate::features::automation::RemoteMultimodalEngine::new(
            cfgs.api_url.clone(),
            cfgs.model_name.clone(),
            cfgs.system_prompt.clone(),
        )
        .with_api_key(cfgs.api_key.as_deref())
        .with_system_prompt_extra(cfgs.system_prompt_extra.as_deref())
        .with_user_message_extra(cfgs.user_message_extra.as_deref())
        .with_remote_multimodal_config(cfgs.cfg.clone())
        .with_prompt_url_gate(cfgs.prompt_url_gate.clone())
        .with_vision_model(cfgs.vision_model.clone())
        .with_text_model(cfgs.text_model.clone())
        .with_vision_route_mode(cfgs.vision_route_mode)
        .with_chrome_ai(cfgs.use_chrome_ai)
        .with_semaphore(sem)
        .to_owned();

        #[cfg(feature = "agent_skills")]
        if let Some(ref registry) = cfgs.skill_registry {
            engine.with_skill_registry(Some(registry.clone()));
        }

        // Build per-round complexity router from model pool (3+ models required)
        let model_pool = cfgs.model_pool.clone();
        if model_pool.len() >= 3 {
            let model_names: Vec<&str> =
                model_pool.iter().map(|ep| ep.model_name.as_str()).collect();
            let policy = crate::features::automation::auto_policy(&model_names);
            engine.model_router = Some(crate::features::automation::ModelRouter::with_policy(
                policy,
            ));
        }
        engine.model_pool = model_pool;

        Some(engine)
    }

    /// Determine if the agent should be set to a Chrome Agent.
    #[cfg(not(feature = "chrome"))]
    pub(crate) fn only_chrome_agent(&self) -> bool {
        false
    }

    /// Determine if the agent should be set to a Chrome Agent.
    #[cfg(feature = "chrome")]
    pub(crate) fn only_chrome_agent(&self) -> bool {
        self.chrome_connection_url.is_some()
            || self.wait_for.is_some()
            || self.chrome_intercept.enabled
            || self.stealth_mode.stealth()
            || self.fingerprint.valid()
    }

    #[cfg(feature = "regex")]
    /// Compile the regex for the blacklist.
    pub fn get_blacklist(&self) -> Box<regex::RegexSet> {
        match &self.blacklist_url {
            Some(blacklist) => match regex::RegexSet::new(&**blacklist) {
                Ok(s) => Box::new(s),
                _ => Default::default(),
            },
            _ => Default::default(),
        }
    }

    #[cfg(not(feature = "regex"))]
    /// Handle the blacklist options.
    pub fn get_blacklist(&self) -> AllowList {
        match &self.blacklist_url {
            Some(blacklist) => blacklist.to_owned(),
            _ => Default::default(),
        }
    }

    /// Set the blacklist
    pub(crate) fn set_blacklist(&mut self) {
        self.blacklist = AllowListSet(self.get_blacklist());
    }

    /// Set the whitelist
    pub fn set_whitelist(&mut self) {
        self.whitelist = AllowListSet(self.get_whitelist());
    }

    /// Configure the allow list.
    pub fn configure_allowlist(&mut self) {
        self.set_whitelist();
        self.set_blacklist();
    }

    /// Get the blacklist compiled.
    pub fn get_blacklist_compiled(&self) -> &AllowList {
        &self.blacklist.0
    }

    /// Setup the budget for crawling.
    pub fn configure_budget(&mut self) {
        self.inner_budget.clone_from(&self.budget);
    }

    /// Get the whitelist compiled.
    pub fn get_whitelist_compiled(&self) -> &AllowList {
        &self.whitelist.0
    }

    #[cfg(feature = "regex")]
    /// Compile the regex for the whitelist.
    pub fn get_whitelist(&self) -> Box<regex::RegexSet> {
        match &self.whitelist_url {
            Some(whitelist) => match regex::RegexSet::new(&**whitelist) {
                Ok(s) => Box::new(s),
                _ => Default::default(),
            },
            _ => Default::default(),
        }
    }

    #[cfg(not(feature = "regex"))]
    /// Handle the whitelist options.
    pub fn get_whitelist(&self) -> AllowList {
        match &self.whitelist_url {
            Some(whitelist) => whitelist.to_owned(),
            _ => Default::default(),
        }
    }

    #[cfg(feature = "sitemap")]
    /// Add sitemap paths to the whitelist and track what was added.
    pub fn add_sitemap_to_whitelist(&mut self) -> SitemapWhitelistChanges {
        let mut changes = SitemapWhitelistChanges::default();

        if self.ignore_sitemap && self.whitelist_url.is_none() {
            return changes;
        }

        if let Some(list) = self.whitelist_url.as_mut() {
            if list.is_empty() {
                return changes;
            }

            let default = CompactString::from("sitemap.xml");

            if !list.contains(&default) {
                list.push(default);
                changes.added_default = true;
            }

            if let Some(custom) = &self.sitemap_url {
                if !list.contains(custom) {
                    list.push(*custom.clone());
                    changes.added_custom = true;
                }
            }
        }

        changes
    }

    #[cfg(feature = "sitemap")]
    /// Revert any changes made to the whitelist by `add_sitemap_to_whitelist`.
    pub fn remove_sitemap_from_whitelist(&mut self, changes: SitemapWhitelistChanges) {
        if let Some(list) = self.whitelist_url.as_mut() {
            if changes.added_default {
                let default = CompactString::from("sitemap.xml");
                if let Some(pos) = list.iter().position(|s| s == default) {
                    list.remove(pos);
                }
            }
            if changes.added_custom {
                if let Some(custom) = &self.sitemap_url {
                    if let Some(pos) = list.iter().position(|s| *s == **custom) {
                        list.remove(pos);
                    }
                }
            }
            if list.is_empty() {
                self.whitelist_url = None;
            }
        }
    }

    /// Respect robots.txt file.
    pub fn with_respect_robots_txt(&mut self, respect_robots_txt: bool) -> &mut Self {
        self.respect_robots_txt = respect_robots_txt;
        self
    }

    /// Include subdomains detection.
    pub fn with_subdomains(&mut self, subdomains: bool) -> &mut Self {
        self.subdomains = subdomains;
        self
    }

    /// Bypass CSP protection detection. This does nothing without the feat flag `chrome` enabled.
    #[cfg(feature = "chrome")]
    pub fn with_csp_bypass(&mut self, enabled: bool) -> &mut Self {
        self.bypass_csp = enabled;
        self
    }

    /// Bypass CSP protection detection. This does nothing without the feat flag `chrome` enabled.
    #[cfg(not(feature = "chrome"))]
    pub fn with_csp_bypass(&mut self, _enabled: bool) -> &mut Self {
        self
    }

    /// Bind the connections only on the network interface.
    pub fn with_network_interface(&mut self, network_interface: Option<String>) -> &mut Self {
        self.network_interface = network_interface;
        self
    }

    /// Bind to a local IP Address.
    pub fn with_local_address(&mut self, local_address: Option<IpAddr>) -> &mut Self {
        self.local_address = local_address;
        self
    }

    /// Include tld detection.
    pub fn with_tld(&mut self, tld: bool) -> &mut Self {
        self.tld = tld;
        self
    }

    /// The max duration for the crawl. This is useful when websites use a robots.txt with long durations and throttle the timeout removing the full concurrency.
    pub fn with_crawl_timeout(&mut self, crawl_timeout: Option<Duration>) -> &mut Self {
        self.crawl_timeout = crawl_timeout;
        self
    }

    /// Delay between request as ms.
    pub fn with_delay(&mut self, delay: u64) -> &mut Self {
        self.delay = delay;
        self
    }

    /// Only use HTTP/2.
    pub fn with_http2_prior_knowledge(&mut self, http2_prior_knowledge: bool) -> &mut Self {
        self.http2_prior_knowledge = http2_prior_knowledge;
        self
    }

    /// Max time to wait for request. By default request times out in 15s. Set to None to disable.
    pub fn with_request_timeout(&mut self, request_timeout: Option<Duration>) -> &mut Self {
        match request_timeout {
            Some(timeout) => self.request_timeout = Some(timeout),
            _ => self.request_timeout = None,
        };

        self
    }

    #[cfg(feature = "sitemap")]
    /// Set the sitemap url. This does nothing without the `sitemap` feature flag.
    pub fn with_sitemap(&mut self, sitemap_url: Option<&str>) -> &mut Self {
        match sitemap_url {
            Some(sitemap_url) => {
                self.sitemap_url = Some(CompactString::new(sitemap_url.to_string()).into())
            }
            _ => self.sitemap_url = None,
        };
        self
    }

    #[cfg(not(feature = "sitemap"))]
    /// Set the sitemap url. This does nothing without the `sitemap` feature flag.
    pub fn with_sitemap(&mut self, _sitemap_url: Option<&str>) -> &mut Self {
        self
    }

    #[cfg(feature = "sitemap")]
    /// Ignore the sitemap when crawling. This method does nothing if the `sitemap` is not enabled.
    pub fn with_ignore_sitemap(&mut self, ignore_sitemap: bool) -> &mut Self {
        self.ignore_sitemap = ignore_sitemap;
        self
    }

    #[cfg(not(feature = "sitemap"))]
    /// Ignore the sitemap when crawling. This method does nothing if the `sitemap` is not enabled.
    pub fn with_ignore_sitemap(&mut self, _ignore_sitemap: bool) -> &mut Self {
        self
    }

    /// Add user agent to request.
    pub fn with_user_agent(&mut self, user_agent: Option<&str>) -> &mut Self {
        match user_agent {
            Some(agent) => self.user_agent = Some(CompactString::new(agent).into()),
            _ => self.user_agent = None,
        };
        self
    }

    /// Preserve the HOST header.
    pub fn with_preserve_host_header(&mut self, preserve: bool) -> &mut Self {
        self.preserve_host_header = preserve;
        self
    }

    /// Use a remote multimodal model to drive browser automation.
    /// Requires the `agent` feature.
    #[cfg(feature = "agent")]
    pub fn with_remote_multimodal(
        &mut self,
        remote_multimodal: Option<crate::features::automation::RemoteMultimodalConfigs>,
    ) -> &mut Self {
        self.remote_multimodal = remote_multimodal.map(Box::new);
        self
    }

    /// Use a remote multimodal model to drive browser automation.
    /// When the `agent` feature is not enabled, this uses a stub type.
    #[cfg(not(feature = "agent"))]
    pub fn with_remote_multimodal(
        &mut self,
        remote_multimodal: Option<crate::features::automation::RemoteMultimodalConfigs>,
    ) -> &mut Self {
        self.remote_multimodal = remote_multimodal.map(Box::new);
        self
    }

    #[cfg(not(feature = "openai"))]
    /// The OpenAI configs to use to drive the browser. This method does nothing if the `openai` is not enabled.
    pub fn with_openai(&mut self, _openai_config: Option<GPTConfigs>) -> &mut Self {
        self
    }

    /// The OpenAI configs to use to drive the browser. This method does nothing if the `openai` is not enabled.
    #[cfg(feature = "openai")]
    pub fn with_openai(&mut self, openai_config: Option<GPTConfigs>) -> &mut Self {
        match openai_config {
            Some(openai_config) => self.openai_config = Some(Box::new(openai_config)),
            _ => self.openai_config = None,
        };
        self
    }

    #[cfg(not(feature = "gemini"))]
    /// The Gemini configs to use to drive the browser. This method does nothing if the `gemini` is not enabled.
    pub fn with_gemini(&mut self, _gemini_config: Option<GeminiConfigs>) -> &mut Self {
        self
    }

    /// The Gemini configs to use to drive the browser. This method does nothing if the `gemini` is not enabled.
    #[cfg(feature = "gemini")]
    pub fn with_gemini(&mut self, gemini_config: Option<GeminiConfigs>) -> &mut Self {
        match gemini_config {
            Some(gemini_config) => self.gemini_config = Some(Box::new(gemini_config)),
            _ => self.gemini_config = None,
        };
        self
    }

    #[cfg(feature = "cookies")]
    /// Cookie string to use in request. This does nothing without the `cookies` flag enabled.
    pub fn with_cookies(&mut self, cookie_str: &str) -> &mut Self {
        self.cookie_str = cookie_str.into();
        self
    }

    #[cfg(not(feature = "cookies"))]
    /// Cookie string to use in request. This does nothing without the `cookies` flag enabled.
    pub fn with_cookies(&mut self, _cookie_str: &str) -> &mut Self {
        self
    }

    #[cfg(feature = "chrome")]
    /// Set custom fingerprint ID for request. This does nothing without the `chrome` flag enabled.
    pub fn with_fingerprint(&mut self, fingerprint: bool) -> &mut Self {
        if fingerprint {
            self.fingerprint = Fingerprint::Basic;
        } else {
            self.fingerprint = Fingerprint::None;
        }
        self
    }

    #[cfg(feature = "chrome")]
    /// Set custom fingerprint ID for request. This does nothing without the `chrome` flag enabled.
    pub fn with_fingerprint_advanced(&mut self, fingerprint: Fingerprint) -> &mut Self {
        self.fingerprint = fingerprint;
        self
    }

    #[cfg(not(feature = "chrome"))]
    /// Set custom fingerprint ID for request. This does nothing without the `chrome` flag enabled.
    pub fn with_fingerprint(&mut self, _fingerprint: bool) -> &mut Self {
        self
    }

    /// Use proxies for request.
    pub fn with_proxies(&mut self, proxies: Option<Vec<String>>) -> &mut Self {
        self.proxies = proxies.map(|p| {
            p.iter()
                .map(|addr| RequestProxy {
                    addr: addr.to_owned(),
                    ..Default::default()
                })
                .collect::<Vec<RequestProxy>>()
        });
        self
    }

    /// Use proxies for request with control between chrome and http.
    pub fn with_proxies_direct(&mut self, proxies: Option<Vec<RequestProxy>>) -> &mut Self {
        self.proxies = proxies;
        self
    }

    /// Use a shared semaphore to evenly handle workloads. The default is false.
    pub fn with_shared_queue(&mut self, shared_queue: bool) -> &mut Self {
        self.shared_queue = shared_queue;
        self
    }

    /// Add blacklist urls to ignore.
    pub fn with_blacklist_url<T>(&mut self, blacklist_url: Option<Vec<T>>) -> &mut Self
    where
        Vec<CompactString>: From<Vec<T>>,
    {
        match blacklist_url {
            Some(p) => self.blacklist_url = Some(p.into()),
            _ => self.blacklist_url = None,
        };
        self
    }

    /// Add whitelist urls to allow.
    pub fn with_whitelist_url<T>(&mut self, whitelist_url: Option<Vec<T>>) -> &mut Self
    where
        Vec<CompactString>: From<Vec<T>>,
    {
        match whitelist_url {
            Some(p) => self.whitelist_url = Some(p.into()),
            _ => self.whitelist_url = None,
        };
        self
    }

    /// Return the links found on the page in the channel subscriptions. This method does nothing if the `decentralized` is enabled.
    pub fn with_return_page_links(&mut self, return_page_links: bool) -> &mut Self {
        self.return_page_links = return_page_links;
        self
    }

    /// Set HTTP headers for request using [reqwest::header::HeaderMap](https://docs.rs/reqwest/latest/reqwest/header/struct.HeaderMap.html).
    pub fn with_headers(&mut self, headers: Option<reqwest::header::HeaderMap>) -> &mut Self {
        match headers {
            Some(m) => self.headers = Some(SerializableHeaderMap::from(m).into()),
            _ => self.headers = None,
        };
        self
    }

    /// Set the max redirects allowed for request.
    pub fn with_redirect_limit(&mut self, redirect_limit: usize) -> &mut Self {
        self.redirect_limit = redirect_limit;
        self
    }

    /// Set the redirect policy to use.
    pub fn with_redirect_policy(&mut self, policy: RedirectPolicy) -> &mut Self {
        self.redirect_policy = policy;
        self
    }

    /// Add a referer (mis-spelling) to the request.
    pub fn with_referer(&mut self, referer: Option<String>) -> &mut Self {
        self.referer = referer;
        self
    }

    /// Add a referer to the request.
    pub fn with_referrer(&mut self, referer: Option<String>) -> &mut Self {
        self.referer = referer;
        self
    }

    /// Determine whether to collect all the resources found on pages.
    pub fn with_full_resources(&mut self, full_resources: bool) -> &mut Self {
        self.full_resources = full_resources;
        self
    }

    /// Determine whether to dismiss dialogs. This method does nothing if the `chrome` is enabled.
    #[cfg(feature = "chrome")]
    pub fn with_dismiss_dialogs(&mut self, dismiss_dialogs: bool) -> &mut Self {
        self.dismiss_dialogs = Some(dismiss_dialogs);
        self
    }

    /// Determine whether to dismiss dialogs. This method does nothing if the `chrome` is enabled.
    #[cfg(not(feature = "chrome"))]
    pub fn with_dismiss_dialogs(&mut self, _dismiss_dialogs: bool) -> &mut Self {
        self
    }

    /// Set the request emuluation. This method does nothing if the `wreq` flag is not enabled.
    #[cfg(feature = "wreq")]
    pub fn with_emulation(&mut self, emulation: Option<wreq_util::Emulation>) -> &mut Self {
        self.emulation = emulation;
        self
    }

    #[cfg(feature = "cron")]
    /// Setup cron jobs to run. This does nothing without the `cron` flag enabled.
    pub fn with_cron(&mut self, cron_str: &str, cron_type: CronType) -> &mut Self {
        self.cron_str = cron_str.into();
        self.cron_type = cron_type;
        self
    }

    #[cfg(not(feature = "cron"))]
    /// Setup cron jobs to run. This does nothing without the `cron` flag enabled.
    pub fn with_cron(&mut self, _cron_str: &str, _cron_type: CronType) -> &mut Self {
        self
    }

    /// Set a crawl page limit. If the value is 0 there is no limit.
    pub fn with_limit(&mut self, limit: u32) -> &mut Self {
        self.with_budget(Some(hashbrown::HashMap::from([("*", limit)])));
        self
    }

    /// Set the concurrency limits. If you set the value to None to use the default limits using the system CPU cors * n.
    pub fn with_concurrency_limit(&mut self, limit: Option<usize>) -> &mut Self {
        self.concurrency_limit = limit;
        self
    }

    #[cfg(feature = "chrome")]
    /// Set the authentiation challenge response. This does nothing without the feat flag `chrome` enabled.
    pub fn with_auth_challenge_response(
        &mut self,
        auth_challenge_response: Option<AuthChallengeResponse>,
    ) -> &mut Self {
        self.auth_challenge_response = auth_challenge_response;
        self
    }

    #[cfg(feature = "chrome")]
    /// Set a custom script to evaluate on new document creation. This does nothing without the feat flag `chrome` enabled.
    pub fn with_evaluate_on_new_document(
        &mut self,
        evaluate_on_new_document: Option<Box<String>>,
    ) -> &mut Self {
        self.evaluate_on_new_document = evaluate_on_new_document;
        self
    }

    #[cfg(not(feature = "chrome"))]
    /// Set a custom script to evaluate on new document creation. This does nothing without the feat flag `chrome` enabled.
    pub fn with_evaluate_on_new_document(
        &mut self,
        _evaluate_on_new_document: Option<Box<String>>,
    ) -> &mut Self {
        self
    }

    #[cfg(not(feature = "chrome"))]
    /// Set the authentiation challenge response. This does nothing without the feat flag `chrome` enabled.
    pub fn with_auth_challenge_response(
        &mut self,
        _auth_challenge_response: Option<AuthChallengeResponse>,
    ) -> &mut Self {
        self
    }

    /// Set a crawl depth limit. If the value is 0 there is no limit.
    pub fn with_depth(&mut self, depth: usize) -> &mut Self {
        self.depth = depth;
        self
    }

    #[cfg(any(feature = "cache_request", feature = "chrome_remote_cache"))]
    /// Cache the page following HTTP rules. This method does nothing if the `cache` feature is not enabled.
    pub fn with_caching(&mut self, cache: bool) -> &mut Self {
        self.cache = cache;
        self
    }

    #[cfg(not(any(feature = "cache_request", feature = "chrome_remote_cache")))]
    /// Cache the page following HTTP rules. This method does nothing if the `cache` feature is not enabled.
    pub fn with_caching(&mut self, _cache: bool) -> &mut Self {
        self
    }

    #[cfg(any(feature = "cache_request", feature = "chrome_remote_cache"))]
    /// Skip browser rendering entirely if cached response exists.
    /// When enabled with caching, returns cached HTML directly without launching Chrome.
    /// This is useful for performance when you only need the cached content.
    pub fn with_cache_skip_browser(&mut self, skip: bool) -> &mut Self {
        self.cache_skip_browser = skip;
        self
    }

    #[cfg(not(any(feature = "cache_request", feature = "chrome_remote_cache")))]
    /// Skip browser rendering entirely if cached response exists.
    /// This method does nothing if the cache features are not enabled.
    pub fn with_cache_skip_browser(&mut self, _skip: bool) -> &mut Self {
        self
    }

    #[cfg(feature = "chrome")]
    /// Enable or disable Service Workers. This method does nothing if the `chrome` feature is not enabled.
    pub fn with_service_worker_enabled(&mut self, enabled: bool) -> &mut Self {
        self.service_worker_enabled = enabled;
        self
    }

    #[cfg(not(feature = "chrome"))]
    /// Enable or disable Service Workers. This method does nothing if the `chrome` feature is not enabled.
    pub fn with_service_worker_enabled(&mut self, _enabled: bool) -> &mut Self {
        self
    }

    /// Automatically setup geo-location configurations when using a proxy. This method does nothing if the `chrome` feature is not enabled.
    #[cfg(not(feature = "chrome"))]
    pub fn with_auto_geolocation(&mut self, _enabled: bool) -> &mut Self {
        self
    }

    /// Automatically setup geo-location configurations when using a proxy. This method does nothing if the `chrome` feature is not enabled.
    #[cfg(feature = "chrome")]
    pub fn with_auto_geolocation(&mut self, enabled: bool) -> &mut Self {
        self.auto_geolocation = enabled;
        self
    }

    /// Set the retry limit for request. Set the value to 0 for no retries. The default is 0.
    pub fn with_retry(&mut self, retry: u8) -> &mut Self {
        self.retry = retry;
        self
    }

    /// The default http connect timeout.
    pub fn with_default_http_connect_timeout(
        &mut self,
        default_http_connect_timeout: Option<Duration>,
    ) -> &mut Self {
        self.default_http_connect_timeout = default_http_connect_timeout;
        self
    }

    /// The default http read timeout.
    pub fn with_default_http_read_timeout(
        &mut self,
        default_http_read_timeout: Option<Duration>,
    ) -> &mut Self {
        self.default_http_read_timeout = default_http_read_timeout;
        self
    }

    /// Skip setting up a control thread for pause, start, and shutdown programmatic handling. This does nothing without the 'control' flag enabled.
    pub fn with_no_control_thread(&mut self, no_control_thread: bool) -> &mut Self {
        self.no_control_thread = no_control_thread;
        self
    }

    /// Configures the viewport of the browser, which defaults to 800x600. This method does nothing if the 'chrome' feature is not enabled.
    pub fn with_viewport(&mut self, viewport: Option<crate::configuration::Viewport>) -> &mut Self {
        self.viewport = viewport.map(|vp| vp);
        self
    }

    #[cfg(feature = "chrome")]
    /// Use stealth mode for the request. This does nothing without the `chrome` flag enabled.
    pub fn with_stealth(&mut self, stealth_mode: bool) -> &mut Self {
        if stealth_mode {
            self.stealth_mode = spider_fingerprint::configs::Tier::Basic;
        } else {
            self.stealth_mode = spider_fingerprint::configs::Tier::None;
        }
        self
    }

    #[cfg(feature = "chrome")]
    /// Use stealth mode for the request. This does nothing without the `chrome` flag enabled.
    pub fn with_stealth_advanced(
        &mut self,
        stealth_mode: spider_fingerprint::configs::Tier,
    ) -> &mut Self {
        self.stealth_mode = stealth_mode;
        self
    }

    #[cfg(not(feature = "chrome"))]
    /// Use stealth mode for the request. This does nothing without the `chrome` flag enabled.
    pub fn with_stealth(&mut self, _stealth_mode: bool) -> &mut Self {
        self
    }

    #[cfg(feature = "chrome")]
    /// Wait for network request to be idle within a time frame period (500ms no network connections). This does nothing without the `chrome` flag enabled.
    pub fn with_wait_for_idle_network(
        &mut self,
        wait_for_idle_network: Option<WaitForIdleNetwork>,
    ) -> &mut Self {
        match self.wait_for.as_mut() {
            Some(wait_for) => wait_for.idle_network = wait_for_idle_network,
            _ => {
                let mut wait_for = WaitFor::default();
                wait_for.idle_network = wait_for_idle_network;
                self.wait_for = Some(wait_for);
            }
        }
        self
    }

    #[cfg(feature = "chrome")]
    /// Wait for network request with a max timeout. This does nothing without the `chrome` flag enabled.
    pub fn with_wait_for_idle_network0(
        &mut self,
        wait_for_idle_network0: Option<WaitForIdleNetwork>,
    ) -> &mut Self {
        match self.wait_for.as_mut() {
            Some(wait_for) => wait_for.idle_network0 = wait_for_idle_network0,
            _ => {
                let mut wait_for = WaitFor::default();
                wait_for.idle_network0 = wait_for_idle_network0;
                self.wait_for = Some(wait_for);
            }
        }
        self
    }

    #[cfg(feature = "chrome")]
    /// Wait for network to be almost idle with a max timeout. This does nothing without the `chrome` flag enabled.
    pub fn with_wait_for_almost_idle_network0(
        &mut self,
        wait_for_almost_idle_network0: Option<WaitForIdleNetwork>,
    ) -> &mut Self {
        match self.wait_for.as_mut() {
            Some(wait_for) => wait_for.almost_idle_network0 = wait_for_almost_idle_network0,
            _ => {
                let mut wait_for = WaitFor::default();
                wait_for.almost_idle_network0 = wait_for_almost_idle_network0;
                self.wait_for = Some(wait_for);
            }
        }
        self
    }

    #[cfg(not(feature = "chrome"))]
    /// Wait for network to be almost idle with a max timeout. This does nothing without the `chrome` flag enabled.
    pub fn with_wait_for_almost_idle_network0(
        &mut self,
        _wait_for_almost_idle_network0: Option<WaitForIdleNetwork>,
    ) -> &mut Self {
        self
    }

    #[cfg(not(feature = "chrome"))]
    /// Wait for network request with a max timeout. This does nothing without the `chrome` flag enabled.
    pub fn with_wait_for_idle_network0(
        &mut self,
        _wait_for_idle_network0: Option<WaitForIdleNetwork>,
    ) -> &mut Self {
        self
    }

    #[cfg(not(feature = "chrome"))]
    /// Wait for idle network request. This method does nothing if the `chrome` feature is not enabled.
    pub fn with_wait_for_idle_network(
        &mut self,
        _wait_for_idle_network: Option<WaitForIdleNetwork>,
    ) -> &mut Self {
        self
    }

    #[cfg(feature = "chrome")]
    /// Wait for idle dom mutations for target element. This method does nothing if the [chrome] feature is not enabled.
    pub fn with_wait_for_idle_dom(
        &mut self,
        wait_for_idle_dom: Option<WaitForSelector>,
    ) -> &mut Self {
        match self.wait_for.as_mut() {
            Some(wait_for) => wait_for.dom = wait_for_idle_dom,
            _ => {
                let mut wait_for = WaitFor::default();
                wait_for.dom = wait_for_idle_dom;
                self.wait_for = Some(wait_for);
            }
        }
        self
    }

    #[cfg(not(feature = "chrome"))]
    /// Wait for idle dom mutations for target element. This method does nothing if the `chrome` feature is not enabled.
    pub fn with_wait_for_idle_dom(
        &mut self,
        _wait_for_idle_dom: Option<WaitForSelector>,
    ) -> &mut Self {
        self
    }

    #[cfg(feature = "chrome")]
    /// Wait for a selector. This method does nothing if the `chrome` feature is not enabled.
    pub fn with_wait_for_selector(
        &mut self,
        wait_for_selector: Option<WaitForSelector>,
    ) -> &mut Self {
        match self.wait_for.as_mut() {
            Some(wait_for) => wait_for.selector = wait_for_selector,
            _ => {
                let mut wait_for = WaitFor::default();
                wait_for.selector = wait_for_selector;
                self.wait_for = Some(wait_for);
            }
        }
        self
    }

    #[cfg(not(feature = "chrome"))]
    /// Wait for a selector. This method does nothing if the `chrome` feature is not enabled.
    pub fn with_wait_for_selector(
        &mut self,
        _wait_for_selector: Option<WaitForSelector>,
    ) -> &mut Self {
        self
    }

    #[cfg(feature = "chrome")]
    /// Wait for with delay. Should only be used for testing. This method does nothing if the 'chrome' feature is not enabled.
    pub fn with_wait_for_delay(&mut self, wait_for_delay: Option<WaitForDelay>) -> &mut Self {
        match self.wait_for.as_mut() {
            Some(wait_for) => wait_for.delay = wait_for_delay,
            _ => {
                let mut wait_for = WaitFor::default();
                wait_for.delay = wait_for_delay;
                self.wait_for = Some(wait_for);
            }
        }
        self
    }

    #[cfg(not(feature = "chrome"))]
    /// Wait for with delay. Should only be used for testing. This method does nothing if the 'chrome' feature is not enabled.
    pub fn with_wait_for_delay(&mut self, _wait_for_delay: Option<WaitForDelay>) -> &mut Self {
        self
    }

    #[cfg(feature = "chrome_intercept")]
    /// Use request intercept for the request to only allow content that matches the host. If the content is from a 3rd party it needs to be part of our include list. This method does nothing if the `chrome_intercept` is not enabled.
    pub fn with_chrome_intercept(
        &mut self,
        chrome_intercept: RequestInterceptConfiguration,
        url: &Option<Box<url::Url>>,
    ) -> &mut Self {
        self.chrome_intercept = chrome_intercept;
        self.chrome_intercept.setup_intercept_manager(url);
        self
    }

    #[cfg(not(feature = "chrome_intercept"))]
    /// Use request intercept for the request to only allow content required for the page that matches the host. If the content is from a 3rd party it needs to be part of our include list. This method does nothing if the `chrome_intercept` is not enabled.
    pub fn with_chrome_intercept(
        &mut self,
        _chrome_intercept: RequestInterceptConfiguration,
        _url: &Option<Box<url::Url>>,
    ) -> &mut Self {
        self
    }

    #[cfg(feature = "chrome")]
    /// Set the connection url for the chrome instance. This method does nothing if the `chrome` is not enabled.
    pub fn with_chrome_connection(&mut self, chrome_connection_url: Option<String>) -> &mut Self {
        self.chrome_connection_url = chrome_connection_url;
        self
    }

    #[cfg(not(feature = "chrome"))]
    /// Set the connection url for the chrome instance. This method does nothing if the `chrome` is not enabled.
    pub fn with_chrome_connection(&mut self, _chrome_connection_url: Option<String>) -> &mut Self {
        self
    }

    #[cfg(not(feature = "chrome"))]
    /// Set JS to run on certain pages. This method does nothing if the `chrome` is not enabled.
    pub fn with_execution_scripts(
        &mut self,
        _execution_scripts: Option<ExecutionScriptsMap>,
    ) -> &mut Self {
        self
    }

    #[cfg(feature = "chrome")]
    /// Set JS to run on certain pages. This method does nothing if the `chrome` is not enabled.
    pub fn with_execution_scripts(
        &mut self,
        execution_scripts: Option<ExecutionScriptsMap>,
    ) -> &mut Self {
        self.execution_scripts =
            crate::features::chrome_common::convert_to_trie_execution_scripts(&execution_scripts);
        self
    }

    #[cfg(not(feature = "chrome"))]
    /// Run web automated actions on certain pages. This method does nothing if the `chrome` is not enabled.
    pub fn with_automation_scripts(
        &mut self,
        _automation_scripts: Option<AutomationScriptsMap>,
    ) -> &mut Self {
        self
    }

    #[cfg(feature = "chrome")]
    /// Run web automated actions on certain pages. This method does nothing if the `chrome` is not enabled.
    pub fn with_automation_scripts(
        &mut self,
        automation_scripts: Option<AutomationScriptsMap>,
    ) -> &mut Self {
        self.automation_scripts =
            crate::features::chrome_common::convert_to_trie_automation_scripts(&automation_scripts);
        self
    }

    /// Set a crawl budget per path with levels support /a/b/c or for all paths with "*". This does nothing without the `budget` flag enabled.
    pub fn with_budget(&mut self, budget: Option<hashbrown::HashMap<&str, u32>>) -> &mut Self {
        self.budget = match budget {
            Some(budget) => {
                let mut crawl_budget: hashbrown::HashMap<
                    case_insensitive_string::CaseInsensitiveString,
                    u32,
                > = hashbrown::HashMap::new();

                for b in budget.into_iter() {
                    crawl_budget.insert(
                        case_insensitive_string::CaseInsensitiveString::from(b.0),
                        b.1,
                    );
                }

                Some(crawl_budget)
            }
            _ => None,
        };
        self
    }

    /// Group external domains to treat the crawl as one. If None is passed this will clear all prior domains.
    pub fn with_external_domains<'a, 'b>(
        &mut self,
        external_domains: Option<impl Iterator<Item = String> + 'a>,
    ) -> &mut Self {
        match external_domains {
            Some(external_domains) => {
                self.external_domains_caseless = external_domains
                    .into_iter()
                    .filter_map(|d| {
                        if d == "*" {
                            Some("*".into())
                        } else {
                            let host = get_domain_from_url(&d);

                            if !host.is_empty() {
                                Some(host.into())
                            } else {
                                None
                            }
                        }
                    })
                    .collect::<hashbrown::HashSet<case_insensitive_string::CaseInsensitiveString>>()
                    .into();
            }
            _ => self.external_domains_caseless = Default::default(),
        }

        self
    }

    /// Dangerously accept invalid certificates - this should be used as a last resort.
    pub fn with_danger_accept_invalid_certs(&mut self, accept_invalid_certs: bool) -> &mut Self {
        self.accept_invalid_certs = accept_invalid_certs;
        self
    }

    /// Normalize the content de-duplicating trailing slash pages and other pages that can be duplicated. This may initially show the link in your links_visited or subscription calls but, the following links will not be crawled.
    pub fn with_normalize(&mut self, normalize: bool) -> &mut Self {
        self.normalize = normalize;
        self
    }

    #[cfg(not(feature = "disk"))]
    /// Store all the links found on the disk to share the state. This does nothing without the `disk` flag enabled.
    pub fn with_shared_state(&mut self, _shared: bool) -> &mut Self {
        self
    }

    /// Store all the links found on the disk to share the state. This does nothing without the `disk` flag enabled.
    #[cfg(feature = "disk")]
    pub fn with_shared_state(&mut self, shared: bool) -> &mut Self {
        self.shared = shared;
        self
    }

    #[cfg(not(feature = "chrome"))]
    /// Overrides default host system timezone with the specified one. This does nothing without the `chrome` flag enabled.
    pub fn with_timezone_id(&mut self, _timezone_id: Option<String>) -> &mut Self {
        self
    }

    #[cfg(feature = "chrome")]
    /// Overrides default host system timezone with the specified one. This does nothing without the `chrome` flag enabled.
    pub fn with_timezone_id(&mut self, timezone_id: Option<String>) -> &mut Self {
        self.timezone_id = timezone_id.map(|timezone_id| timezone_id.into());
        self
    }

    #[cfg(not(feature = "chrome"))]
    /// Overrides default host system locale with the specified one. This does nothing without the `chrome` flag enabled.
    pub fn with_locale(&mut self, _locale: Option<String>) -> &mut Self {
        self
    }

    #[cfg(feature = "chrome")]
    /// Overrides default host system locale with the specified one. This does nothing without the `chrome` flag enabled.
    pub fn with_locale(&mut self, locale: Option<String>) -> &mut Self {
        self.locale = locale.map(|locale| locale.into());
        self
    }

    #[cfg(feature = "chrome")]
    /// Track the events made via chrome.
    pub fn with_event_tracker(&mut self, track_events: Option<ChromeEventTracker>) -> &mut Self {
        self.track_events = track_events;
        self
    }

    /// Set the chrome screenshot configuration. This does nothing without the `chrome` flag enabled.
    #[cfg(not(feature = "chrome"))]
    pub fn with_screenshot(&mut self, _screenshot_config: Option<ScreenShotConfig>) -> &mut Self {
        self
    }

    /// Set the chrome screenshot configuration. This does nothing without the `chrome` flag enabled.
    #[cfg(feature = "chrome")]
    pub fn with_screenshot(&mut self, screenshot_config: Option<ScreenShotConfig>) -> &mut Self {
        self.screenshot = screenshot_config;
        self
    }

    /// Set the max amount of bytes to collect per page. This method does nothing if the `chrome` is not enabled.
    pub fn with_max_page_bytes(&mut self, max_page_bytes: Option<f64>) -> &mut Self {
        self.max_page_bytes = max_page_bytes;
        self
    }

    /// Set the max amount of bytes to collected for the browser context. This method does nothing if the `chrome` is not enabled.
    pub fn with_max_bytes_allowed(&mut self, max_bytes_allowed: Option<u64>) -> &mut Self {
        self.max_bytes_allowed = max_bytes_allowed;
        self
    }

    /// Block assets from loading from the network.
    pub fn with_block_assets(&mut self, only_html: bool) -> &mut Self {
        self.only_html = only_html;
        self
    }

    /// Modify the headers to mimic a real browser.
    pub fn with_modify_headers(&mut self, modify_headers: bool) -> &mut Self {
        self.modify_headers = modify_headers;
        self
    }

    /// Modify the HTTP client headers to mimic a real browser.
    pub fn with_modify_http_client_headers(
        &mut self,
        modify_http_client_headers: bool,
    ) -> &mut Self {
        self.modify_http_client_headers = modify_http_client_headers;
        self
    }

    /// Set the cache policy.
    pub fn with_cache_policy(&mut self, cache_policy: Option<BasicCachePolicy>) -> &mut Self {
        self.cache_policy = cache_policy;
        self
    }

    #[cfg(feature = "webdriver")]
    /// Set the WebDriver configuration. This does nothing without the `webdriver` flag enabled.
    pub fn with_webdriver_config(
        &mut self,
        webdriver_config: Option<WebDriverConfig>,
    ) -> &mut Self {
        self.webdriver_config = webdriver_config.map(Box::new);
        self
    }

    #[cfg(not(feature = "webdriver"))]
    /// Set the WebDriver configuration. This does nothing without the `webdriver` flag enabled.
    pub fn with_webdriver_config(
        &mut self,
        _webdriver_config: Option<WebDriverConfig>,
    ) -> &mut Self {
        self
    }

    /// Get the cache option to use for the run. This does nothing without the 'cache_request' feature.
    #[cfg(any(feature = "cache_request", feature = "chrome_remote_cache"))]
    pub(crate) fn get_cache_options(&self) -> Option<crate::utils::CacheOptions> {
        use crate::utils::CacheOptions;
        if !self.cache {
            return None;
        }
        let auth_token = self
            .headers
            .as_ref()
            .and_then(|headers| {
                headers
                    .0
                    .get("authorization")
                    .or_else(|| headers.0.get("Authorization"))
            })
            .map(|s| s.to_owned());

        // When using in-memory cache (cache_mem), auto-enable skip_browser
        // since the cached HTML was already rendered by a prior Chrome crawl
        // and re-rendering through Chrome is redundant. The browser only
        // launches when the cache has no hit for the requested page.
        #[cfg(feature = "cache_mem")]
        let skip_browser = true;
        #[cfg(not(feature = "cache_mem"))]
        let skip_browser = self.cache_skip_browser;

        match auth_token {
            Some(token) if !token.is_empty() => {
                if let Ok(token_str) = token.to_str() {
                    if skip_browser {
                        Some(CacheOptions::SkipBrowserAuthorized(token_str.into()))
                    } else {
                        Some(CacheOptions::Authorized(token_str.into()))
                    }
                } else if skip_browser {
                    Some(CacheOptions::SkipBrowser)
                } else {
                    Some(CacheOptions::Yes)
                }
            }
            _ => {
                if skip_browser {
                    Some(CacheOptions::SkipBrowser)
                } else {
                    Some(CacheOptions::Yes)
                }
            }
        }
    }

    /// Get the cache option to use for the run. This does nothing without the 'cache_request' feature.
    #[cfg(all(
        feature = "chrome",
        not(any(feature = "cache_request", feature = "chrome_remote_cache"))
    ))]
    pub(crate) fn get_cache_options(&self) -> Option<crate::utils::CacheOptions> {
        None
    }

    /// Get the cache option to use for the run when chrome/cache features are disabled.
    #[cfg(not(any(
        feature = "cache_request",
        feature = "chrome_remote_cache",
        feature = "chrome"
    )))]
    #[allow(dead_code)]
    pub(crate) fn get_cache_options(&self) -> Option<crate::utils::CacheOptions> {
        None
    }

    /// Build the website configuration when using with_builder.
    pub fn build(&self) -> Self {
        self.to_owned()
    }

    #[cfg(feature = "search")]
    /// Configure web search integration. This does nothing without the `search` flag enabled.
    pub fn with_search_config(&mut self, search_config: Option<SearchConfig>) -> &mut Self {
        self.search_config = search_config.map(Box::new);
        self
    }

    #[cfg(not(feature = "search"))]
    /// Configure web search integration. This does nothing without the `search` flag enabled.
    pub fn with_search_config(&mut self, _search_config: Option<()>) -> &mut Self {
        self
    }

    /// Set a [spider.cloud](https://spider.cloud) API key (Proxy mode).
    #[cfg(feature = "spider_cloud")]
    pub fn with_spider_cloud(&mut self, api_key: &str) -> &mut Self {
        self.spider_cloud = Some(Box::new(SpiderCloudConfig::new(api_key)));
        self
    }

    /// Set a [spider.cloud](https://spider.cloud) API key (no-op without `spider_cloud` feature).
    #[cfg(not(feature = "spider_cloud"))]
    pub fn with_spider_cloud(&mut self, _api_key: &str) -> &mut Self {
        self
    }

    /// Set a [spider.cloud](https://spider.cloud) config.
    #[cfg(feature = "spider_cloud")]
    pub fn with_spider_cloud_config(&mut self, config: SpiderCloudConfig) -> &mut Self {
        self.spider_cloud = Some(Box::new(config));
        self
    }

    /// Set a [spider.cloud](https://spider.cloud) config (no-op without `spider_cloud` feature).
    #[cfg(not(feature = "spider_cloud"))]
    pub fn with_spider_cloud_config(&mut self, _config: ()) -> &mut Self {
        self
    }

    /// Connect to [Spider Browser Cloud](https://spider.cloud/docs/api#browser)
    /// via CDP over WebSocket using an API key.
    ///
    /// Sets `chrome_connection_url` to `wss://browser.spider.cloud/v1/browser?token=API_KEY`.
    #[cfg(all(feature = "spider_cloud", feature = "chrome"))]
    pub fn with_spider_browser(&mut self, api_key: &str) -> &mut Self {
        let cfg = SpiderBrowserConfig::new(api_key);
        self.chrome_connection_url = Some(cfg.connection_url());
        self.spider_browser = Some(Box::new(cfg));
        self
    }

    /// Connect to Spider Browser Cloud (no-op without `spider_cloud` + `chrome` features).
    #[cfg(not(all(feature = "spider_cloud", feature = "chrome")))]
    pub fn with_spider_browser(&mut self, _api_key: &str) -> &mut Self {
        self
    }

    /// Connect to [Spider Browser Cloud](https://spider.cloud/docs/api#browser)
    /// with full configuration (stealth, country, browser type, etc.).
    #[cfg(all(feature = "spider_cloud", feature = "chrome"))]
    pub fn with_spider_browser_config(&mut self, config: SpiderBrowserConfig) -> &mut Self {
        self.chrome_connection_url = Some(config.connection_url());
        self.spider_browser = Some(Box::new(config));
        self
    }

    /// Connect to Spider Browser Cloud with config (no-op without features).
    #[cfg(not(all(feature = "spider_cloud", feature = "chrome")))]
    pub fn with_spider_browser_config(&mut self, _config: ()) -> &mut Self {
        self
    }

    /// Set the hedged request (work-stealing) configuration.
    #[cfg(feature = "hedge")]
    pub fn with_hedge(&mut self, config: crate::utils::hedge::HedgeConfig) -> &mut Self {
        self.hedge = Some(config);
        self
    }

    /// Set the hedged request configuration (no-op without `hedge` feature).
    #[cfg(not(feature = "hedge"))]
    pub fn with_hedge(&mut self, _config: ()) -> &mut Self {
        self
    }

    #[cfg(feature = "auto_throttle")]
    /// Set the auto-throttle configuration for latency-based adaptive delay.
    pub fn with_auto_throttle(
        &mut self,
        config: crate::utils::auto_throttle::AutoThrottleConfig,
    ) -> &mut Self {
        self.auto_throttle = Some(config);
        self
    }

    /// Set the auto-throttle configuration (no-op without `auto_throttle` feature).
    #[cfg(not(feature = "auto_throttle"))]
    pub fn with_auto_throttle(&mut self, _config: ()) -> &mut Self {
        self
    }

    #[cfg(feature = "etag_cache")]
    /// Enable or disable ETag / conditional request caching for bandwidth-efficient re-crawls.
    pub fn with_etag_cache(&mut self, enabled: bool) -> &mut Self {
        self.etag_cache = enabled;
        self
    }

    /// Enable or disable ETag caching (no-op without `etag_cache` feature).
    #[cfg(not(feature = "etag_cache"))]
    pub fn with_etag_cache(&mut self, _enabled: bool) -> &mut Self {
        self
    }

    #[cfg(feature = "warc")]
    /// Configure WARC output for writing a web archive file during crawl.
    pub fn with_warc(&mut self, config: crate::utils::warc::WarcConfig) -> &mut Self {
        self.warc = Some(config);
        self
    }

    /// Configure WARC output (no-op without `warc` feature).
    #[cfg(not(feature = "warc"))]
    pub fn with_warc(&mut self, _config: ()) -> &mut Self {
        self
    }
}

/// Search provider configuration for web search integration.
#[cfg(feature = "search")]
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct SearchConfig {
    /// The search provider to use.
    pub provider: SearchProviderType,
    /// API key for the search provider.
    pub api_key: String,
    /// Custom API URL (overrides default endpoint for the provider).
    pub api_url: Option<String>,
    /// Default search options.
    pub default_options: Option<SearchOptions>,
}

#[cfg(feature = "search")]
impl SearchConfig {
    /// Create a new search configuration.
    pub fn new(provider: SearchProviderType, api_key: impl Into<String>) -> Self {
        Self {
            provider,
            api_key: api_key.into(),
            api_url: None,
            default_options: None,
        }
    }

    /// Use a custom API endpoint for this provider.
    pub fn with_api_url(mut self, url: impl Into<String>) -> Self {
        self.api_url = Some(url.into());
        self
    }

    /// Set default search options.
    pub fn with_default_options(mut self, options: SearchOptions) -> Self {
        self.default_options = Some(options);
        self
    }

    /// Check if this configuration is valid and search is enabled.
    ///
    /// Returns true if an API key is set or a custom API URL is configured.
    pub fn is_enabled(&self) -> bool {
        !self.api_key.is_empty() || self.api_url.is_some()
    }
}

/// Available search providers.
#[cfg(feature = "search")]
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum SearchProviderType {
    /// Serper.dev - Google SERP API (high quality).
    #[default]
    Serper,
    /// Brave Search API (privacy-focused).
    Brave,
    /// Microsoft Bing Web Search API.
    Bing,
    /// Tavily AI Search (optimized for LLMs).
    Tavily,
}

// ─── Spider Cloud ───────────────────────────────────────────────────────────

/// Integration mode for [spider.cloud](https://spider.cloud).
#[cfg(feature = "spider_cloud")]
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum SpiderCloudMode {
    /// Route all HTTP requests through `proxy.spider.cloud`.
    /// This is the simplest mode — the existing fetch pipeline works
    /// unmodified, traffic goes through the proxy transparently.
    #[default]
    Proxy,
    /// Use the spider.cloud `POST /crawl` API (with `limit: 1`) for each page.
    /// Best for simple scraping needs.
    Api,
    /// Use the spider.cloud `POST /unblocker` API for anti-bot bypass.
    /// Best for hard-to-get pages behind advanced bot protection.
    Unblocker,
    /// Direct fetch first; fall back to spider.cloud API on
    /// 403 / 429 / 503 or connection errors.
    Fallback,
    /// Intelligent mode: proxy by default, automatically falls back to
    /// `/unblocker` when it detects bot protection (403, 429, 503, CAPTCHA
    /// pages, Cloudflare challenges, empty bodies on HTML pages, etc.).
    /// This is the recommended mode for production use.
    Smart,
}

/// Configuration for spider.cloud integration.
///
/// Spider Cloud provides anti-bot bypass, proxy rotation, and high-throughput
/// data collection. Sign up at <https://spider.cloud> to obtain an API key.
#[cfg(feature = "spider_cloud")]
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct SpiderCloudConfig {
    /// API key / secret. Sign up at <https://spider.cloud> to get one.
    pub api_key: String,
    /// Integration mode.
    #[cfg_attr(feature = "serde", serde(default))]
    pub mode: SpiderCloudMode,
    /// API base URL (default: `https://api.spider.cloud`).
    #[cfg_attr(
        feature = "serde",
        serde(default = "SpiderCloudConfig::default_api_url")
    )]
    pub api_url: String,
    /// Proxy URL (default: `https://proxy.spider.cloud`).
    #[cfg_attr(
        feature = "serde",
        serde(default = "SpiderCloudConfig::default_proxy_url")
    )]
    pub proxy_url: String,
    /// Return format for API mode (default: `"raw"` to get original HTML).
    #[cfg_attr(
        feature = "serde",
        serde(default = "SpiderCloudConfig::default_return_format")
    )]
    pub return_format: String,
    /// Extra params forwarded in API mode (e.g. `stealth`, `fingerprint`, `cache`).
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub extra_params: Option<hashbrown::HashMap<String, serde_json::Value>>,
}

#[cfg(feature = "spider_cloud")]
impl Default for SpiderCloudConfig {
    fn default() -> Self {
        Self {
            api_key: String::new(),
            mode: SpiderCloudMode::default(),
            api_url: Self::default_api_url(),
            proxy_url: Self::default_proxy_url(),
            return_format: Self::default_return_format(),
            extra_params: None,
        }
    }
}

#[cfg(feature = "spider_cloud")]
impl SpiderCloudConfig {
    /// Create a new config with defaults (Proxy mode).
    pub fn new(api_key: impl Into<String>) -> Self {
        Self {
            api_key: api_key.into(),
            ..Default::default()
        }
    }

    /// Set the integration mode.
    pub fn with_mode(mut self, mode: SpiderCloudMode) -> Self {
        self.mode = mode;
        self
    }

    /// Set a custom API base URL.
    pub fn with_api_url(mut self, url: impl Into<String>) -> Self {
        self.api_url = url.into();
        self
    }

    /// Set a custom proxy URL.
    pub fn with_proxy_url(mut self, url: impl Into<String>) -> Self {
        self.proxy_url = url.into();
        self
    }

    /// Set the return format for API mode.
    pub fn with_return_format(mut self, fmt: impl Into<String>) -> Self {
        self.return_format = fmt.into();
        self
    }

    /// Set extra params for API mode.
    pub fn with_extra_params(
        mut self,
        params: hashbrown::HashMap<String, serde_json::Value>,
    ) -> Self {
        self.extra_params = Some(params);
        self
    }

    /// Determine if a response should trigger a spider.cloud API fallback.
    ///
    /// This encapsulates the intelligence about which status codes and
    /// content patterns indicate the page needs spider.cloud's help.
    ///
    /// Checks for:
    /// - HTTP 403 (Forbidden) — typically bot protection
    /// - HTTP 429 (Too Many Requests) — rate limiting
    /// - HTTP 503 (Service Unavailable) — often Cloudflare/DDoS protection
    /// - HTTP 520-530 (Cloudflare error range)
    /// - HTTP 5xx (server errors)
    /// - Empty body on what should be an HTML page
    /// - Known CAPTCHA / challenge page markers in the response body
    pub fn should_fallback(&self, status_code: u16, body: Option<&[u8]>) -> bool {
        match self.mode {
            SpiderCloudMode::Api | SpiderCloudMode::Unblocker => false, // already using API
            SpiderCloudMode::Proxy => false,                            // proxy-only, no fallback
            SpiderCloudMode::Fallback | SpiderCloudMode::Smart => {
                // Status code triggers
                if matches!(status_code, 403 | 429 | 503 | 520..=530) {
                    return true;
                }
                if status_code >= 500 {
                    return true;
                }

                // Content-based triggers (Smart mode only)
                if self.mode == SpiderCloudMode::Smart {
                    if let Some(body) = body {
                        // Empty body when we expected HTML
                        if body.is_empty() {
                            return true;
                        }

                        // Check for bot protection / CAPTCHA markers in the body
                        // (only check first 4KB for performance)
                        let check_len = body.len().min(4096);
                        let snippet = String::from_utf8_lossy(&body[..check_len]);
                        let lower = snippet.to_lowercase();

                        // Cloudflare challenge
                        if lower.contains("cf-browser-verification")
                            || lower.contains("cloudflare") && lower.contains("challenge-platform")
                        {
                            return true;
                        }

                        // Generic CAPTCHA / bot detection markers
                        if lower.contains("captcha") && lower.contains("challenge")
                            || lower.contains("please verify you are a human")
                            || lower.contains("access denied") && lower.contains("automated")
                            || lower.contains("bot detection")
                        {
                            return true;
                        }

                        // Distil Networks / Imperva / Akamai patterns
                        if lower.contains("distil_r_captcha")
                            || lower.contains("_imperva")
                            || lower.contains("akamai") && lower.contains("bot manager")
                        {
                            return true;
                        }
                    }
                }

                false
            }
        }
    }

    /// Get the fallback API route for this config.
    ///
    /// - `Smart` mode → `/unblocker` (best for bot-protected pages)
    /// - `Fallback` mode → `/crawl` (general purpose)
    /// - Other modes → `/crawl` (default)
    pub fn fallback_route(&self) -> &'static str {
        match self.mode {
            SpiderCloudMode::Smart | SpiderCloudMode::Unblocker => "unblocker",
            _ => "crawl",
        }
    }

    /// Whether this mode uses the proxy transport layer.
    pub fn uses_proxy(&self) -> bool {
        matches!(
            self.mode,
            SpiderCloudMode::Proxy | SpiderCloudMode::Fallback | SpiderCloudMode::Smart
        )
    }

    fn default_api_url() -> String {
        "https://api.spider.cloud".to_string()
    }

    fn default_proxy_url() -> String {
        "https://proxy.spider.cloud".to_string()
    }

    fn default_return_format() -> String {
        "raw".to_string()
    }
}

// ─── Spider Browser Cloud ────────────────────────────────────────────────────

/// Configuration for [Spider Browser Cloud](https://spider.cloud/docs/api#browser).
///
/// Connects to a remote Chromium instance via CDP over WebSocket at
/// `wss://browser.spider.cloud/v1/browser`.  Authentication is via
/// `?token=API_KEY` query parameter.
///
/// Optional query parameters: `stealth`, `browser`, `country`.
#[cfg(all(feature = "spider_cloud", feature = "chrome"))]
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct SpiderBrowserConfig {
    /// API key / secret. Sign up at <https://spider.cloud> to get one.
    pub api_key: String,
    /// WebSocket base URL (default: `wss://browser.spider.cloud/v1/browser`).
    #[cfg_attr(
        feature = "serde",
        serde(default = "SpiderBrowserConfig::default_wss_url")
    )]
    pub wss_url: String,
    /// Enable stealth mode (anti-fingerprinting). Sent as `stealth=true` query param.
    #[cfg_attr(feature = "serde", serde(default))]
    pub stealth: bool,
    /// Browser type to request (e.g. `"chrome"`, `"firefox"`). Sent as `browser=<value>`.
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub browser: Option<String>,
    /// Country code for geo-targeting (e.g. `"us"`, `"gb"`). Sent as `country=<value>`.
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub country: Option<String>,
    /// Extra query parameters appended to the WSS URL.
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub extra_params: Option<Vec<(String, String)>>,
}

#[cfg(all(feature = "spider_cloud", feature = "chrome"))]
impl Default for SpiderBrowserConfig {
    fn default() -> Self {
        Self {
            api_key: String::new(),
            wss_url: Self::default_wss_url(),
            stealth: false,
            browser: None,
            country: None,
            extra_params: None,
        }
    }
}

#[cfg(all(feature = "spider_cloud", feature = "chrome"))]
impl SpiderBrowserConfig {
    /// Create a new config with the given API key.
    pub fn new(api_key: impl Into<String>) -> Self {
        Self {
            api_key: api_key.into(),
            ..Default::default()
        }
    }

    /// Set a custom WSS base URL.
    pub fn with_wss_url(mut self, url: impl Into<String>) -> Self {
        self.wss_url = url.into();
        self
    }

    /// Enable or disable stealth mode.
    pub fn with_stealth(mut self, stealth: bool) -> Self {
        self.stealth = stealth;
        self
    }

    /// Set the browser type to request.
    pub fn with_browser(mut self, browser: impl Into<String>) -> Self {
        self.browser = Some(browser.into());
        self
    }

    /// Set the country code for geo-targeting.
    pub fn with_country(mut self, country: impl Into<String>) -> Self {
        self.country = Some(country.into());
        self
    }

    /// Add extra query parameters.
    pub fn with_extra_params(mut self, params: Vec<(String, String)>) -> Self {
        self.extra_params = Some(params);
        self
    }

    /// Build the full WSS connection URL with authentication and options.
    ///
    /// Returns a URL like:
    /// `wss://browser.spider.cloud/v1/browser?token=KEY&stealth=true&country=us`
    pub fn connection_url(&self) -> String {
        let mut url = self.wss_url.clone();

        // Start query string
        if url.contains('?') {
            url.push('&');
        } else {
            url.push('?');
        }
        url.push_str("token=");
        url.push_str(&self.api_key);

        if self.stealth {
            url.push_str("&stealth=true");
        }
        if let Some(ref browser) = self.browser {
            url.push_str("&browser=");
            url.push_str(browser);
        }
        if let Some(ref country) = self.country {
            url.push_str("&country=");
            url.push_str(country);
        }
        if let Some(ref extra) = self.extra_params {
            for (k, v) in extra {
                url.push('&');
                url.push_str(k);
                url.push('=');
                url.push_str(v);
            }
        }

        url
    }

    fn default_wss_url() -> String {
        "wss://browser.spider.cloud/v1/browser".to_string()
    }
}

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

    #[test]
    fn test_configuration_defaults() {
        let config = Configuration::default();
        assert!(!config.respect_robots_txt);
        assert!(!config.subdomains);
        assert!(!config.tld);
        assert_eq!(config.delay, 0);
        assert!(config.user_agent.is_none());
        assert!(config.blacklist_url.is_none());
        assert!(config.whitelist_url.is_none());
        assert!(config.proxies.is_none());
        assert!(!config.http2_prior_knowledge);
    }

    #[test]
    fn test_redirect_policy_variants() {
        assert_eq!(RedirectPolicy::default(), RedirectPolicy::Loose);
        let strict = RedirectPolicy::Strict;
        let none = RedirectPolicy::None;
        assert_ne!(strict, RedirectPolicy::Loose);
        assert_ne!(none, RedirectPolicy::Loose);
        assert_ne!(strict, none);
    }

    #[test]
    fn test_proxy_ignore_variants() {
        assert_eq!(ProxyIgnore::default(), ProxyIgnore::No);
        let chrome = ProxyIgnore::Chrome;
        let http = ProxyIgnore::Http;
        assert_ne!(chrome, ProxyIgnore::No);
        assert_ne!(http, ProxyIgnore::No);
        assert_ne!(chrome, http);
    }

    #[test]
    fn test_request_proxy_construction() {
        let proxy = RequestProxy {
            addr: "http://proxy.example.com:8080".to_string(),
            ignore: ProxyIgnore::No,
        };
        assert_eq!(proxy.addr, "http://proxy.example.com:8080");
        assert_eq!(proxy.ignore, ProxyIgnore::No);
    }

    #[test]
    fn test_request_proxy_default() {
        let proxy = RequestProxy::default();
        assert!(proxy.addr.is_empty());
        assert_eq!(proxy.ignore, ProxyIgnore::No);
    }

    #[test]
    fn test_configuration_blacklist_setup() {
        let mut config = Configuration::default();
        config.blacklist_url = Some(vec![
            "https://example.com/private".into(),
            "https://example.com/admin".into(),
        ]);
        assert_eq!(config.blacklist_url.as_ref().unwrap().len(), 2);
    }

    #[test]
    fn test_configuration_whitelist_setup() {
        let mut config = Configuration::default();
        config.whitelist_url = Some(vec!["https://example.com/public".into()]);
        assert_eq!(config.whitelist_url.as_ref().unwrap().len(), 1);
    }

    #[test]
    fn test_configuration_external_domains() {
        let mut config = Configuration::default();
        config.external_domains_caseless = Arc::new(
            [
                case_insensitive_string::CaseInsensitiveString::from("Example.Com"),
                case_insensitive_string::CaseInsensitiveString::from("OTHER.org"),
            ]
            .into_iter()
            .collect(),
        );
        assert_eq!(config.external_domains_caseless.len(), 2);
        assert!(config.external_domains_caseless.contains(
            &case_insensitive_string::CaseInsensitiveString::from("example.com")
        ));
    }

    #[test]
    fn test_configuration_budget() {
        let mut config = Configuration::default();
        let mut budget = hashbrown::HashMap::new();
        budget.insert(
            case_insensitive_string::CaseInsensitiveString::from("/path"),
            100u32,
        );
        config.budget = Some(budget);
        assert!(config.budget.is_some());
        assert_eq!(
            config.budget.as_ref().unwrap().get(
                &case_insensitive_string::CaseInsensitiveString::from("/path")
            ),
            Some(&100u32)
        );
    }

    #[cfg(not(feature = "regex"))]
    #[test]
    fn test_allow_list_set_default() {
        let allow_list = AllowListSet::default();
        assert!(allow_list.0.is_empty());
    }

    #[cfg(feature = "agent")]
    #[test]
    fn test_build_remote_multimodal_engine_preserves_dual_models() {
        use crate::features::automation::{
            ModelEndpoint, RemoteMultimodalConfigs, VisionRouteMode,
        };

        let mut config = Configuration::default();
        let mm = RemoteMultimodalConfigs::new(
            "https://api.example.com/v1/chat/completions",
            "primary-model",
        )
        .with_vision_model(ModelEndpoint::new("vision-model").with_api_key("vision-key"))
        .with_text_model(
            ModelEndpoint::new("text-model")
                .with_api_url("https://text.example.com/v1/chat/completions")
                .with_api_key("text-key"),
        )
        .with_vision_route_mode(VisionRouteMode::TextFirst);
        config.remote_multimodal = Some(Box::new(mm));

        let engine = config
            .build_remote_multimodal_engine()
            .expect("engine should be built");

        assert_eq!(
            engine.vision_model.as_ref().map(|m| m.model_name.as_str()),
            Some("vision-model")
        );
        assert_eq!(
            engine.text_model.as_ref().map(|m| m.model_name.as_str()),
            Some("text-model")
        );
        assert_eq!(engine.vision_route_mode, VisionRouteMode::TextFirst);
    }

    #[cfg(all(feature = "spider_cloud", feature = "chrome"))]
    #[test]
    fn test_spider_browser_config_defaults() {
        let cfg = SpiderBrowserConfig::new("test-key");
        assert_eq!(cfg.api_key, "test-key");
        assert_eq!(cfg.wss_url, "wss://browser.spider.cloud/v1/browser");
        assert!(!cfg.stealth);
        assert!(cfg.browser.is_none());
        assert!(cfg.country.is_none());
        assert!(cfg.extra_params.is_none());
    }

    #[cfg(all(feature = "spider_cloud", feature = "chrome"))]
    #[test]
    fn test_spider_browser_connection_url_basic() {
        let cfg = SpiderBrowserConfig::new("sk-abc123");
        assert_eq!(
            cfg.connection_url(),
            "wss://browser.spider.cloud/v1/browser?token=sk-abc123"
        );
    }

    #[cfg(all(feature = "spider_cloud", feature = "chrome"))]
    #[test]
    fn test_spider_browser_connection_url_full() {
        let cfg = SpiderBrowserConfig::new("sk-abc123")
            .with_stealth(true)
            .with_browser("chrome")
            .with_country("us")
            .with_extra_params(vec![("timeout".into(), "30000".into())]);
        assert_eq!(
            cfg.connection_url(),
            "wss://browser.spider.cloud/v1/browser?token=sk-abc123&stealth=true&browser=chrome&country=us&timeout=30000"
        );
    }

    #[cfg(all(feature = "spider_cloud", feature = "chrome"))]
    #[test]
    fn test_spider_browser_connection_url_custom_wss() {
        let cfg = SpiderBrowserConfig::new("key")
            .with_wss_url("wss://custom.browser.example.com/v1/browser");
        assert_eq!(
            cfg.connection_url(),
            "wss://custom.browser.example.com/v1/browser?token=key"
        );
    }

    #[cfg(all(feature = "spider_cloud", feature = "chrome"))]
    #[test]
    fn test_with_spider_browser_sets_chrome_connection() {
        let mut config = Configuration::default();
        config.with_spider_browser("my-api-key");
        assert_eq!(
            config.chrome_connection_url.as_deref(),
            Some("wss://browser.spider.cloud/v1/browser?token=my-api-key")
        );
        assert!(config.spider_browser.is_some());
    }

    #[cfg(all(feature = "spider_cloud", feature = "chrome"))]
    #[test]
    fn test_with_spider_browser_config_stealth() {
        let mut config = Configuration::default();
        let browser_cfg = SpiderBrowserConfig::new("key")
            .with_stealth(true)
            .with_country("gb");
        config.with_spider_browser_config(browser_cfg);
        assert_eq!(
            config.chrome_connection_url.as_deref(),
            Some("wss://browser.spider.cloud/v1/browser?token=key&stealth=true&country=gb")
        );
    }
}