fatsearch 0.1.2

Web pages and documents turned into small, clean, cached Markdown for AI agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
//! PROVIDERS: how a URL becomes bytes. `plain` = a direct GET with Safari 26's TLS, HTTP/2 and header profile;
//! `bd` = Bright Data Web Unlocker; `oxy` / `oxyjs` = Oxylabs Web API `/v1/scrape` without / with JavaScript
//! rendering (one key, two prices, two timeouts). One table holds names, keys, timeouts
//! and list prices; the router (fetch.rs) decides which to call.

use serde_json::{Value, json};
use std::sync::LazyLock;
use std::time::Duration;

#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum Tier {
    #[default]
    Plain,
    Bd,
    Oxy,
    OxyJs,
}

#[derive(serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Spec {
    /// meta.json / stats name (`brightdata`); `short` is the `provider:` value and the tier-path name (`bd`).
    pub name: &'static str,
    pub short: &'static str,
    pub env: &'static str,
    pub file: &'static str,
    pub timeout: Duration,
    /// USD per request at list price (no API returns a cost).
    pub price: f64,
    /// THE capability row the router builds every ladder from (`fetch::Plan::ladder`): `page` (fetches a page),
    /// `js` (renders JavaScript), `search`, `pdf` (a file's exact bytes), `gov` (government hosts served).
    can: Vec<&'static str>,
    /// The provider bills a finished job that relays the site's own 5xx (`charged`): Oxylabs' "Not
    /// charged" is its own API error (`500 REQUEST_FAILED_AFTER_TOO_MANY_RETRIES`, an error envelope, never a
    /// `results` answer); Bright Data's inner 5xx is an unlock failure (zone counter +0).
    pub bills_site_5xx: bool,
    /// What a call adds, for the `no_key` row (`unblock+JS`).
    pub buys: &'static str,
    /// A search's typical answer time, s: the default `wait:` of a search this tier leads (`fetch::Plan::search`).
    pub search_s: u64,
}

/// The provider table (`src/data/providers.json`): `specs` indexed by `Tier as usize`, `apis` by `Api as usize`,
/// `links` per account, `cctld` = TLD → `"<exit country> <its page languages>"` (`fetch::langs`).
/// Prices: Oxylabs Web API $1.00/1k, $1.50/1k with `run_js` (smallest paid plan);
/// Bright Data Web Unlocker ~$1.50/1k. Timeouts: plain 10 s, Oxylabs without JS 10 s (its wins took 1.4–5.6 s on
/// 40 hard pages, 6 s cut 2 of 3 Reddit threads; no page tier since the 2026-10-14 spike: files, prefetch, `provider:oxy`), BD and Oxylabs with
/// JS 60 s each (`timeout:` sets these two).
#[derive(serde::Deserialize)]
#[serde(deny_unknown_fields, bound(deserialize = "'de: 'static"))]
pub struct Providers {
    pub specs: Vec<Spec>,
    pub apis: Vec<ApiRow>,
    pub links: Vec<Links>,
    pub cctld: std::collections::HashMap<&'static str, &'static str>,
}

pub static PROVIDERS: LazyLock<Providers> = LazyLock::new(|| crate::settings::table("providers"));

impl Tier {
    pub const ALL: [Tier; 4] = [Tier::Plain, Tier::Bd, Tier::Oxy, Tier::OxyJs];

    pub fn spec(self) -> &'static Spec {
        &PROVIDERS.specs[self as usize]
    }

    /// A tier's short or stored name (`oxyjs`, `oxylabs-js`) → tier; the `provider:` mod refuses `oxyjs`.
    pub fn parse(s: &str) -> Option<Tier> {
        Tier::ALL.into_iter().find(|t| t.spec().short == s || t.spec().name == s)
    }

    /// The tier whose key this one sends, as `fats config` lists it (`oxyjs` → `oxy`): the first with its env.
    pub fn owner(self) -> Tier {
        Tier::ALL.into_iter().find(|t| t.spec().env == self.spec().env).unwrap_or(self)
    }

    /// The mods that ask for this tier alone: `provider:` takes the key's name, so oxyjs = `provider:oxy js:true`.
    pub fn ask(self) -> String {
        format!("provider:{}{}", self.owner().spec().short, if self.owner() == self { "" } else { " js:true" })
    }

    /// The tier's row says it does `job` (`Spec::can`).
    pub fn can(self, job: &str) -> bool {
        self.spec().can.contains(&job)
    }

    /// The key (and for BD the zone) this tier needs; None = not configured. Plain needs nothing.
    pub fn key(self) -> Option<String> {
        let s = self.spec();
        match self {
            Tier::Plain => Some(String::new()),
            Tier::Bd => crate::settings::zone().and(crate::settings::key(s.env, s.file).map(|k| k.0)),
            Tier::Oxy | Tier::OxyJs => crate::settings::key(s.env, s.file).map(|k| k.0),
        }
    }
}

/// Short name for a stored provider name (`brightdata` → `bd`); unknown names pass through.
pub fn short(name: &str) -> &str {
    PROVIDERS.specs.iter().find(|s| s.name == name).map_or(name, |s| s.short)
}

/// What to fetch and how.
#[derive(Clone, Default)]
pub struct Ask {
    pub url: String,
    /// Oxylabs `run_js`.
    pub js: bool,
    /// `country:` as given, ISO 3166-1 alpha-2, lower case (`fr`); see `country` for what each tier sends.
    pub country: Option<String>,
    pub timeout: Option<Duration>,
    /// Body cap in bytes (`max_bytes:`).
    pub max_bytes: u64,
    /// `device:mobile`: Oxylabs emulates a phone's user agent and viewport; Bright Data has no such setting.
    pub mobile: bool,
    /// A PDF run (fetch `pdf_run`): Bright Data sends the file's bytes (`format: raw`), not a JSON string.
    pub doc: bool,
    /// Plain sends the browser's own `Accept`, without `MD_ACCEPT`: `fetch::run`'s second call after a weak Markdown
    /// answer, and a picture download (`cli::download`).
    pub html: bool,
}

/// Plain's `Accept` (`FATS_ACCEPT_MD`, not in a PDF run): Markdown first, then Safari's own list, so a server that
/// converts its pages (Cloudflare's Markdown for Agents, `text/markdown`) skips our CONVERT and any other server
/// answers as it does a browser.
pub const MD_ACCEPT: &str = "text/markdown;q=1.0, text/html;q=0.9, application/xhtml+xml;q=0.9, */*;q=0.8";

/// A target's answer, whoever carried it. `headers` = lowercase `name: value` lines (bot-wall vendors live there).
#[derive(Default)]
pub struct Raw {
    pub status: u16,
    pub final_url: String,
    pub ctype: String,
    pub headers: String,
    pub body: Vec<u8>,
    /// What the body was decoded from (`windows-1250`; "" = UTF-8, as provider APIs return JSON strings).
    pub charset: &'static str,
    /// The provider's request budget, when its answer said (`Limit`).
    pub limit: Option<Limit>,
}

/// A provider's own request budget from its answer: the two numbers only. Oxylabs Web API sends
/// `x-ratelimit-<bucket>-<account number>-limit` and `-remaining` (search 10, scrape 250; undocumented, window
/// unknown; observed, not documented). The header names carry the account number, so they are never kept.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Limit {
    pub limit: u32,
    pub remaining: u32,
}

/// Seconds before a rate-limited call is worth retrying when the answer gives none (`retry-after`).
pub const RETRY_AFTER: u64 = 5;

/// A failed call: the stable code, and the provider's own answer when it sent one (HTTP status, body). The body
/// is never printed: it is masked here and kept only as the snapshot's `error.txt` (a provider may echo the
/// key in it: ScrapingBee's 401 does).
#[derive(Debug, Default, PartialEq)]
pub struct Fail {
    pub code: &'static str,
    pub status: u16,
    pub body: Vec<u8>,
    /// What the `!` row may add to the code: a short token read from the answer (`proxy_error`), never raw text.
    pub why: String,
    pub limit: Option<Limit>,
}

impl From<&'static str> for Fail {
    fn from(code: &'static str) -> Fail {
        Fail { code, ..Fail::default() }
    }
}

/// One call. Err = a stable code. `billed` = the provider charges for it (`charged`).
pub async fn get(t: Tier, ask: &Ask, key: &str) -> (Result<Raw, Fail>, bool) {
    let wait = ask.timeout.unwrap_or(t.spec().timeout);
    let r = match t {
        Tier::Plain => plain(ask, wait).await,
        Tier::Bd => brightdata(ask, key, wait).await,
        Tier::Oxy | Tier::OxyJs => oxylabs(ask, key, wait).await,
    };
    let billed = charged(t, r.as_ref().map(|raw| raw.status));
    (r.and_then(|raw| if raw.body.len() as u64 > ask.max_bytes { Err("too_big".into()) } else { Ok(raw) }), billed)
}

/// Run `f` to its end on a fresh single-thread runtime: the one bridge from the blocking CLI to async calls.
/// None = no runtime could be built (the caller's `net_error`).
pub fn block<F: Future>(f: F) -> Option<F::Output> {
    Some(tokio::runtime::Builder::new_current_thread().enable_all().build().ok()?.block_on(f))
}

/// A command answers by `wait:`: `calls` run side by side on one runtime, each answer in order;
/// None = still running at `wait` (given up, the row says `late`).
pub fn all_within<F>(calls: Vec<F>, wait: Duration) -> Vec<Option<F::Output>>
where
    F: Future<Output: Send> + Send + 'static,
{
    let mut got: Vec<Option<F::Output>> = calls.iter().map(|_| None).collect();
    block(async {
        let mut set = tokio::task::JoinSet::new();
        for (i, call) in calls.into_iter().enumerate() {
            set.spawn(async move { (i, call.await) });
        }
        let end = tokio::time::Instant::now() + wait;
        while let Ok(Some(Ok((i, answer)))) = tokio::time::timeout_at(end, set.join_next()).await {
            got[i] = Some(answer);
        }
    });
    got
}

/// A call given up at the command's `wait:` (`all_within`, a search's deadline): `provider_timeout wait:5s`.
pub fn late(wait: Duration) -> Fail {
    Fail { why: format!("wait:{}s", wait.as_secs()), ..Fail::from("provider_timeout") }
}

/// The second resolver, asked only when the system resolver found no address: Cloudflare's DNS over HTTPS (JSON,
/// developers.cloudflare.com 1.1.1.1 dns-json: GET `name` + `type`, `accept: application/dns-json`; `Status` = the
/// DNS RCODE). Some(false) = NXDOMAIN (RCODE 3), Some(true) = the name exists, None = no verdict (unreachable).
pub async fn exists(host: &str) -> Option<bool> {
    let (body, ..) = api(Api::Doh, "", json!({"name": host, "type": "A"}), 64 << 10, DOH_WAIT).await.ok()?;
    match serde_json::from_slice::<Value>(&body).ok()?["Status"].as_u64()? {
        3 => Some(false),
        0 => Some(true),
        _ => None,
    }
}

pub const DOH_WAIT: Duration = Duration::from_millis(1500);

/// THE billing rule, one for both providers: an answer below 500 is billed; a refusal, a 5xx or a timeout is not,
/// but a site's 5xx relayed in a finished job is where `bills_site_5xx` (Oxylabs, printed `(assumed)` until one is
/// reconciled). Oxylabs: "All upstream engines failed. Not charged." (developers.oxylabs.io/products/web-api/
/// troubleshooting, its own error envelope, a `provider_error` here); its no-JS and 60 s cuts end in that 500 (10 of
/// 11 re-run at 60 s, spike 2026-10-14). Bright Data: the zone counter moved +20 for ~28 calls, its 3 `http_502` and
/// 6 timeouts unbilled. A search answer with no result list is not (bd: +0
/// for 2 such `provider_error`s). A call WE cut has no answer: its price is unverified (`fetch::billed`:
/// bd billed 15 s search cuts; "a cut is free" held for 1-s cuts only).
pub fn charged(t: Tier, status: Result<u16, &Fail>) -> bool {
    t != Tier::Plain && status.is_ok_and(|s| s < 500 || t.spec().bills_site_5xx)
}

/// THE list of the provider's own refusals (its error envelope, bd's `x-brd-error`, a rate limit): no answer, so
/// never billed (`charged` gets them as an `Err`); a tried path says `$0 (not charged)`, a priced retry after one
/// ` (last try not charged)` (one list, was three).
pub const REFUSED: &[&str] = &["provider_error", "provider_refused", "rate_limited"];

/// THE money total: from +0.0, so nothing spent prints `$0.0000` (`sum::<f64>()` of nothing is −0.0 → `$-0.0000`).
pub fn spend(costs: impl IntoIterator<Item = f64>) -> f64 {
    costs.into_iter().fold(0.0, |total, cost| total + cost)
}

fn net(e: &wreq::Error) -> &'static str {
    let mut src: Option<&(dyn std::error::Error + 'static)> = Some(e);
    while let Some(s) = src {
        if s.is::<Private>() {
            return "private_address";
        }
        src = s.source();
    }
    if e.is_timeout() {
        "provider_timeout"
    } else if e.is_connect() || e.is_dns() || e.is_tls() {
        "connect_failed"
    } else {
        "net_error"
    }
}

/// A header map as (name, value) pairs; names are lower case already.
fn pairs(h: &wreq::header::HeaderMap) -> Vec<(String, String)> {
    h.iter().map(|(k, v)| (k.as_str().to_string(), String::from_utf8_lossy(v.as_bytes()).into())).collect()
}

/// Headers as `Raw::headers` keeps them: `name: value` lines, all lower case (wall vendors are matched on them).
fn header_lines<'a>(h: impl Iterator<Item = (&'a String, &'a str)>) -> String {
    h.map(|(k, v)| format!("{}: {}\n", k.to_lowercase(), v.to_lowercase())).collect()
}

async fn plain(ask: &Ask, wait: Duration) -> Result<Raw, Fail> {
    let client = wreq::Client::builder()
        .emulation(browser())
        .redirect(wreq::redirect::Policy::none())
        .dns_resolver(Fence)
        .timeout(wait)
        .build()
        .map_err(|_| "net_error")?;
    let send = |u: String| {
        let req = client.get(&u);
        let md = crate::settings::get().accept_md.value && !ask.doc && !ask.html;
        let req = if md { req.header(wreq::header::ACCEPT, MD_ACCEPT) } else { req };
        async move {
            let r = req.send().await.map_err(|e| net(&e))?;
            let to = r.headers().get("location").map(|v| String::from_utf8_lossy(v.as_bytes()).into_owned());
            Ok((r.status().as_u16(), to, r))
        }
    };
    let (final_url, r) = follow(&ask.url, send).await?;
    let (status, headers) =
        (r.status().as_u16(), header_lines(pairs(r.headers()).iter().map(|h| (&h.0, h.1.as_str()))));
    let ctype = r.headers().get("content-type").map(|v| String::from_utf8_lossy(v.as_bytes()).to_lowercase());
    let ctype = ctype.unwrap_or_default();
    let body = capped(r, ask.max_bytes).await?;
    let declared = ctype.split("charset=").nth(1).map(|c| c.split(';').next().unwrap_or(c).trim_matches(['"', ' ']));
    // a picture's bytes are never text (`cli::asset`)
    let (body, charset) = if ctype.starts_with("image/") { (body, "") } else { decode_body(body, declared) };
    Ok(Raw { status, final_url, ctype, headers, body, charset, ..Raw::default() })
}

/// Text is kept as UTF-8: a body with no file magic is decoded from what the header or page declares (else
/// sniffed); a file (PDF, zip) stays bytes. The one rule for every carrier of a page's bytes (plain, Bright Data
/// raw, a local file).
pub fn decode_body(body: Vec<u8>, declared: Option<&str>) -> (Vec<u8>, &'static str) {
    match crate::clean::sniff(&body) {
        None => crate::clean::decode(body, declared),
        Some(_) => (body, ""),
    }
}

// ---------------------------------------------------------------- private-address fence

/// Not a public unicast address: loopback, private, link-local (169.254.169.254 = cloud metadata), CGNAT,
/// unspecified, multicast, reserved, documentation; IPv6 ULA and link-local; IPv4 inside IPv6 (mapped, NAT64)
/// is judged as the IPv4 it carries.
pub fn private_ip(ip: std::net::IpAddr) -> bool {
    use std::net::IpAddr::{V4, V6};
    match ip {
        V4(a) => {
            let [x, y, ..] = a.octets();
            a.is_private()
                || a.is_loopback()
                || a.is_link_local()
                || a.is_unspecified()
                || a.is_broadcast()
                || a.is_multicast()
                || a.is_documentation()
                || x == 0
                || x >= 240
                || (x == 100 && (64..128).contains(&y))
                || (x == 198 && (y & 0xfe) == 18)
                || (x == 192 && y == 0 && a.octets()[2] == 0)
        }
        V6(a) => {
            let s = a.segments();
            // an IPv4 inside: mapped `::ffff:a.b.c.d`, NAT64 `64:ff9b::/96`, compatible `::/96`, 6to4 `2002::/16`
            let v4 = |hi: u16, lo: u16| Some(std::net::Ipv4Addr::from((u32::from(hi) << 16) | u32::from(lo)));
            let v4 = a.to_ipv4_mapped().or(match s {
                [0x64, 0xff9b, 0, 0, 0, 0, ..] | [0, 0, 0, 0, 0, 0, ..] => v4(s[6], s[7]),
                [0x2002, ..] => v4(s[1], s[2]),
                _ => None,
            });
            match v4 {
                Some(v4) => private_ip(V4(v4)),
                None => {
                    a.is_loopback()
                        || a.is_unspecified()
                        || a.is_multicast()
                        || a.is_unique_local()
                        || a.is_unicast_link_local()
                        || (s[0] & 0xffc0) == 0xfec0
                        || (s[0], s[1]) == (0x2001, 0xdb8)
                }
            }
        }
    }
}

/// The URL's own host is private (an IP literal in any WHATWG spelling, or `localhost`); DNS names are judged
/// by `Fence` when they resolve. Always false with `FATS_ALLOW_PRIVATE=1`.
pub fn private_host(url: &str) -> bool {
    !crate::settings::get().allow_private.value
        && match url::Url::parse(url).ok().as_ref().and_then(url::Url::host) {
            Some(url::Host::Ipv4(a)) => private_ip(a.into()),
            Some(url::Host::Ipv6(a)) => private_ip(a.into()),
            Some(url::Host::Domain(d)) => {
                let d = d.trim_end_matches('.');
                d == "localhost" || d.ends_with(".localhost")
            }
            None => true,
        }
}

/// The resolver for plain fetches: the system's answer minus private addresses, so a name that resolves (or
/// re-resolves, DNS rebinding) to one never gets a connection.
struct Fence;

#[derive(Debug)]
struct Private;

impl std::fmt::Display for Private {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        f.write_str("resolves to a private address")
    }
}

impl std::error::Error for Private {}

impl wreq::dns::Resolve for Fence {
    fn resolve(&self, name: wreq::dns::Name) -> wreq::dns::Resolving {
        let all = wreq::dns::GaiResolver::new().resolve(name);
        Box::pin(async move {
            let open = crate::settings::get().allow_private.value;
            let keep: Vec<_> = all.await?.filter(|a| open || !private_ip(a.ip())).collect();
            if keep.is_empty() {
                return Err(Box::new(Private) as Box<dyn std::error::Error + Send + Sync>);
            }
            Ok(Box::new(keep.into_iter()) as wreq::dns::Addrs)
        })
    }
}

/// Redirects, followed here rather than by the client so every hop's host passes `private_host` (an IP literal
/// in a `Location` never reaches the resolver). `send` = one request → (status, Location, response).
/// Ok = (final URL, response); at most 10 redirects.
async fn follow<R, F>(url: &str, send: impl Fn(String) -> F) -> Result<(String, R), &'static str>
where
    F: Future<Output = Result<(u16, Option<String>, R), &'static str>>,
{
    let mut at = url.to_string();
    for _ in 0..=10 {
        if private_host(&at) {
            return Err("private_address");
        }
        match send(at.clone()).await? {
            (301 | 302 | 303 | 307 | 308, Some(to), _) => {
                at = url::Url::parse(&at).and_then(|u| u.join(&to)).map_err(|_| "net_error")?.into();
            }
            (_, _, r) => return Ok((at, r)),
        }
    }
    Err("redirect_loop")
}

/// The body, frame by frame, refused as soon as it passes `cap` bytes: a chunked or lying server never fills
/// memory (Content-Length, when sent, refuses it before the first frame, its size the why).
async fn capped(mut r: wreq::Response, cap: u64) -> Result<Vec<u8>, Fail> {
    use http_body::Body;
    if let Some(n) = r.content_length().filter(|&n| n > cap) {
        return Err(Fail { why: format!("{}B", crate::lang::ksize(n as usize)), ..Fail::from("too_big") });
    }
    let mut v = Vec::new();
    while let Some(f) = std::future::poll_fn(|cx| std::pin::Pin::new(&mut r).poll_frame(cx)).await {
        if let Ok(d) = f.map_err(|e| net(&e))?.into_data() {
            if (v.len() + d.len()) as u64 > cap {
                return Err("too_big".into());
            }
            v.extend_from_slice(&d);
        }
    }
    Ok(v)
}

// ---------------------------------------------------------------- provider APIs: the one table, the one sender

/// Every provider API this binary sends a key to. A call names an `Api`, never a URL string, so a key can only
/// go to a URL in `Providers::apis`: scrape, search, and the account reads `fats account` makes. Account endpoints that
/// return secrets are never listed (Bright Data `GET /zone` and `/zone/passwords` return zone passwords,
/// Webshare `/proxy/list` returns proxy passwords).
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum Api {
    BdRequest,
    OxyScrape,
    OxySearch,
    /// Account reads (`fats account`): Oxylabs has no balance or usage API for the Web API key; the scraper list
    /// answers 200 or 401, so it is the key check (developers.oxylabs.io products/web-api).
    OxyScrapers,
    /// Bright Data Account Management API (docs.brightdata.com api-reference/account-management-api): balance in
    /// USD, active zones `[{name, type}]`, the cost export (a read, documented as POST), one zone's month.
    BdBalance,
    BdZones,
    BdCosts,
    BdZoneCost,
    /// DNS over HTTPS (`exists`): no key.
    Doh,
    /// GitHub repository search and one account's repositories (`gh_repos`): the GitHub token, or none.
    GhRepos,
    GhUser,
}

/// A row of `Providers::apis`: the method, the URL, and what an account read gets (`account dry:true`, `{from}`
/// `{to}` = the month). A GET sends the request's fields as the query string.
#[derive(serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ApiRow {
    pub api: Api,
    pub method: &'static str,
    pub url: &'static str,
    pub what: &'static str,
    /// The `accept` header the API asks for (DoH: `application/dns-json`); empty = none.
    #[serde(default)]
    pub accept: &'static str,
}

impl Api {
    pub fn row(self) -> &'static ApiRow {
        &PROVIDERS.apis[self as usize]
    }

    /// The URL a call to `self` goes to: a GET's `req` string fields as the query (`send`, `account dry:true`).
    pub fn url(self, req: &Value) -> String {
        let get = req.as_object().into_iter().flatten().filter(|_| self.row().method == "GET");
        let q = url::form_urlencoded::Serializer::new(String::new())
            .extend_pairs(get.map(|(k, v)| (k, v.as_str().unwrap_or_default())))
            .finish();
        // a path's `{q}` (GhUser's login, `[A-Za-z0-9-]` only) is the request's `q`, also sent in the query
        let url = self.row().url.replace("{q}", req["q"].as_str().unwrap_or_default());
        if q.is_empty() { url } else { format!("{url}?{q}") }
    }
}

/// A provider's dashboard pages, printed after a `!` row's fix (`→ <link>`); never requested, never sent a key.
/// Only pages the providers' own docs give as a URL (read 2026-10-12);
/// a page the docs reach only by menu path is None, never a guessed URL.
#[derive(serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Links {
    pub short: &'static str,
    pub signup: &'static str,
    pub keys: Option<&'static str>,
    pub billing: Option<&'static str>,
    pub usage: Option<&'static str>,
}

/// A provider's pages by any tier name that uses its key (`oxyjs` → Oxylabs).
pub fn links(short: &str) -> Option<&'static Links> {
    let owner = Tier::parse(short).map_or(short, |t| t.owner().spec().short);
    PROVIDERS.links.iter().find(|l| l.short == owner)
}

/// THE page a `!` row about a provider's key or money ends with: `no_key` → sign-up, `bad_key` → the keys
/// page, `low_balance` → billing. None = another code, or the docs give no URL for that page.
pub fn page(code: &str, short: &str) -> Option<String> {
    let l = links(short)?;
    match code {
        "no_key" => Some(l.signup.into()),
        "bad_key" => l.keys.map(String::from),
        "low_balance" => l.billing.map(String::from),
        _ => None,
    }
}

/// `page` for every provider a row names, appended after its fix: ` · bd https://…` ("" when none has one).
pub fn pages<'a>(code: &str, names: impl IntoIterator<Item = &'a str>) -> String {
    names.into_iter().filter_map(|n| page(code, n).map(|p| format!(" · {n} {p}"))).collect()
}

/// A provider API's answer before it is read: HTTP status, headers (lower-case names), body. Headers live only
/// here: `read` takes the few values it needs, nothing stores or prints them.
pub struct Reply {
    pub status: u16,
    pub headers: Vec<(String, String)>,
    pub body: Vec<u8>,
}

impl Reply {
    fn header(&self, name: &str) -> Option<&str> {
        self.headers.iter().find(|h| h.0 == name).map(|h| h.1.as_str())
    }

    /// Bright Data's refusal: HTTP 200 (also for `format: raw` with an empty body) and the reason in `x-brd-error`
    /// (`x-luminati-error` before the rename), its code in `x-brd-error-code` (observed 2026-10-12).
    fn refused(&self) -> bool {
        self.header("x-brd-error").or(self.header("x-luminati-error")).is_some()
    }

    /// Seconds until a rate-limited call is worth retrying, None = not a rate limit that says so. Oxylabs: a 429
    /// titled `RATE_LIMIT_EXCEEDED` (`retry-after`, else `RETRY_AFTER`). GitHub (docs.github.com rest
    /// "Exceeding the rate limit"): a 403 or 429 with `retry-after`, or with `x-ratelimit-remaining: 0` until
    /// `x-ratelimit-reset` (UTC epoch seconds).
    fn retry_in(&self) -> Option<u64> {
        let num = |name: &str| self.header(name).and_then(|s| s.trim().parse::<u64>().ok());
        let after = num("retry-after").filter(|s| (1..=3600).contains(s));
        let title =
            serde_json::from_slice::<Value>(&self.body).ok().and_then(|j| j["title"].as_str().map(String::from));
        let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs());
        let reset = num("x-ratelimit-reset").filter(|_| num("x-ratelimit-remaining") == Some(0));
        match () {
            _ if self.status == 429 && title.as_deref() == Some("RATE_LIMIT_EXCEEDED") => after.or(Some(RETRY_AFTER)),
            _ => after.or(reset.map(|t| t.saturating_sub(now).max(1))),
        }
    }

    /// The account's own `x-ratelimit-…-limit` / `-remaining` pair (not the `system_` one every client shares).
    fn limit(&self) -> Option<Limit> {
        let num = |end: &str| {
            let mine = |n: &str| n.starts_with("x-ratelimit-") && !n.contains("system_") && n.ends_with(end);
            self.headers.iter().find(|h| mine(&h.0)).and_then(|h| h.1.trim().parse().ok())
        };
        Some(Limit { limit: num("-limit")?, remaining: num("-remaining")? })
    }
}

/// A header value as a printable token: `[a-z0-9_]`, at most 32 chars; anything else is dropped (empty).
fn token(v: Option<&str>) -> String {
    let v = v.unwrap_or_default().trim().to_ascii_lowercase();
    let ok =
        !v.is_empty() && v.len() <= 32 && v.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_');
    if ok { v } else { String::new() }
}

/// Stand-in for the network in tests (tests/redact.rs): (api, key, request) → reply, set once per process. Only
/// in builds with the `fake` feature; the shipped binary has no such hook.
#[cfg(feature = "fake")]
pub type Fake = fn(Api, &str, &Value) -> Reply;
#[cfg(feature = "fake")]
static FAKE: std::sync::OnceLock<Fake> = std::sync::OnceLock::new();

#[cfg(feature = "fake")]
pub fn fake(f: Fake) {
    FAKE.set(f).ok(); // the first stand-in holds
}

/// A test's stand-in transport answers (`fake`): it lives in this process only, so a detached fetch runs on a
/// thread here, not in a new process (`cli::detach`).
pub fn in_process() -> bool {
    #[cfg(feature = "fake")]
    if FAKE.get().is_some() {
        return true;
    }
    false
}

/// Call a provider API; Ok = the body of a 200. `cap` = the largest body kept (a JSON-escaped page can be twice
/// its size: fetches pass twice their page cap).
async fn api(to: Api, key: &str, req: Value, cap: u64, wait: Duration) -> Result<Answer, Fail> {
    #[cfg(feature = "fake")]
    if let Some(f) = FAKE.get() {
        // a stand-in answer may ask to be slow (`x-fake-delay-ms`): the router's cancel and wait paths under test
        let r = f(to, key, &req);
        let ms = r.header("x-fake-delay-ms").and_then(|v| v.parse().ok()).unwrap_or(0);
        tokio::time::sleep(Duration::from_millis(ms).min(wait)).await;
        return if ms > wait.as_millis() as u64 { Err("provider_timeout".into()) } else { read(to, r) };
    }
    read(to, send(to, key, req, cap, wait).await?)
}

/// The only request that carries a key (`bearer_auth`; none when empty), to `to.url()` only: a POST with `req` as
/// JSON, or a GET with `req`'s string fields as the query. Every call names this tool (`user-agent`).
async fn send(to: Api, key: &str, req: Value, cap: u64, wait: Duration) -> Result<Reply, &'static str> {
    let client = wreq::Client::builder().timeout(wait).build().map_err(|_| "net_error")?;
    let r = match to.row().method {
        "GET" => client.get(to.url(&req)),
        _ => client.post(to.row().url).header("content-type", "application/json").body(req.to_string()),
    };
    let r = r.header("user-agent", concat!("fatsearch/", env!("CARGO_PKG_VERSION")));
    let r = if to.row().accept.is_empty() { r } else { r.header("accept", to.row().accept) };
    let r = if key.is_empty() { r } else { r.bearer_auth(key) };
    let r = r.send().await.map_err(|e| net(&e))?;
    let status = r.status().as_u16();
    let mut reply = Reply { status, headers: pairs(r.headers()), body: Vec::new() };
    reply.body = match (reply.refused(), status) {
        (false, 200) => capped(r, cap).await.map_err(|f| f.code)?,
        // an error body over the cap is not worth keeping; the code says what happened
        _ => capped(r, crate::settings::limit("err_cap_bytes")).await.unwrap_or_default(),
    };
    Ok(reply)
}

/// A provider API's 200: the body, the request budget (`Reply::limit`), and the target's own status where the API
/// reports it in a header: Bright Data's `/request` answers 200 once its unlocker ran and puts the site's status in
/// `x-brd-status-code` (docs.brightdata.com products/web-unlocker/error-codes, "Direct API").
type Answer = (Vec<u8>, Option<Limit>, Option<u16>);

/// A reply → the 200 body, or the code + the masked body for `error.txt`.
/// A 200 with an empty body is a failure too: no API answers a good call with nothing. A rate limit that says
/// when to retry (`Reply::retry_in`) gets `retry in Ns`; another 429 may be an exhausted quota (Oxylabs' docs give
/// no title for it), so it gets no retry time; another 403 is a refused key.
fn read(to: Api, r: Reply) -> Result<Answer, Fail> {
    let limit = r.limit();
    let target = r.header("x-brd-status-code").and_then(|s| s.trim().parse().ok());
    // our setup: Bright Data's 400 naming the zone we sent (`zone "nozone" not found`:
    // its own APIs, the name quoted, a 200 never decoded), its zone-cost read's 422 `Unknown zone` (live
    // 2026-10-15, naming none)
    let named = |z: &str| match (to, r.status) {
        (Api::BdZoneCost, 422) => true,
        (Api::BdRequest | Api::BdZoneCost, 400) => String::from_utf8_lossy(&r.body).contains(&format!("zone \"{z}\"")),
        _ => false,
    };
    let zone = crate::settings::zone().filter(|z| !z.is_empty() && named(z));
    let (code, why) = match (r.refused(), r.status) {
        (false, 200) if !r.body.is_empty() => return Ok((r.body, limit, target)),
        (false, 200) => ("provider_error", "empty".into()),
        (true, _) => bd_refused(token(r.header("x-brd-error-code")), r.header("x-brd-status-code"), r.retry_in()),
        (_, 400 | 422) if let Some(z) = zone => ("bad_zone", z.into()),
        (_, 403 | 429) if let Some(s) = r.retry_in() => ("rate_limited", format!("retry in {s}s")),
        (_, 401 | 403) => ("bad_key", String::new()),
        (_, 408) => ("provider_timeout", String::new()),
        (_, 429) => ("rate_limited", String::new()),
        _ => ("provider_error", String::new()),
    };
    let body = crate::lang::redact(&String::from_utf8_lossy(&r.body), &crate::settings::secrets()).into_bytes();
    Err(Fail { code, status: r.status, body, why, limit })
}

/// Bright Data's refusal (`x-brd-error-code`, the `why`) → our code: a rate limit is a wait, not a no
/// (`bucket_rate_limit`, the same eBay URL served 4 min later), with its retry time when sent; a site status it
/// relayed (`http_status` + `x-brd-status-code: 403`: a 0-byte body, the zone counter +0) is the
/// site's block; anything else its own policy (`provider_refused`). None of them is billed (`charged`: no answer).
fn bd_refused(why: String, site: Option<&str>, retry: Option<u64>) -> (&'static str, String) {
    const SITE: [&str; 4] = ["blocked_401", "blocked_403", "blocked_429", "blocked_451"];
    let relayed = site.and_then(|s| SITE.into_iter().find(|c| c[8..] == *s.trim())).filter(|_| why == "http_status");
    match retry {
        _ if !why.contains("rate_limit") => (relayed.unwrap_or("provider_refused"), why),
        Some(s) => ("rate_limited", format!("{why} retry in {s}s")),
        None => ("rate_limited", why),
    }
}

/// Web Unlocker REST: `{zone, url, format: "json", country}` → `{status_code, headers, body}` (the BD CLI's
/// request shape; `country` = lower-case ISO alpha-2, docs.brightdata.com api-reference unlock-website; sent only
/// when one is named, `bd_body`). The page's
/// final URL is `headers["x-unblocker-redirected-to"]` when the site redirected (observed live 2026-10-13 on a
/// wrong product slug; not in the unlock-website docs); absent = the asked URL.
async fn brightdata(ask: &Ask, key: &str, wait: Duration) -> Result<Raw, Fail> {
    let (body, _, target) = api(Api::BdRequest, key, bd_body(ask), 2 * ask.max_bytes, wait).await?;
    if ask.doc {
        // the target's body and status as sent (a failure is a header + empty body, `read`). A page (a `/pdf/`
        // path that was not a file) is decoded to UTF-8 like plain's
        let (body, charset) = decode_body(body, None);
        let status = target.unwrap_or(200);
        return Ok(Raw { status, final_url: ask.url.clone(), body, charset, ..Raw::default() });
    }
    let j: Value = serde_json::from_slice(&body).map_err(|_| "provider_error")?;
    // its own policy refusal inside the answer: `x-brd-error` among the headers beside a `status_code` below 500
    // that is Bright Data's, not the site's (a bad port: 403, empty body; zone counter +0 four times).
    // Beside a 5xx it is an unlock failure (`reject_block`), retried as the 5xx it is (`fetch::FINAL`)
    let inner = |k: &str| j["headers"][k].as_str();
    if inner("x-brd-error").is_some() && j["status_code"].as_u64().is_some_and(|s| s < 500) {
        let why = token(inner("x-brd-err-code").or(inner("x-brd-error-code")));
        let (code, why) = bd_refused(why, inner("x-brd-status-code"), None);
        return Err(Fail { why, ..Fail::from(code) });
    }
    let headers =
        header_lines(j["headers"].as_object().into_iter().flatten().map(|(k, v)| (k, v.as_str().unwrap_or(""))));
    // no `status_code` = 200; one that is no HTTP status is a broken answer, never truncated (65940 → 404)
    let status = j["status_code"].as_u64().map_or(Ok(200), u16::try_from).map_err(|_| "provider_error")?;
    Ok(Raw {
        status,
        final_url: j["headers"]["x-unblocker-redirected-to"].as_str().unwrap_or(&ask.url).to_string(),
        headers,
        body: j["body"].as_str().unwrap_or_default().as_bytes().to_vec(),
        ..Raw::default()
    })
}

/// The country a page's domain names, upper case: its ccTLD's `Providers::cctld` row (sites that answer best from
/// inside the country; `.uk` → GB); a gTLD names none.
pub fn domain_country(url: &str) -> Option<String> {
    let host = crate::clean::host_of(url);
    PROVIDERS.cctld.get(host.rsplit('.').next().unwrap_or_default()).map(|c| c[..2].to_uppercase())
}

/// `FATS_COUNTRY`, upper case: `US` unless set, the country of the Accept-Language plain sends (`settings`).
pub fn home() -> String {
    crate::settings::get().country.value.to_uppercase()
}

/// THE geo rule (from a replay of saved copies): the country a page call of `t` sends, upper
/// case: the one named (`country:`; an empty one names none), else the domain's (`domain_country`), else `home`:
/// always on Oxylabs, whose unset `location` is a random exit (developers.oxylabs.io products/web-api/scrape; 196
/// saved paid copies: none sent = 18 of 110 in another language, a country sent = 0 of 8; Reddit's captcha
/// came at either exit, 0 of 10), on Bright Data only when it is not the default `US`, else none there: its unset
/// default is the best location for the target (docs.brightdata.com products/web-unlocker features; 2 of 77 saved
/// copies foreign). Plain sends none. A copy in another language is flagged (`fetch::geo`) with a fix that changes
/// the request (`outline::geo_fix`). What the serving call sent is the page's `meta.json` country (`stats` `@FR`).
pub fn sent(ask: &Ask, t: Tier) -> Option<String> {
    let named = ask.country.as_ref().filter(|c| !c.is_empty()).map(|c| c.to_uppercase());
    let home = Some(home()).filter(|h| h != "US" || t.owner() == Tier::Oxy);
    (t != Tier::Plain).then(|| named.or_else(|| domain_country(&ask.url)).or(home)).flatten()
}

/// Web Unlocker `/request` body: `country` only when one is `sent`, `format: raw` for a file's bytes.
fn bd_body(ask: &Ask) -> Value {
    let format = if ask.doc { "raw" } else { "json" };
    let mut req = json!({"zone": crate::settings::zone(), "url": ask.url, "format": format});
    if let Some(c) = sent(ask, Tier::Bd) {
        req["country"] = c.to_lowercase().into();
    }
    req
}

/// Web API `/v1/scrape` request: `{url, output: ["html"], run_js, location, device}` (developers.oxylabs.io
/// products/web-api/scrape: `location` = ISO alpha-2, `sent`, never empty; `device` = `desktop` (default) or
/// `mobile`). `run_js` is always sent: the same page says an omitted `run_js` takes "the optimal execution path",
/// which may render (and bill) JavaScript, and to pass `"run_js": false` for static pages.
fn oxy_body(ask: &Ask) -> Value {
    let mut req = json!({"url": ask.url, "output": ["html"], "run_js": ask.js, "location": sent(ask, Tier::Oxy)});
    if ask.mobile {
        req["device"] = "mobile".into();
    }
    req
}

/// `/v1/scrape` → `results[0].html`; a file (PDF, zip magic) comes back as bytes (`file_bytes`). The JSON cap is
/// 5× the page cap: a file byte can take 5 JSON bytes (`\\x9c`).
async fn oxylabs(ask: &Ask, key: &str, wait: Duration) -> Result<Raw, Fail> {
    let (body, limit, _) = api(Api::OxyScrape, key, oxy_body(ask), 5 * ask.max_bytes, wait).await?;
    let j: Value = serde_json::from_slice(&body).map_err(|_| "provider_error")?;
    let r = &j["results"][0];
    let html = r["html"].as_str().ok_or("provider_error")?.as_bytes();
    // the target's own answer (a 404 page is a 404, not a page): `metadata.statuses.http_request.code`, observed
    // live 2026-10-13, not in the /scrape docs (developers.oxylabs.io products/web-api/scrape.md); absent = 200
    let status = r["metadata"]["statuses"]["http_request"]["code"].as_u64().and_then(|c| u16::try_from(c).ok());
    Ok(Raw {
        status: status.unwrap_or(200),
        final_url: r["metadata"]["url"].as_str().unwrap_or(&ask.url).to_string(),
        body: if crate::clean::sniff(html).is_some() { file_bytes(html) } else { html.to_vec() },
        limit,
        ..Raw::default()
    })
}

/// A file's bytes from Oxylabs' `html` string. It is the file decoded as UTF-8 with every byte that does not
/// decode written as the 4 characters `\xNN` (Python's `backslashreplace`: lower-case hex, and only bytes
/// 0x80–0xff, since every byte below 0x80 decodes). So only `\x[89a-f][0-9a-f]` is an escape; a `\x48` is the
/// file's own text. Measured: arXiv 2405.15793 (4,963,538 B) holds two such runs; reading every `\xNN` as an
/// escape left it 6 bytes short; this rule gives it back byte for byte.
/// Still ambiguous: the file's own text `\x80`–`\xff`; a PDF copy it broke fails `pdf::xref_ok` (`pdf_mangled`), so
/// the ladder goes on to Bright Data's raw bytes.
fn file_bytes(s: &[u8]) -> Vec<u8> {
    let hex = |c: u8| (c as char).to_digit(16).filter(|_| !c.is_ascii_uppercase()).map(|d| d as u8);
    let (mut out, mut i) = (Vec::with_capacity(s.len()), 0);
    while i < s.len() {
        match (&s[i..], s.get(i + 2).copied().and_then(hex), s.get(i + 3).copied().and_then(hex)) {
            ([b'\\', b'x', ..], Some(h @ 8..), Some(l)) => {
                out.push(h << 4 | l);
                i += 4;
            }
            _ => {
                out.push(s[i]);
                i += 1;
            }
        }
    }
    out
}

// ---------------------------------------------------------------- web search

/// One web search result.
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct Hit {
    pub url: String,
    pub title: String,
    pub snippet: String,
}

/// Tiers that search = the `search` rows (`Spec::can`): Oxylabs Web API `/v1/search`, then Google results through
/// the Bright Data zone. Results per call: 1–20 (`max_results`, Oxylabs search docs); one wait for both.
pub const SEARCH_MAX: usize = 20;
pub const SEARCH_TIMEOUT: Duration = Duration::from_secs(15);

/// THE spend text: `$0.0225`, and `+ ≤$0.0060 unverified` when calls we cut may have been billed.
pub fn bill(cost: f64, upto: f64) -> String {
    if upto > 0.0 { format!("${cost:.4} + ≤${upto:.4} unverified") } else { format!("${cost:.4}") }
}

/// The request for one search: (endpoint, body). Oxylabs (developers.oxylabs.io products/web-api/search):
/// `{query, max_results, location}`, `location` = ISO alpha-2, unknown fields are a 400. Bright Data: a Google
/// URL with `brd_json=1` (parsed JSON, as the BD CLI's `search` sends it) and `gl` for the country, through the
/// `/request` API (`country` = proxy location, BD SERP API reference). Google returns about 10 results a page.
fn search_req(t: Tier, q: &str, limit: usize, country: Option<&str>) -> (Api, Value) {
    let c = search_country(country);
    if t == Tier::Bd {
        let p = [("q", q.to_string()), ("brd_json", "1".into()), ("gl", c.to_lowercase())];
        let url =
            url::Url::parse_with_params("https://www.google.com/search", &p).map(String::from).unwrap_or_default();
        let req = json!({"zone": crate::settings::zone(), "url": url, "format": "json", "country": c.to_lowercase()});
        return (Api::BdRequest, req);
    }
    (Api::OxySearch, json!({"query": q, "max_results": limit.min(SEARCH_MAX), "location": c}))
}

/// The country a search sends, both providers: `country:`, else `home` (never none: Google's `gl`).
pub fn search_country(country: Option<&str>) -> String {
    country.filter(|c| !c.is_empty()).map_or_else(home, str::to_uppercase)
}

/// A search answer → hits, best first. Oxylabs: `results[].{url, title, outline[]}`. Bright Data: `organic[].{link,
/// title, description}`, top level from a SERP zone, inside the `body` string from an unlocker zone.
pub fn hits(t: Tier, body: &[u8], limit: usize) -> Result<Vec<Hit>, &'static str> {
    let j: Value = serde_json::from_slice(body).map_err(|_| "provider_error")?;
    let s = |v: &Value| crate::clean::collapse(v.as_str().unwrap_or_default());
    let (list, url, snip) = match t {
        Tier::Bd => {
            let inner = j["body"].as_str().and_then(|b| serde_json::from_str::<Value>(b).ok()).unwrap_or_default();
            let j = if j["organic"].is_array() { &j } else { &inner };
            (j["organic"].as_array().cloned().ok_or("provider_error")?, "link", "description")
        }
        _ => (j["results"].as_array().cloned().ok_or("provider_error")?, "url", "outline"),
    };
    let hits = list.iter().filter(|r| r[url].is_string()).take(limit);
    Ok(hits
        .map(|r| Hit {
            url: s(&r[url]),
            title: s(&r["title"]),
            snippet: if r[snip].is_array() { s(&r[snip][0]) } else { s(&r[snip]) },
        })
        .collect())
}

/// One search call. `billed` as in `get`.
pub async fn search(
    t: Tier,
    q: &str,
    limit: usize,
    country: Option<&str>,
    wait: Duration,
) -> (Result<(Vec<Hit>, Option<Limit>), Fail>, bool) {
    let key = t.key().unwrap_or_default();
    let (to, req) = search_req(t, q, limit, country);
    let r = api(to, &key, req, 2 * crate::cli::MAX_BYTES, wait).await;
    let r = r.and_then(|(body, lim, _)| hits(t, &body, limit).map(|h| (h, lim)).map_err(Fail::from));
    // an answer without a result list is bd's failed SERP: the zone counter +0 for 2
    let billed = charged(t, r.as_ref().map(|_| 200));
    (r, billed)
}

/// `fats gh <words>`: GitHub REST `GET /search/repositories` sorted by stars (docs.github.com rest/search "Search
/// repositories": `q`, `sort=stars`, `order`, `per_page`), free: 30 searches a minute with a token, 10 without.
/// A login-shaped word (`[A-Za-z0-9-]`, ≤ 39: GitHub's username rule) also lists that account's repos, at once,
/// its top 100 by stars (`q=user:<login>`, one more search; `GET /users/{q}/repos` holds only its 100 last pushed,
/// so a ★71 repo of an account with 164 was missing), that list only for an account the search leaves out (422
/// with or without a token, seen live on a real account) or none (then 404): a login's own repos rarely bear it in
/// their text (0 hits, or repos about the person). The lists merge by stars, so a
/// squatter account of a topic word (★0 repos) stays below the topic's hits. A repository → a hit: its page,
/// `★12.4k owner/repo`, `description (80 chars) · pushed YYYY-MM-DD`. Ok = the hits + each call's code and `=` line
/// note (the search's, then the account's: ` · no user <q>`, ` · user lookup: rate_limited retry in 60s`); the
/// account's failure with no hit at all is the answer's (`! rate_limited gh user <q> …`), never `0 results`.
pub async fn gh_repos(q: String, limit: usize) -> Result<(Vec<Hit>, Vec<(&'static str, String)>), Fail> {
    let (key, per) = (crate::settings::gh_token(), limit.min(crate::settings::limit("gh_max")));
    let call = |to: Api, req: Value| api(to, &key, req, 4 << 20, SEARCH_TIMEOUT);
    let login = q.len() <= 39 && !q.contains(|c: char| !c.is_ascii_alphanumeric() && c != '-');
    let user = login.then_some(async {
        let by_stars = json!({"q": format!("user:{q}"), "sort": "stars", "order": "desc", "per_page": "100"});
        match call(Api::GhRepos, by_stars).await {
            Err(f) if f.status == 422 => call(Api::GhUser, json!({"q": q, "sort": "pushed", "per_page": "100"})).await,
            r => r,
        }
    });
    let req = json!({"q": q, "sort": "stars", "order": "desc", "per_page": per.to_string()});
    let (found, user) = tokio::join!(call(Api::GhRepos, req), async { Some(user?.await) });
    let items =
        |r: Result<Answer, Fail>| serde_json::from_slice::<Value>(&r?.0).map_err(|_| Fail::from("provider_error"));
    let items = |r| items(r).map(|j| j["items"].as_array().or(j.as_array()).cloned().unwrap_or_default());
    let mut repos = items(found)?;
    // the account call's hop (`cli::github`): its code and the `=` line's note when it got no list
    let user = match user.map(items) {
        Some(Err(f)) if f.status == 404 => Some(("not_found", format!(" · no user {q}"))),
        Some(Err(f)) if repos.is_empty() => return Err(Fail { why: format!("user {q} {}", f.why), ..f }),
        Some(Err(f)) => Some((f.code, format!(" · user lookup: {} {}", f.code, f.why).trim_end().into())),
        theirs => theirs.map(|r| repos.extend(r.unwrap_or_default())).map(|()| ("ok", String::new())),
    };
    repos.sort_by_key(|r| std::cmp::Reverse(r["stargazers_count"].as_u64()));
    let s = |v: &Value| crate::clean::collapse(v.as_str().unwrap_or_default());
    let hit = |r: &Value| {
        let stars = crate::lang::ksize(r["stargazers_count"].as_u64().unwrap_or(0) as usize);
        let pushed = format!("pushed {}", crate::lang::cut(&s(&r["pushed_at"]), 10));
        let about: Vec<String> =
            [crate::lang::short(&s(&r["description"]), 80), pushed].into_iter().filter(|x| !x.is_empty()).collect();
        Hit { url: s(&r["html_url"]), title: format!("★{stars} {}", s(&r["full_name"])), snippet: about.join(" · ") }
    };
    let on_github =
        |h: &Hit| url::Url::parse(&h.url).is_ok_and(|u| u.scheme() == "https" && u.host_str() == Some("github.com"));
    let hits = crate::lang::uniq(repos.iter().map(hit).filter(on_github), |h| h.url.clone());
    Ok((hits.into_iter().take(per).collect(), [("ok", String::new())].into_iter().chain(user).collect()))
}

// ---------------------------------------------------------------- account (`fats account`)

/// The providers `fats account` reads, in row order.
pub const ACCOUNTS: [Tier; 2] = [Tier::Oxy, Tier::Bd];
/// Per call; the account APIs answered in 0.1–0.5 s (measured 2026-10-12).
pub const ACCOUNT_TIMEOUT: Duration = Duration::from_secs(10);
/// The largest account answer kept (the scraper list is ~14 KB).
const ACCOUNT_CAP: u64 = 1 << 20;

/// One provider's account as read from its answers (never the answers themselves). None = not offered or not read.
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(default)]
pub struct Account {
    /// `oxy`, `bd`.
    pub provider: String,
    /// `ok`, or the failed call's code (`bad_key`, `rate_limited` …); `why` = its printable token.
    pub code: String,
    #[serde(skip_serializing_if = "String::is_empty")]
    pub why: String,
    pub ms: u64,
    pub calls: usize,
    pub scrapers: Option<usize>,
    /// USD.
    pub balance: Option<f64>,
    /// USD this calendar month (UTC).
    pub spend: Option<f64>,
    pub reqs_unblocker: Option<u64>,
    pub reqs_serp: Option<u64>,
    /// USD this month on the zone fats calls (`BRIGHTDATA_UNLOCKER_ZONE`): what `stats` reconciles against.
    pub zone_cost: Option<f64>,
    pub zones: Vec<String>,
    /// The reads a scoped key may not make (403 on that one only), by endpoint (`stats::READS` names them).
    pub denied: Vec<Api>,
}

/// The calls one provider's account takes, in order, with their request fields. `month` = (its first day, the
/// next month's first day), `YYYY-MM-DD` UTC (Bright Data: `to` is exclusive). The zone's month needs the
/// configured zone and is skipped without one.
pub fn account_calls(t: Tier, month: (&str, &str), zone: Option<&str>) -> Vec<(Api, Value)> {
    let (from, to) = month;
    match t {
        Tier::Bd => {
            let mut v = vec![
                (Api::BdBalance, json!({})),
                (Api::BdZones, json!({})),
                (Api::BdCosts, json!({"dimension": "products", "filters": {}, "from": from, "to": to})),
            ];
            v.extend(zone.map(|z| (Api::BdZoneCost, json!({"from": from, "to": to, "zone": z}))));
            v
        }
        _ => vec![(Api::OxyScrapers, json!({}))],
    }
}

/// One account answer into `a`. Bright Data's cost export has a key per day **and** a `total` key: the month's
/// spend is the sum of `total` only (summing every key counts each day twice). A zone's month is keyed by
/// customer, then plan: requests are summed over the plans.
pub fn account_read(a: &mut Account, to: Api, body: &[u8]) {
    let j: Value = serde_json::from_slice(body).unwrap_or_default();
    match to {
        Api::OxyScrapers => a.scrapers = j["scrapers"].as_array().map(Vec::len),
        Api::BdBalance => a.balance = j["balance"].as_f64(),
        Api::BdZones => {
            let z = j.as_array().into_iter().flatten().filter_map(|z| z["type"].as_str().map(String::from));
            a.zones = z.collect::<std::collections::BTreeSet<_>>().into_iter().collect();
        }
        Api::BdCosts => a.spend = j["total"].as_object().map(|t| spend(t.values().filter_map(Value::as_f64))),
        Api::BdZoneCost => {
            let customers = j.as_object().into_iter().flat_map(|c| c.values());
            let plans: Vec<&Value> = customers.filter_map(Value::as_object).flat_map(|p| p.values()).collect();
            let sum = |k: &str| plans.iter().map(|p| p[k].as_u64()).sum::<Option<u64>>();
            let n = |k: &str| sum(k).filter(|_| !plans.is_empty());
            (a.reqs_unblocker, a.reqs_serp) = (n("reqs_unblocker"), n("reqs_serp"));
            a.zone_cost = plans.iter().map(|p| p["cost"].as_f64()).sum::<Option<f64>>().filter(|_| !plans.is_empty());
        }
        _ => {}
    }
}

/// Read one provider's account: its calls in order; the first failure stops the rest (a refused key fails them
/// all). A 403 on one read is a key scoped without it (Bright Data's per-permission keys: `denied`, the rest
/// read on); a 401, or a 403 on every read, is a bad key. Answers are parsed and dropped; an error body is never
/// kept.
pub async fn account(t: Tier, key: String, month: (String, String), zone: Option<&str>) -> Account {
    let t0 = std::time::Instant::now();
    let mut a = Account { provider: t.spec().short.into(), code: "ok".into(), ..Account::default() };
    for (to, req) in account_calls(t, (&month.0, &month.1), zone) {
        a.calls += 1;
        match api(to, &key, req, ACCOUNT_CAP, ACCOUNT_TIMEOUT).await {
            Ok((body, ..)) => account_read(&mut a, to, &body),
            Err(f) if f.status == 403 && f.code == "bad_key" => {
                a.denied.push(to);
            }
            Err(f) => {
                (a.code, a.why) = (f.code.into(), f.why);
                break;
            }
        }
    }
    if a.denied.len() == a.calls {
        a.code = "bad_key".into();
    }
    a.ms = t0.elapsed().as_millis() as u64;
    a
}

/// One free read with a key and no request fields (`OxyScrapers`, `BdZones`): its JSON (the body is dropped).
pub async fn read_json(to: Api, key: String) -> Result<Value, Fail> {
    let (body, ..) = api(to, &key, json!({}), ACCOUNT_CAP, ACCOUNT_TIMEOUT).await?;
    Ok(serde_json::from_slice(&body).unwrap_or_default())
}

/// Safari 26 on macOS (TLS ClientHello, HTTP/2 settings, navigation headers, as maintained by wreq-util). Measured
/// on 121 test URLs, one run each: Safari 26 passed 85, Chrome 149 73 (Cloudflare challenged it more).
fn browser() -> wreq_util::Emulation {
    wreq_util::Emulation::builder().profile(wreq_util::Profile::Safari26).platform(wreq_util::Platform::MacOS).build()
}

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

    /// THE billing rule (bd's zone counter): an answer below 500 is billed, a 5xx (bd's
    /// `http_502`), a timeout (a search's too: counter +0 for 2) or a refusal is not, for both providers.
    #[test]
    fn charged_only_on_a_charged_reply() {
        let (late, err) = (Fail::from("provider_timeout"), Fail::from("provider_error"));
        for t in [Tier::Oxy, Tier::OxyJs, Tier::Bd] {
            let fetch = |s| charged(t, s);
            assert!(fetch(Ok(200)) && fetch(Ok(404)), "{t:?}: an answer");
            // Oxylabs' finished job relaying the site's 502 is billed; Bright Data's inner 5xx is not
            assert_eq!(fetch(Ok(502)), t != Tier::Bd, "{t:?}: a site's 5xx");
            assert!(!fetch(Err(&late)) && !fetch(Err(&err)), "{t:?}: a timeout or refusal is free");
        }
        assert!(!charged(Tier::Plain, Ok(200)), "plain is free");
    }

    /// The Oxylabs request always says `run_js` and a `location` (`US` where nothing names one: an unset one is a
    /// random exit), and carries `device` only for `device:mobile` (desktop is the API's default).
    #[test]
    fn oxy_request_body() {
        let ask = Ask { url: "https://ex.com/a".into(), ..Ask::default() };
        let want = json!({"url": "https://ex.com/a", "output": ["html"], "run_js": false, "location": "US"});
        assert_eq!(oxy_body(&ask), want);
        let ask = Ask { url: "https://ex.com/a".into(), js: true, mobile: true, ..Ask::default() };
        assert_eq!(
            oxy_body(&ask),
            json!({"url": "https://ex.com/a", "output": ["html"], "run_js": true, "location": "US", "device": "mobile"})
        );
        assert_eq!(oxy_body(&Ask { url: "https://www.lemonde.fr/".into(), ..Ask::default() })["location"], "FR");
    }

    /// Oxylabs' escaped file → the file: only lower-case `\x80`–`\xff` are escapes; the file's own `\x48`, an
    /// upper-case `\x9C`, a cut `\x9` and UTF-8 stay as they are (the arXiv case: two literal runs, 0 bytes lost).
    #[test]
    fn oxylabs_file_bytes() {
        let file: &[u8] = b"%PDF-1.5 \x9c\xff\\x48 \xc3\xa9 \\x9C \\x9";
        let escaped = r"%PDF-1.5 \x9c\xff\x48 é \x9C \x9";
        assert_eq!(file_bytes(escaped.as_bytes()), file);
    }

    /// A key goes only to `Providers::apis`: scrape, search and account reads on the two provider API hosts, never an
    /// endpoint that returns secrets (Bright Data `GET /zone`, `/zone/passwords`; Webshare `/proxy/list`), and a
    /// POST only where the docs make it a query. `send` is the only request with a key, and no provider URL is
    /// written outside `apis` and `links` in providers.json (pages printed for people, never requested): a new one is a visible row.
    #[test]
    fn keys_go_only_to_listed_endpoints() {
        // 1.1.1.1 (DoH) is sent no key: `exists` passes an empty one, which `send` never puts in a header
        const HOSTS: &[&str] = &["api.brightdata.com", "webapi.oxylabs.io", "1.1.1.1", "api.github.com"];
        const NEVER: &[&str] = &["password", "/proxy/list", "/billing", "/account", "/users"];
        const POST: &[&str] = &["/request", "/scrape", "/search", "/costs/export/json"];
        for (i, ApiRow { api, method, url, .. }) in PROVIDERS.apis.iter().enumerate() {
            assert_eq!(*api as usize, i, "apis is indexed by Api");
            let u = url::Url::parse(url).expect("url");
            assert_eq!(u.scheme(), "https", "{url}");
            assert!(HOSTS.contains(&u.host_str().unwrap_or_default()), "{url}: unlisted host");
            let p = u.path();
            // GitHub's `/users/{login}/repos` lists an account's public repositories, nothing of the caller's
            let public = u.host_str() == Some("api.github.com") && p.ends_with("/repos");
            assert!(p != "/zone" && (public || NEVER.iter().all(|n| !p.contains(n))), "{url}: returns secrets");
            assert!(*method == "GET" || (*method == "POST" && POST.iter().any(|e| p.ends_with(e))), "{url}");
        }
        let links: Vec<&str> =
            PROVIDERS.links.iter().flat_map(|l| [Some(l.signup), l.keys, l.billing, l.usage]).flatten().collect();
        assert!(links.iter().all(|l| l.starts_with("https://")));
        let src: String = [
            include_str!("provider.rs"),
            include_str!("fetch.rs"),
            include_str!("cli.rs"),
            include_str!("stats.rs"),
            include_str!("settings.rs"),
            include_str!("mcp.rs"),
            include_str!("data/providers.json"),
        ]
        .iter()
        .map(|f| f.split("#[cfg(test)]").next().unwrap_or_default())
        .collect();
        assert_eq!(src.matches("bearer_auth(").count(), 1, "one request carries a key");
        assert!(!src.contains("basic_auth(") && !src.to_ascii_lowercase().contains("\"authorization\""));
        let listed: Vec<&str> = PROVIDERS.apis.iter().map(|a| a.url).chain(links).collect();
        let provider =
            ["oxylabs.io", "brightdata.com", "luminati", "webshare.io", "decodo.com", "1.1.1.1", "github.com"];
        let lits: Vec<String> =
            src.split("\"http").skip(1).filter_map(|r| r.split('"').next()).map(|r| format!("http{r}")).collect();
        let found: Vec<&String> = lits.iter().filter(|l| provider.iter().any(|h| l.contains(h))).collect();
        assert_eq!(found.len(), listed.len(), "each provider URL is written once, in apis or links: {found:?}");
        assert!(found.iter().all(|l| listed.contains(&l.as_str())), "provider URL outside apis/links: {found:?}");
    }

    /// A provider's answer → a code; an error body is kept for `error.txt`, the 200 body is the answer.
    #[test]
    fn replies_become_codes() {
        let r = |status, refused: bool, body: &str| {
            let h = [
                ("x-brd-error", "Access denied: x.gov is classified as Government"),
                ("x-brd-error-code", "proxy_error"),
            ];
            let headers = h.iter().filter(|_| refused).map(|(k, v)| (k.to_string(), v.to_string())).collect();
            read(Api::BdRequest, Reply { status, headers, body: body.into() })
        };
        assert_eq!(r(200, false, "{}"), Ok((b"{}".to_vec(), None, None)));
        let raw = Reply { status: 200, headers: vec![("x-brd-status-code".into(), "404".into())], body: b"<p>".into() };
        assert_eq!(read(Api::BdRequest, raw), Ok((b"<p>".to_vec(), None, Some(404))), "Bright Data's target status");
        let empty = r(200, false, "").expect_err("200 + empty body");
        assert_eq!((empty.code, empty.why.as_str()), ("provider_error", "empty"));
        let gov = r(200, true, "").expect_err("Bright Data refusal");
        assert_eq!(
            (gov.code, gov.why.as_str()),
            ("provider_refused", "proxy_error"),
            "the code header, not the message"
        );
        // A status bd relayed is the site's block, a rate limit a wait; neither is bd's policy
        let brd = |code: &str, site: &str| {
            let h = [("x-brd-error", "rejected"), ("x-brd-error-code", code), ("x-brd-status-code", site)];
            let f = read(
                Api::BdRequest,
                Reply { status: 200, headers: h.map(|(k, v)| (k.into(), v.into())).to_vec(), body: vec![] },
            );
            f.map_err(|f| (f.code, f.why)).expect_err("refused")
        };
        assert_eq!(brd("http_status", "403"), ("blocked_403", "http_status".into()), "a relayed site 403");
        assert_eq!(brd("http_status", "502").0, "provider_refused", "no site block row");
        assert_eq!(brd("bucket_rate_limit", "").0, "rate_limited", "a rate limit");
        assert_eq!(bd_refused("bucket_rate_limit".into(), None, Some(30)).1, "bucket_rate_limit retry in 30s");
        assert!(!charged(Tier::Bd, Err(&Fail::from("blocked_403"))), "a relayed status is no answer: not billed");
        assert_eq!(token(Some("Access denied: x.gov")), "", "free text is never a token");
        assert_eq!(token(Some(" Proxy_Error ")), "proxy_error");
        let f = r(401, false, "Invalid api key").expect_err("401");
        assert_eq!((f.code, f.status, f.body.as_slice()), ("bad_key", 401, &b"Invalid api key"[..]));
        assert_eq!(r(403, false, "").map_err(|f| f.code), Err("bad_key"));
        assert_eq!(r(408, false, "").map_err(|f| f.code), Err("provider_timeout"));
        assert_eq!(r(429, false, "").map_err(|f| (f.code, f.why)), Err(("rate_limited", String::new())), "quota?");
        let acct = |h: &[(&str, &str)]| Reply {
            status: 429,
            headers: h.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect(),
            body: br#"{"status":429,"title":"RATE_LIMIT_EXCEEDED","detail":"Too many requests."}"#.to_vec(),
        };
        let h = [
            ("x-ratelimit-search_total_dynamic_europe-1234567-limit", "10"),
            ("x-ratelimit-search_total_dynamic_europe-1234567-remaining", "0"),
            ("x-ratelimit-system_search_total_dynamic_europe-remaining", "9999"),
        ];
        let f = read(Api::OxyScrape, acct(&h)).expect_err("429");
        assert_eq!((f.why.as_str(), f.limit), ("retry in 5s", Some(Limit { limit: 10, remaining: 0 })));
        let f = read(Api::OxyScrape, acct(&[("retry-after", "7")])).expect_err("429");
        assert_eq!((f.why.as_str(), f.limit), ("retry in 7s", None), "retry-after wins; no budget sent");
        assert_eq!(
            read(Api::OxyScrape, acct(&[("retry-after", "Wed, 21 Oct 2026 07:28:00 GMT")])).map_err(|f| f.why),
            Err("retry in 5s".into())
        );
        assert_eq!(r(500, false, "<html>oops").map_err(|f| f.code), Err("provider_error"));
    }

    /// Search requests carry only the documented fields; the parser reads both providers' saved answers.
    #[test]
    fn search_requests_and_answers() {
        let (u, r) = search_req(Tier::Oxy, "heidelberg university", 50, Some("fr"));
        assert_eq!(u.row().url, "https://webapi.oxylabs.io/v1/search");
        assert_eq!(r, json!({"query": "heidelberg university", "max_results": 20, "location": "FR"}));
        assert_eq!(search_req(Tier::Oxy, "a", 10, None).1, json!({"query": "a", "max_results": 10, "location": "US"}));
        let none = search_req(Tier::Bd, "a", 10, None).1;
        assert_eq!(
            (none["country"].as_str(), none["url"].as_str()),
            (Some("us"), Some("https://www.google.com/search?q=a&brd_json=1&gl=us"))
        );
        let (u, r) = search_req(Tier::Bd, "a b&c", 10, Some("fr"));
        assert_eq!(u.row().url, "https://api.brightdata.com/request");
        assert_eq!(r["url"], "https://www.google.com/search?q=a+b%26c&brd_json=1&gl=fr");
        assert_eq!((r["format"].as_str(), r["country"].as_str()), (Some("json"), Some("fr")));
        let oxy = hits(Tier::Oxy, include_bytes!("../tests/fixtures/oxy-search.json"), 10).expect("oxy fixture");
        assert_eq!(oxy.len(), 5);
        assert_eq!(
            (oxy[0].url.as_str(), oxy[0].title.as_str()),
            ("https://www.uni-heidelberg.de/en", "Heidelberg University")
        );
        assert!(oxy[0].snippet.starts_with("Heidelberg University – the oldest in Germany"));
        assert_eq!(hits(Tier::Oxy, include_bytes!("../tests/fixtures/oxy-search.json"), 2).map(|h| h.len()), Ok(2));
        let bd = hits(Tier::Bd, include_bytes!("../tests/fixtures/bd-serp.json"), 10).expect("bd fixture");
        assert_eq!(bd.len(), 3);
        assert_eq!(bd[0].url, "https://pizza.example.com/delivery-springfield");
        assert!(bd[0].snippet.starts_with("Example Pizzeria offers fast pizza delivery"));
        assert_eq!(hits(Tier::Oxy, b"<html>", 10), Err("provider_error"));
        assert_eq!(hits(Tier::Oxy, br#"{"state":"done","results":[]}"#, 10), Ok(vec![]));
    }

    /// Account answers in the providers' shapes (made-up numbers) → the fields; BD spend = the `total` key only
    /// (summing every key gives 11.00: each day counted twice).
    #[test]
    fn account_answers() {
        let mut a = Account::default();
        account_read(&mut a, Api::OxyScrapers, include_bytes!("../tests/fixtures/account-oxy-scrapers.json"));
        assert_eq!(a.scrapers, Some(351));
        account_read(&mut a, Api::BdBalance, include_bytes!("../tests/fixtures/account-bd-balance.json"));
        account_read(&mut a, Api::BdZones, include_bytes!("../tests/fixtures/account-bd-zones.json"));
        account_read(&mut a, Api::BdCosts, include_bytes!("../tests/fixtures/account-bd-costs.json"));
        account_read(&mut a, Api::BdZoneCost, include_bytes!("../tests/fixtures/account-bd-zone-cost.json"));
        assert_eq!((a.balance, format!("{:.2}", a.spend.unwrap_or_default())), (Some(1234.56), "5.50".into()));
        assert_eq!((a.reqs_unblocker, a.reqs_serp, a.zone_cost), (Some(1500), Some(700), Some(3.21)));
        let all: Value = serde_json::from_slice(include_bytes!("../tests/fixtures/account-bd-costs.json")).unwrap();
        let every: f64 = all
            .as_object()
            .unwrap()
            .values()
            .flat_map(|d| d.as_object().unwrap().values())
            .filter_map(Value::as_f64)
            .sum();
        assert_eq!(format!("{every:.2}"), "11.00", "the double count the `total` rule avoids");
        assert_eq!(a.zones, ["dc", "serp", "unblocker"], "zone types, sorted, each once");
        let mut b = Account::default();
        account_read(&mut b, Api::BdZoneCost, b"{}");
        account_read(&mut b, Api::BdBalance, b"<html>");
        assert_eq!((b.reqs_unblocker, b.balance, b.zone_cost), (None, None, None), "no answer = n/a, never 0");
        let calls = |z| account_calls(Tier::Bd, ("2026-10-01", "2026-11-01"), z);
        assert_eq!(calls(None).len(), 3, "no zone, no zone month");
        let all = calls(Some("unblocker"));
        assert_eq!(all[3].1, json!({"zone": "unblocker", "from": "2026-10-01", "to": "2026-11-01"}));
        assert_eq!(account_calls(Tier::Oxy, ("", ""), None)[0].0.row().url, "https://webapi.oxylabs.io/v1/scrapers");
    }

    /// `!` row pages: documented URLs only (the Oxylabs keys page is not), by any tier name of the key.
    #[test]
    fn row_pages() {
        assert_eq!(
            pages("no_key", ["oxyjs", "bd"]),
            " · oxyjs https://dashboard.oxylabs.io/en/registration · bd https://brightdata.com/cp/start"
        );
        assert_eq!(pages("bad_key", "oxy bd".split(' ')), format!("{K} · bd https://brightdata.com/cp/setting/users"));
        // developers.oxylabs.io/products/web-api/authentication "Getting a key": only a Web API key works
        const K: &str = " · oxy https://dashboard.oxylabs.io (a Web API instance's key)";
        assert_eq!(pages("bad_key", ["oxy"]), K);
        assert_eq!(pages("provider_error", ["bd"]), "", "only key and money codes");
        assert_eq!(page("low_balance", "bd").as_deref(), Some("https://brightdata.com/cp/billing"));
        assert_eq!(page("no_key", "plain"), None);
    }

    /// ccTLD → country for both providers; `country:` wins; a gTLD names `home` on Oxylabs, none on Bright Data;
    /// plain never has one.
    #[test]
    fn country_from_tld() {
        let at = |url: &str, c: Option<&str>, t: Tier| {
            sent(&Ask { url: url.into(), country: c.map(String::from), ..Ask::default() }, t)
        };
        for (url, want) in [
            ("https://www.lemonde.fr/a", Some("FR")),
            ("https://www.spiegel.de/", Some("DE")),
            ("https://www.bbc.co.uk/news", Some("GB")),
            ("https://www.idealo.fr/x", Some("FR")),
            ("https://ex.gr/", Some("GR")),
            ("https://example.com/", None),
            ("https://europa.eu/", None),
            ("https://crates.io/", None),
            ("https://ex.us/", None),
        ] {
            assert_eq!(at(url, None, Tier::Bd).as_deref(), want, "{url}");
            for t in [Tier::Oxy, Tier::OxyJs] {
                assert_eq!(at(url, None, t).as_deref(), want.or(Some("US")), "{url} {t:?}");
            }
        }
        assert_eq!(at("https://www.lemonde.fr/", Some("de"), Tier::Oxy).as_deref(), Some("DE"), "country: wins");
        assert_eq!(at("https://ex.com/", Some("pl"), Tier::Bd).as_deref(), Some("PL"));
        assert_eq!(at("https://www.lemonde.fr/", Some("de"), Tier::Plain), None);
    }

    /// An Oxylabs page call always names a `location`
    /// (unset = a random exit: 18 of 110 saved copies foreign); a Bright Data page names a country only when one is
    /// named or the domain gives one (unset = its best location for the target).
    #[test]
    fn oxylabs_always_names_a_location_bd_only_a_named_one() {
        let ask = |url: &str, c: Option<&str>| Ask { url: url.into(), country: c.map(String::from), ..Ask::default() };
        for (url, c, oxy, bd) in [
            ("https://example.com/", None, "US", None),
            ("https://example.com/", Some(""), "US", None),
            ("https://www.lemonde.fr/a", None, "FR", Some("fr")),
            ("https://example.com/", Some("de"), "DE", Some("de")),
        ] {
            let a = ask(url, c);
            assert_eq!(oxy_body(&a)["location"].as_str(), Some(oxy), "{url} {c:?}");
            assert_eq!(bd_body(&a).get("country").and_then(Value::as_str), bd, "{url} {c:?}");
        }
    }

    /// Every spelling of a private address is private; public ones pass.
    #[test]
    fn private_addresses() {
        for ip in [
            "127.0.0.1", "10.1.2.3", "172.16.0.1", "192.168.1.1", "169.254.169.254", "100.64.0.1", "0.0.0.0",
            "255.255.255.255", "224.0.0.1", "240.0.0.1", "198.18.0.1", "192.0.0.8", "::1", "::", "fe80::1", "fc00::1",
            "fd12::1", "::ffff:127.0.0.1", "::ffff:10.0.0.1", "64:ff9b::a9fe:a9fe", "2001:db8::1", "::7f00:1",
            "::a9fe:a9fe", "2002:7f00:1::", "2002:c0a8:101::1",
        ] {
            assert!(private_ip(ip.parse().unwrap()), "{ip} is private");
        }
        for ip in
            ["8.8.8.8", "1.1.1.1", "172.32.0.1", "100.128.0.1", "2606:4700::1111", "::ffff:8.8.8.8", "2002:808:808::1"]
        {
            assert!(!private_ip(ip.parse().unwrap()), "{ip} is public");
        }
        for url in [
            "http://localhost:8080/",
            "http://api.localhost/",
            "http://127.0.0.1/",
            "http://2130706433/",
            "http://0x7f.1/",
            "http://[::1]/",
            "http://169.254.169.254/latest/meta-data/",
            "http://10.0.0.1:9000/x",
            "data:text/html,hi",
        ] {
            assert!(private_host(url), "{url} is refused");
        }
        assert!(!private_host("https://example.com/") && !private_host("http://8.8.8.8/"));
    }

    /// Redirects run through the fence: a public page that bounces to the metadata address is refused before
    /// the second request; relative Locations resolve; an endless chain stops.
    #[test]
    fn redirects_are_fenced() {
        let rt = tokio::runtime::Builder::new_current_thread().build().unwrap();
        let calls = std::cell::RefCell::new(Vec::<String>::new());
        let fake = |to: Option<&'static str>| {
            let calls = &calls;
            move |u: String| {
                calls.borrow_mut().push(u);
                let reply = match to {
                    Some(t) => (302, Some(t.to_string()), ()),
                    None => (200, None, ()),
                };
                std::future::ready(Ok::<_, &'static str>(reply))
            }
        };
        let r = rt.block_on(follow("https://ex.com/a", fake(Some("http://169.254.169.254/latest/meta-data/"))));
        assert_eq!(r.err(), Some("private_address"));
        assert_eq!(*calls.borrow(), ["https://ex.com/a"], "the private hop is never requested");
        calls.borrow_mut().clear();
        assert_eq!(
            rt.block_on(follow("https://ex.com/a", fake(Some("http://[::ffff:7f00:1]/")))).err(),
            Some("private_address")
        );
        calls.borrow_mut().clear();
        assert_eq!(rt.block_on(follow("https://ex.com/a", fake(Some("/b")))).err(), Some("redirect_loop"));
        assert_eq!(calls.borrow().len(), 11, "the first request + 10 redirects");
        assert!(calls.borrow()[1..].iter().all(|u| u == "https://ex.com/b"));
        let ok = rt.block_on(follow("https://ex.com/a", fake(None)));
        assert_eq!(ok.map(|r| r.0), Ok("https://ex.com/a".to_string()));
    }

    /// A DNS name that resolves only to loopback gets no address (`localhost` resolves from the hosts file,
    /// no network), and the error is recognised as `private_address`.
    #[test]
    fn resolver_drops_private_answers() {
        use wreq::dns::Resolve;
        let rt = tokio::runtime::Builder::new_current_thread().build().unwrap();
        let e = rt.block_on(Fence.resolve("localhost".into())).err().expect("refused");
        assert!(e.is::<Private>());
    }
}