rustai-core 0.3.0

Zero-cost local research pipeline: async search routing, TLS-fingerprint-aware fetching, SIMD DOM denoising and BM25 context slimming for local LLMs.
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
//! Python bindings.
//!
//! The shape of this API is deliberately boring: blocking methods that look
//! like `requests`, returning plain objects with attributes. Async Rust is an
//! implementation detail, not something a caller should have to adopt.
//!
//! Every method that touches the network or the rayon pool releases the GIL for
//! its whole duration, so a `rustai` call in one Python thread does not stall
//! the others — which is most of the point of doing this work outside Python.

use std::sync::OnceLock;

use pyo3::create_exception;
use pyo3::exceptions::{PyException, PyValueError};
use pyo3::prelude::*;
use pyo3::types::{PyDict, PyList};

use crate::chunk::ChunkConfig;
use crate::denoise::{DenoiseConfig, DenoiseStats};
use crate::error::Error;
use crate::http::{FetchConfig, Impersonate, Page};
use crate::parse::{
    Article, ArticleKind, ExtractOptions, IndexMode, Link, Meta, RenderOptions, Unit,
};
use crate::pipeline::{Pipeline, Research};
use crate::rank::{Context, SlimConfig};
use crate::search::{Provider, SearchConfig, SearchResult};

create_exception!(rustai, RustaiError, PyException, "Base class for every rustai error.");
create_exception!(rustai, NetworkError, RustaiError, "The request failed at the transport level.");
create_exception!(
    rustai,
    HttpStatusError,
    RustaiError,
    "The server answered with a failure status."
);
create_exception!(rustai, RobotsError, RustaiError, "robots.txt disallows this URL.");
create_exception!(rustai, ExtractError, RustaiError, "The document could not be parsed.");
create_exception!(rustai, ProviderError, RustaiError, "A search provider failed.");
create_exception!(rustai, BrowserError, RustaiError, "The headless fallback was unavailable.");

impl From<Error> for PyErr {
    fn from(e: Error) -> PyErr {
        let msg = e.to_string();
        match e {
            Error::Network { .. } => NetworkError::new_err(msg),
            Error::Status { .. } => HttpStatusError::new_err(msg),
            Error::BodyTooLarge { .. } => NetworkError::new_err(msg),
            Error::RobotsDenied(_) => RobotsError::new_err(msg),
            Error::InvalidUrl(_) | Error::Config(_) => PyValueError::new_err(msg),
            Error::Parse(_) => ExtractError::new_err(msg),
            Error::Provider { .. } => ProviderError::new_err(msg),
            Error::Browser(_) => BrowserError::new_err(msg),
        }
    }
}

/// One multi-threaded tokio runtime for the process.
///
/// Building a runtime per call would cost more than most of the calls do, and
/// a shared one lets the connection pool actually be a pool.
fn runtime() -> PyResult<&'static tokio::runtime::Runtime> {
    static RUNTIME: OnceLock<std::io::Result<tokio::runtime::Runtime>> = OnceLock::new();
    RUNTIME
        .get_or_init(|| tokio::runtime::Builder::new_multi_thread().enable_all().build())
        .as_ref()
        .map_err(|e| RustaiError::new_err(format!("could not start the async runtime: {e}")))
}

/// Convert serialised data into plain Python containers.
fn json_to_py<'py>(py: Python<'py>, v: &serde_json::Value) -> PyResult<Bound<'py, PyAny>> {
    use serde_json::Value;
    Ok(match v {
        Value::Null => py.None().into_bound(py),
        Value::Bool(b) => b.into_pyobject(py)?.to_owned().into_any(),
        Value::Number(n) => match (n.as_i64(), n.as_f64()) {
            (Some(i), _) => i.into_pyobject(py)?.into_any(),
            (_, Some(f)) => f.into_pyobject(py)?.into_any(),
            _ => py.None().into_bound(py),
        },
        Value::String(s) => s.into_pyobject(py)?.into_any(),
        Value::Array(items) => {
            let list = PyList::empty(py);
            for item in items {
                list.append(json_to_py(py, item)?)?;
            }
            list.into_any()
        }
        Value::Object(map) => {
            let dict = PyDict::new(py);
            for (k, val) in map {
                dict.set_item(k, json_to_py(py, val)?)?;
            }
            dict.into_any()
        }
    })
}

fn to_dict<T: serde::Serialize>(py: Python<'_>, value: &T) -> PyResult<Py<PyAny>> {
    let json = serde_json::to_value(value)
        .map_err(|e| RustaiError::new_err(format!("could not serialise: {e}")))?;
    Ok(json_to_py(py, &json)?.unbind())
}

// ---------------------------------------------------------------- data types

/// Document metadata read from `<head>`.
#[pyclass(name = "Meta", frozen, module = "rustai", skip_from_py_object)]
#[derive(Clone)]
pub struct PyMeta {
    inner: Meta,
}

#[pymethods]
impl PyMeta {
    /// Best available title.
    #[getter]
    fn title(&self) -> Option<&str> {
        self.inner.title.as_deref()
    }
    /// Meta or Open Graph description.
    #[getter]
    fn description(&self) -> Option<&str> {
        self.inner.description.as_deref()
    }
    /// Declared author.
    #[getter]
    fn byline(&self) -> Option<&str> {
        self.inner.byline.as_deref()
    }
    /// Publication timestamp, verbatim from the page.
    #[getter]
    fn published(&self) -> Option<&str> {
        self.inner.published.as_deref()
    }
    /// BCP-47 language tag.
    #[getter]
    fn language(&self) -> Option<&str> {
        self.inner.language.as_deref()
    }
    /// Canonical URL.
    #[getter]
    fn canonical(&self) -> Option<&str> {
        self.inner.canonical.as_deref()
    }
    /// Site name.
    #[getter]
    fn site_name(&self) -> Option<&str> {
        self.inner.site_name.as_deref()
    }
    /// Everything above, as a dict.
    fn to_dict(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
        to_dict(py, &self.inner)
    }
    fn __repr__(&self) -> String {
        format!("Meta(title={:?}, language={:?})", self.inner.title, self.inner.language)
    }
}

/// One block of an extracted document.
#[pyclass(name = "Unit", frozen, module = "rustai", skip_from_py_object)]
#[derive(Clone)]
pub struct PyUnit {
    inner: Unit,
}

#[pymethods]
impl PyUnit {
    /// `"heading"`, `"paragraph"`, `"list_item"`, `"code"`, `"quote"` or `"table"`.
    #[getter]
    fn kind(&self) -> String {
        serde_json::to_value(self.inner.kind)
            .ok()
            .and_then(|v| v.as_str().map(str::to_string))
            .unwrap_or_default()
    }
    /// Heading level, or list nesting depth.
    #[getter]
    fn level(&self) -> u8 {
        self.inner.level
    }
    /// Plain text.
    #[getter]
    fn text(&self) -> &str {
        &self.inner.text
    }
    /// Rendered Markdown.
    #[getter]
    fn markdown(&self) -> &str {
        &self.inner.markdown
    }
    /// Enclosing headings, outermost first.
    #[getter]
    fn heading_path(&self) -> Vec<String> {
        self.inner.heading_path.clone()
    }
    /// Index in document order.
    #[getter]
    fn position(&self) -> usize {
        self.inner.position
    }
    /// Estimated tokens.
    #[getter]
    fn tokens(&self) -> usize {
        self.inner.tokens
    }
    /// Everything above, as a dict.
    fn to_dict(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
        to_dict(py, &self.inner)
    }
    fn __repr__(&self) -> String {
        let preview: String = self.inner.text.chars().take(40).collect();
        format!("Unit(kind={}, tokens={}, text={preview:?})", self.kind(), self.inner.tokens)
    }
}

/// What the denoiser removed.
#[pyclass(name = "DenoiseStats", frozen, module = "rustai", skip_from_py_object)]
#[derive(Clone)]
pub struct PyStats {
    inner: DenoiseStats,
}

#[pymethods]
impl PyStats {
    /// Nodes considered.
    #[getter]
    fn nodes_visited(&self) -> usize {
        self.inner.nodes_visited
    }
    /// Nodes rejected as boilerplate.
    #[getter]
    fn nodes_dropped(&self) -> usize {
        self.inner.nodes_dropped
    }
    /// Bytes of HTML in.
    #[getter]
    fn html_bytes(&self) -> usize {
        self.inner.html_bytes
    }
    /// Bytes of Markdown out.
    #[getter]
    fn markdown_bytes(&self) -> usize {
        self.inner.markdown_bytes
    }
    /// Size reduction in `[0, 1]`.
    #[getter]
    fn compression(&self) -> f32 {
        self.inner.compression()
    }
    /// Everything above, as a dict.
    fn to_dict(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
        to_dict(py, &self.inner)
    }
    fn __repr__(&self) -> String {
        format!(
            "DenoiseStats(html_bytes={}, markdown_bytes={}, compression={:.2})",
            self.inner.html_bytes,
            self.inner.markdown_bytes,
            self.inner.compression()
        )
    }
}

/// One link harvested from a listing page.
#[pyclass(name = "Link", frozen, module = "rustai", skip_from_py_object)]
#[derive(Clone)]
pub struct PyLink {
    inner: Link,
}

#[pymethods]
impl PyLink {
    /// Anchor text.
    #[getter]
    fn text(&self) -> &str {
        &self.inner.text
    }
    /// Absolute URL.
    #[getter]
    fn url(&self) -> &str {
        &self.inner.url
    }
    /// Nearby descriptive text, if the page offered any.
    #[getter]
    fn snippet(&self) -> &str {
        &self.inner.snippet
    }
    /// Enclosing section headings, outermost first.
    #[getter]
    fn heading_path(&self) -> Vec<String> {
        self.inner.heading_path.clone()
    }
    /// Everything above, as a dict.
    fn to_dict(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
        to_dict(py, &self.inner)
    }
    fn __repr__(&self) -> String {
        format!("Link(text={:?}, url={:?})", self.inner.text, self.inner.url)
    }
}

/// A cleaned document.
#[pyclass(name = "Article", frozen, module = "rustai", from_py_object)]
#[derive(Clone)]
pub struct PyArticle {
    pub(crate) inner: Article,
}

#[pymethods]
impl PyArticle {
    /// Group the units into pieces an embedding model will accept.
    ///
    /// A `Unit` is one block — a paragraph, a list item, a heading. That is
    /// the grain ranking wants and the wrong one for a vector store: on MDN's
    /// `Promise` reference the median unit is 37 tokens and a third are under
    /// 30, so embedding units directly gives you 125 vectors that each know
    /// almost nothing. This walks them in order and groups them up to
    /// `target_tokens`, starting a new chunk at each heading so a chunk opens
    /// with the thing that says what it is about.
    ///
    /// `overlap_tokens` repeats whole units from the previous chunk's tail, so
    /// an answer that straddles a boundary is retrievable from either side. A
    /// unit longer than `target_tokens` is emitted whole rather than cut
    /// mid-sentence, and an article that would otherwise produce nothing gets
    /// one chunk anyway — a short page is still a source.
    ///
    /// Returns dicts, ready to hand to a vector store:
    ///
    /// ```text
    /// for c in article.chunks():
    ///     store.add(id=f"{c['url']}#{c['index']}", text=c["text"],
    ///               metadata={"title": c["title"], "url": c["url"]})
    /// ```
    #[pyo3(signature = (*, target_tokens = 512, overlap_tokens = 64, min_tokens = 24))]
    fn chunks(
        &self,
        py: Python<'_>,
        target_tokens: usize,
        overlap_tokens: usize,
        min_tokens: usize,
    ) -> PyResult<Py<PyAny>> {
        if target_tokens == 0 {
            return Err(PyValueError::new_err("target_tokens must be greater than 0"));
        }
        if overlap_tokens >= target_tokens {
            return Err(PyValueError::new_err(
                "overlap_tokens must be smaller than target_tokens, or every \
                 chunk repeats the last one and chunking never advances",
            ));
        }
        let cfg = ChunkConfig { target_tokens, overlap_tokens, min_tokens };
        let out = py.detach(|| crate::chunk::chunk(&self.inner, &cfg));
        to_dict(py, &out)
    }

    /// Source URL.
    #[getter]
    fn url(&self) -> Option<&str> {
        self.inner.url.as_deref()
    }
    /// Title, falling back to the first heading.
    #[getter]
    fn title(&self) -> Option<&str> {
        self.inner.title()
    }
    /// The whole cleaned document as Markdown.
    #[getter]
    fn markdown(&self) -> &str {
        &self.inner.markdown
    }
    /// The whole cleaned document as plain text.
    #[getter]
    fn text(&self) -> &str {
        &self.inner.text
    }
    /// `"article"` for prose, `"index"` for a listing page.
    #[getter]
    fn kind(&self) -> &'static str {
        match self.inner.kind {
            ArticleKind::Article => "article",
            ArticleKind::Index => "index",
        }
    }
    /// Links harvested from a listing page.
    #[getter]
    fn links(&self) -> Vec<PyLink> {
        self.inner.links.iter().cloned().map(|inner| PyLink { inner }).collect()
    }
    /// Metadata from `<head>`.
    #[getter]
    fn meta(&self) -> PyMeta {
        PyMeta { inner: self.inner.meta.clone() }
    }
    /// Rankable blocks.
    #[getter]
    fn units(&self) -> Vec<PyUnit> {
        self.inner.units.iter().cloned().map(|inner| PyUnit { inner }).collect()
    }
    /// Denoiser statistics.
    #[getter]
    fn stats(&self) -> PyStats {
        PyStats { inner: self.inner.stats.clone() }
    }
    /// Estimated tokens for the whole article.
    #[getter]
    fn tokens(&self) -> usize {
        self.inner.tokens()
    }
    /// The article as nested dicts.
    fn to_dict(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
        to_dict(py, &self.inner)
    }
    fn __len__(&self) -> usize {
        self.inner.units.len()
    }
    fn __repr__(&self) -> String {
        format!(
            "Article(kind={}, title={:?}, units={}, tokens={})",
            self.kind(),
            self.inner.title(),
            self.inner.units.len(),
            self.inner.tokens()
        )
    }
}

/// A raw HTTP response.
#[pyclass(name = "Page", frozen, module = "rustai", skip_from_py_object)]
#[derive(Clone)]
pub struct PyPage {
    inner: Page,
}

#[pymethods]
impl PyPage {
    /// URL as requested.
    #[getter]
    fn url(&self) -> &str {
        &self.inner.url
    }
    /// URL after redirects.
    #[getter]
    fn final_url(&self) -> &str {
        &self.inner.final_url
    }
    /// HTTP status code.
    #[getter]
    fn status(&self) -> u16 {
        self.inner.status
    }
    /// `Content-Type` header.
    #[getter]
    fn content_type(&self) -> Option<&str> {
        self.inner.content_type.as_deref()
    }
    /// Decoded response body.
    #[getter]
    fn body(&self) -> &str {
        &self.inner.body
    }
    /// Wall time in milliseconds.
    #[getter]
    fn elapsed_ms(&self) -> u64 {
        self.inner.elapsed_ms
    }
    /// Whether headless Chrome produced this body.
    #[getter]
    fn rendered(&self) -> bool {
        self.inner.rendered
    }
    /// Extract this page without fetching it again.
    fn extract(&self) -> PyResult<PyArticle> {
        let inner = crate::parse::extract(&self.inner.body, Some(&self.inner.final_url))?;
        Ok(PyArticle { inner })
    }
    /// Everything above, as a dict.
    fn to_dict(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
        to_dict(py, &self.inner)
    }
    fn __repr__(&self) -> String {
        format!(
            "Page(url={:?}, status={}, bytes={}, elapsed_ms={})",
            self.inner.url,
            self.inner.status,
            self.inner.body.len(),
            self.inner.elapsed_ms
        )
    }
}

/// One search hit.
#[pyclass(name = "SearchResult", frozen, module = "rustai", skip_from_py_object)]
#[derive(Clone)]
pub struct PySearchResult {
    inner: SearchResult,
}

#[pymethods]
impl PySearchResult {
    /// Result title.
    #[getter]
    fn title(&self) -> &str {
        &self.inner.title
    }
    /// Absolute URL.
    #[getter]
    fn url(&self) -> &str {
        &self.inner.url
    }
    /// Provider snippet.
    #[getter]
    fn snippet(&self) -> &str {
        &self.inner.snippet
    }
    /// Providers that returned this URL.
    #[getter]
    fn providers(&self) -> Vec<String> {
        self.inner.providers.clone()
    }
    /// Fused rank-fusion score.
    #[getter]
    fn score(&self) -> f32 {
        self.inner.score
    }
    /// Best position this URL reached at any *single* provider, zero-based.
    ///
    /// Not this result's position in the fused list — for that, enumerate the
    /// list you were handed. A result ranked first by two providers and a
    /// result ranked first by one both report `0`; what separates them is
    /// `score`, which is what the list is sorted by.
    #[getter]
    fn rank(&self) -> usize {
        self.inner.rank
    }
    /// Everything above, as a dict.
    fn to_dict(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
        to_dict(py, &self.inner)
    }
    fn __repr__(&self) -> String {
        format!(
            "SearchResult(title={:?}, url={:?}, providers={:?})",
            self.inner.title, self.inner.url, self.inner.providers
        )
    }
}

/// A compressed context window.
#[pyclass(name = "Context", frozen, module = "rustai", skip_from_py_object)]
#[derive(Clone)]
pub struct PyContext {
    inner: Context,
}

#[pymethods]
impl PyContext {
    /// The query it was built for.
    #[getter]
    fn query(&self) -> &str {
        &self.inner.query
    }
    /// Ready-to-prompt Markdown.
    #[getter]
    fn markdown(&self) -> &str {
        &self.inner.markdown
    }
    /// Estimated tokens.
    #[getter]
    fn tokens(&self) -> usize {
        self.inner.tokens
    }
    /// Sources that contributed, as dicts.
    #[getter]
    fn sources(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
        to_dict(py, &self.inner.sources)
    }
    /// Why each unit was chosen, as dicts.
    ///
    /// Keys: `source` and `unit`, which are indices rather than text --
    /// `articles[source].units[unit]` is the block itself -- plus `tokens`
    /// and the three scores behind the decision: `relevance` (BM25 against
    /// the query), `density` (nouns and numbers over filler) and the combined
    /// `score`. Enough to answer "why is this in my context window and that
    /// paragraph is not".
    ///
    /// These scores rank units *within one query* and are not comparable
    /// across queries: BM25 scales with how rare the query's terms are, so a
    /// common-word question produces small numbers for good matches and a
    /// rare-word question large ones for mediocre matches. Measured on two
    /// live queries, an off-topic encyclopedia article scored 0.22 on one
    /// while every correct source on the other scored below 0.10 -- so a fixed
    /// cutoff drops the good set and keeps the bad one. Sort by them, show
    /// them, but do not threshold on them.
    #[getter]
    fn selected(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
        to_dict(py, &self.inner.selected)
    }
    /// Units available before selection.
    #[getter]
    fn units_considered(&self) -> usize {
        self.inner.units_considered
    }
    /// Everything above, as a dict.
    fn to_dict(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
        to_dict(py, &self.inner)
    }
    fn __str__(&self) -> &str {
        &self.inner.markdown
    }
    fn __repr__(&self) -> String {
        format!(
            "Context(tokens={}, sources={}, selected={}/{})",
            self.inner.tokens,
            self.inner.sources.len(),
            self.inner.selected.len(),
            self.inner.units_considered
        )
    }
}

/// The result of a full research run.
#[pyclass(name = "Research", frozen, module = "rustai", skip_from_py_object)]
#[derive(Clone)]
pub struct PyResearch {
    inner: Research,
}

#[pymethods]
impl PyResearch {
    /// The query as asked.
    #[getter]
    fn query(&self) -> &str {
        &self.inner.query
    }
    /// The compressed context.
    #[getter]
    fn context(&self) -> PyContext {
        PyContext { inner: self.inner.context.clone() }
    }
    /// Ready-to-prompt Markdown, straight from the context.
    #[getter]
    fn markdown(&self) -> &str {
        &self.inner.context.markdown
    }
    /// Search hits, best first.
    #[getter]
    fn results(&self) -> Vec<PySearchResult> {
        self.inner.results.iter().cloned().map(|inner| PySearchResult { inner }).collect()
    }
    /// Articles that were successfully read.
    #[getter]
    fn articles(&self) -> Vec<PyArticle> {
        self.inner.articles.iter().cloned().map(|inner| PyArticle { inner }).collect()
    }
    /// `(stage, message)` pairs for non-fatal failures.
    #[getter]
    fn failures(&self) -> Vec<(String, String)> {
        self.inner.failures.clone()
    }
    /// Everything above, as a dict.
    fn to_dict(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
        to_dict(py, &self.inner)
    }
    fn __str__(&self) -> &str {
        &self.inner.context.markdown
    }
    fn __repr__(&self) -> String {
        format!(
            "Research(query={:?}, articles={}, tokens={}, failures={})",
            self.inner.query,
            self.inner.articles.len(),
            self.inner.context.tokens,
            self.inner.failures.len()
        )
    }
}

// -------------------------------------------------------------------- client

/// A reusable pipeline: connection pool, providers, extractor and slimmer.
///
/// Build one and keep it: the connection pool, the robots cache and the
/// per-host delays all live on the client, so a second call to a host you
/// have already visited is cheaper.
///
/// `providers` accepts `"duckduckgo"`, `"wikipedia"` or `"wikipedia:ko"`,
/// `"searxng:https://…"`, `"rss:https://…"` and `"sitemap:https://…"`.
///
/// Two separate caps decide how much work a question costs, and they are
/// easy to mistake for each other:
///
/// * `max_results` (this constructor) is search breadth -- how many fused
///   hits `search` returns. Fetching nothing, it is cheap to raise.
/// * `max_sources` (`research`) is read depth -- how many of those hits are
///   actually fetched and extracted. This is what costs time.
///
/// So `Client(max_results=20).research(q, max_sources=5)` casts a wide net
/// and reads the best five of it. `max_results` was called `limit` in 0.2.0
/// and that name still works.
///
/// `respect_crawl_delay` is why a fetch sometimes stalls for a long time with
/// nothing on the network. A site may publish a `Crawl-delay` in its
/// `robots.txt` and this client honours it: arXiv asks for fifteen seconds
/// between requests, so a second arXiv URL through the same client waits that
/// long. A *new* client has not visited anything yet and so does not wait,
/// which is worth knowing before concluding that reusing a client is slow.
/// Setting this to `False` ignores a published request; do that for a host you
/// own. `per_host_delay` does not override it — the larger of the two wins.
///
/// `max_tokens_per_source` caps how much any one page may contribute to the
/// context. Leaving it `None` is right for most questions: measured over six
/// queries at budgets of 1,000, 2,048 and 4,096 tokens, capping either
/// changed nothing or bought source coverage by admitting less relevant text,
/// and coverage rises on its own as the budget grows. Reach for it when a
/// question needs corroboration rather than depth -- two of those six queries
/// had a single long page take 86% and 90% of the window, in one case
/// starving the encyclopedia article on the exact term asked about.
#[pyclass(name = "Client", frozen, module = "rustai")]
pub struct PyClient {
    pipeline: Pipeline,
    summary: String,
}

#[pymethods]
impl PyClient {
    /// Build a client. PyO3 drops this comment; see the class docstring.
    #[new]
    #[pyo3(signature = (
        *,
        providers = None,
        concurrency = 16,
        timeout = 20.0,
        impersonate = "chrome",
        respect_robots = true,
        respect_crawl_delay = true,
        per_host_delay = 0.25,
        retries = 2,
        max_body_bytes = 8 * 1024 * 1024,
        accept_language = "en-US,en;q=0.9",
        browser_fallback = false,
        contact_email = None,
        proxies = None,
        max_retry_after = 60.0,
        cookie_file = None,
        max_tokens = 2048,
        max_tokens_per_source = None,
        diversity = 0.35,
        include_links = true,
        include_images = false,
        include_tables = true,
        index_mode = "auto",
        max_results = None,
        limit = None,
    ))]
    #[allow(clippy::too_many_arguments)]
    fn new(
        providers: Option<Vec<String>>,
        concurrency: usize,
        timeout: f64,
        impersonate: &str,
        respect_robots: bool,
        respect_crawl_delay: bool,
        per_host_delay: f64,
        retries: u32,
        max_body_bytes: usize,
        accept_language: &str,
        browser_fallback: bool,
        contact_email: Option<String>,
        proxies: Option<Vec<String>>,
        max_retry_after: f64,
        cookie_file: Option<String>,
        max_tokens: usize,
        max_tokens_per_source: Option<usize>,
        diversity: f32,
        include_links: bool,
        include_images: bool,
        include_tables: bool,
        index_mode: &str,
        max_results: Option<usize>,
        limit: Option<usize>,
    ) -> PyResult<Self> {
        if !timeout.is_finite() || timeout <= 0.0 {
            return Err(PyValueError::new_err("timeout must be a positive number of seconds"));
        }
        if !(0.0..=1.0).contains(&diversity) {
            return Err(PyValueError::new_err("diversity must be between 0.0 and 1.0"));
        }

        // `limit` was this parameter's name in 0.2.0 and stays accepted. It is
        // a bad name: it does not say what it limits, and the neighbouring
        // `max_sources` limits something else -- this caps how many hits
        // `search` returns, `max_sources` caps how many of them `research`
        // then fetches. Naming it after what it caps keeps the two apart.
        let max_results = match (max_results, limit) {
            (Some(a), Some(b)) if a != b => {
                return Err(PyValueError::new_err(format!(
                    "max_results={a} and limit={b} disagree; limit is the old name \
                     for max_results, so pass only max_results"
                )));
            }
            (Some(n), _) | (None, Some(n)) => n,
            (None, None) => 10,
        };

        let providers = match providers {
            Some(specs) => {
                specs.iter().map(|s| Provider::parse(s)).collect::<Result<Vec<_>, _>>()?
            }
            None => SearchConfig::default().providers,
        };
        if providers.is_empty() {
            return Err(PyValueError::new_err("at least one provider is required"));
        }

        let fetch = FetchConfig {
            concurrency,
            timeout: std::time::Duration::from_secs_f64(timeout),
            max_body_bytes,
            retries,
            per_host_delay: std::time::Duration::from_secs_f64(per_host_delay.max(0.0)),
            respect_robots,
            respect_crawl_delay,
            impersonate: Impersonate::parse(impersonate)?,
            accept_language: accept_language.to_string(),
            browser_fallback,
            proxies: proxies.unwrap_or_default(),
            max_retry_after: std::time::Duration::from_secs_f64(max_retry_after.max(0.0)),
            cookie_file: cookie_file.map(std::path::PathBuf::from),
            ..Default::default()
        };
        let summary = format!(
            "Client(providers={:?}, concurrency={concurrency}, impersonate={impersonate:?}, \
             respect_robots={respect_robots}, proxies={}, max_tokens={max_tokens})",
            providers.iter().map(Provider::name).collect::<Vec<_>>(),
            fetch.proxies.len()
        );

        let pipeline = Pipeline::builder()
            .fetch(fetch)
            .search(SearchConfig {
                providers,
                limit: max_results,
                per_provider: max_results.max(10),
                contact_email,
            })
            .extract(ExtractOptions {
                render: RenderOptions { include_links, include_images, include_tables },
                denoise: DenoiseConfig { keep_tables: include_tables, ..Default::default() },
                index_mode: parse_index_mode(index_mode)?,
                ..ExtractOptions::new()
            })
            .slim(SlimConfig { max_tokens, max_tokens_per_source, diversity, ..Default::default() })
            .build()?;

        Ok(PyClient { pipeline, summary })
    }

    /// Search every configured provider and return fused results.
    ///
    /// Provider failures are not raised: a partial result set is more useful
    /// than an exception when one of five providers is having a bad day. Pass
    /// `strict=True` to raise when *every* provider failed.
    #[pyo3(signature = (query, *, strict = false))]
    fn search(&self, py: Python<'_>, query: &str, strict: bool) -> PyResult<Vec<PySearchResult>> {
        let outcome = py.detach(|| runtime().map(|rt| rt.block_on(self.pipeline.search(query))))?;
        if strict && outcome.results.is_empty() && !outcome.failures.is_empty() {
            let detail = outcome
                .failures
                .iter()
                .map(|(p, m)| format!("{p}: {m}"))
                .collect::<Vec<_>>()
                .join("; ");
            return Err(ProviderError::new_err(format!("every provider failed ({detail})")));
        }
        Ok(outcome.results.into_iter().map(|inner| PySearchResult { inner }).collect())
    }

    /// Fetch URLs concurrently.
    ///
    /// **The result is not 1:1 with the input.** With `raise_on_error=False`
    /// (the default) a failed URL is simply absent, so one dead link cannot
    /// lose you the other nineteen — but neither can you tell which one went,
    /// and indexing the result against the input you passed will be wrong.
    /// Match on `Page.url` instead, or pass `raise_on_error=True` when a
    /// missing page is a problem rather than a nuisance.
    ///
    /// This differs deliberately from `extract_many`, which is 1:1 and raises:
    /// there, an input is a document you already hold, and losing one silently
    /// would be a bug in your own pipeline. Here an input is somebody else's
    /// server, and it is allowed to be down.
    #[pyo3(signature = (urls, *, raise_on_error = false))]
    fn fetch(
        &self,
        py: Python<'_>,
        urls: Vec<String>,
        raise_on_error: bool,
    ) -> PyResult<Vec<PyPage>> {
        let results = py.detach(|| runtime().map(|rt| rt.block_on(self.pipeline.fetch(&urls))))?;
        collect(results, raise_on_error)
            .map(|pages| pages.into_iter().map(|inner| PyPage { inner }).collect())
    }

    /// Fetch and extract in one step.
    ///
    /// **The result is not 1:1 with the input** — see `fetch`. Match on
    /// `Article.url` rather than by position, or pass `raise_on_error=True`.
    #[pyo3(signature = (urls, *, raise_on_error = false))]
    fn read(
        &self,
        py: Python<'_>,
        urls: Vec<String>,
        raise_on_error: bool,
    ) -> PyResult<Vec<PyArticle>> {
        let results = py.detach(|| runtime().map(|rt| rt.block_on(self.pipeline.read(&urls))))?;
        collect(results, raise_on_error)
            .map(|arts| arts.into_iter().map(|inner| PyArticle { inner }).collect())
    }

    /// Search, read the top results, and compress them into a context window.
    #[pyo3(signature = (query, *, max_sources = 5))]
    fn research(&self, py: Python<'_>, query: &str, max_sources: usize) -> PyResult<PyResearch> {
        let inner = py.detach(|| {
            runtime().map(|rt| rt.block_on(self.pipeline.research(query, max_sources)))
        })?;
        Ok(PyResearch { inner })
    }

    /// Write the cookie jar to the `cookie_file` this client was built with.
    ///
    /// Returns how many cookies were saved, or 0 when no file was configured.
    /// Clearance cookies are the expensive part of getting through a bot wall;
    /// saving them means not paying for them again next run.
    fn save_cookies(&self) -> PyResult<usize> {
        Ok(self.pipeline.fetcher().save_cookies()?)
    }

    fn __repr__(&self) -> String {
        self.summary.clone()
    }
}

fn collect<T>(results: Vec<crate::error::Result<T>>, raise: bool) -> PyResult<Vec<T>> {
    let mut out = Vec::with_capacity(results.len());
    for r in results {
        match r {
            Ok(v) => out.push(v),
            Err(e) if raise => return Err(e.into()),
            Err(_) => {}
        }
    }
    Ok(out)
}

// ----------------------------------------------------------- free functions

fn parse_index_mode(mode: &str) -> PyResult<IndexMode> {
    match mode.trim().to_ascii_lowercase().as_str() {
        "auto" => Ok(IndexMode::Auto),
        "never" | "off" => Ok(IndexMode::Never),
        "always" | "on" => Ok(IndexMode::Always),
        other => Err(PyValueError::new_err(format!(
            "index_mode must be `auto`, `never` or `always`, not {other:?}"
        ))),
    }
}

/// Catch the most likely first mistake: handing `extract` a URL.
///
/// The library fetches, so `extract("https://…")` is a natural thing to try,
/// and HTML that happens to be a bare URL is not a thing that exists. Left
/// alone it returns an empty `Article` and the caller has nothing to go on.
fn reject_url_as_html(html: &str) -> PyResult<()> {
    let trimmed = html.trim();
    let looks_like_url = trimmed.len() < 2048
        && !trimmed.contains('<')
        && !trimmed.contains(char::is_whitespace)
        && (trimmed.starts_with("http://") || trimmed.starts_with("https://"));
    if looks_like_url {
        return Err(PyValueError::new_err(format!(
            "expected HTML, got what looks like a URL ({trimmed:?}).\n\
             `extract` takes markup you already have and does not fetch. To \
             read a URL:\n    rustai.Client().read([{trimmed:?}])[0]\n\
             or, for a whole question:\n    rustai.research(\"your question\")"
        )));
    }
    Ok(())
}

/// Denoise a raw HTML string into Markdown. No network access.
#[pyfunction]
#[pyo3(signature = (html, url = None, *, include_links = true, include_images = false, include_tables = true, index_mode = "auto"))]
fn extract(
    py: Python<'_>,
    html: &str,
    url: Option<&str>,
    include_links: bool,
    include_images: bool,
    include_tables: bool,
    index_mode: &str,
) -> PyResult<PyArticle> {
    reject_url_as_html(html)?;
    let opts = ExtractOptions {
        render: RenderOptions { include_links, include_images, include_tables },
        denoise: DenoiseConfig { keep_tables: include_tables, ..Default::default() },
        index_mode: parse_index_mode(index_mode)?,
        ..ExtractOptions::new()
    };
    // Extraction on a large document is long enough to be worth releasing the
    // GIL for, and it touches nothing Python owns.
    let inner = py.detach(|| crate::parse::extract_with(html, url, &opts))?;
    Ok(PyArticle { inner })
}

/// Chunk many articles at once, in parallel across the rayon pool.
///
/// The batch form of `Article.chunks`. Chunking is cheap per article but a
/// crawl produces thousands, and the GIL is released for the whole call, so a
/// list costs roughly one article's wall time on a multi-core machine.
///
/// Returns one flat list: chunks carry their own `url`, so which article a
/// chunk came from survives the flattening, which is the shape a vector store
/// wants anyway.
#[pyfunction]
#[pyo3(signature = (articles, *, target_tokens = 512, overlap_tokens = 64, min_tokens = 24))]
fn chunk_many(
    py: Python<'_>,
    articles: Vec<PyRef<'_, PyArticle>>,
    target_tokens: usize,
    overlap_tokens: usize,
    min_tokens: usize,
) -> PyResult<Py<PyAny>> {
    if target_tokens == 0 {
        return Err(PyValueError::new_err("target_tokens must be greater than 0"));
    }
    if overlap_tokens >= target_tokens {
        return Err(PyValueError::new_err("overlap_tokens must be smaller than target_tokens"));
    }
    let cfg = ChunkConfig { target_tokens, overlap_tokens, min_tokens };
    let owned: Vec<Article> = articles.iter().map(|a| a.inner.clone()).collect();
    let out = py.detach(|| {
        use rayon::prelude::*;
        owned.par_iter().flat_map(|a| crate::chunk::chunk(a, &cfg)).collect::<Vec<_>>()
    });
    to_dict(py, &out)
}

/// Denoise many HTML strings at once, in parallel across the rayon pool.
///
/// This is the batch form of [`extract`]. Parsing is CPU-bound and per-document
/// independent, so a list of 20 documents costs roughly one document's wall
/// time on a multi-core machine — and because the GIL is released for the whole
/// call, it parallelises whether or not the caller uses threads.
///
/// `urls` is optional; when given it must be the same length as `documents`.
/// Output is 1:1 with the input, so a failed document raises rather than
/// silently shifting every later index.
#[pyfunction]
#[pyo3(signature = (documents, urls = None, *, include_links = true, include_images = false, include_tables = true, index_mode = "auto"))]
fn extract_many(
    py: Python<'_>,
    documents: Vec<String>,
    urls: Option<Vec<Option<String>>>,
    include_links: bool,
    include_images: bool,
    include_tables: bool,
    index_mode: &str,
) -> PyResult<Vec<PyArticle>> {
    for doc in &documents {
        reject_url_as_html(doc)?;
    }
    if let Some(urls) = &urls
        && urls.len() != documents.len()
    {
        return Err(PyValueError::new_err(format!(
            "urls has {} entries but documents has {}",
            urls.len(),
            documents.len()
        )));
    }
    let opts = ExtractOptions {
        render: RenderOptions { include_links, include_images, include_tables },
        denoise: DenoiseConfig { keep_tables: include_tables, ..Default::default() },
        index_mode: parse_index_mode(index_mode)?,
        ..ExtractOptions::new()
    };

    let results = py.detach(|| {
        let pairs: Vec<(&str, Option<&str>)> = documents
            .iter()
            .enumerate()
            .map(|(i, html)| {
                let url = urls.as_ref().and_then(|u| u[i].as_deref());
                (html.as_str(), url)
            })
            .collect();
        crate::parse::extract_many(pairs, &opts)
    });

    results.into_iter().map(|r| r.map(|inner| PyArticle { inner }).map_err(PyErr::from)).collect()
}

/// Rank and compress already-extracted articles into a context window.
///
/// Pass `query_vector` and `unit_vectors` to blend an embedding model's
/// judgement into the ranking. BM25 cannot see that "딥러닝" and "deep
/// learning" name the same subject, or that a paragraph explains a term
/// without using it; a model you already run can, and the arithmetic then
/// happens across every core with the GIL released:
///
/// ```text
/// units = [u.text for a in articles for u in a.units]
/// ctx = rustai.slim(
///     query, articles,
///     query_vector=model.encode(query).tolist(),
///     unit_vectors=model.encode(units).tolist(),
///     semantic_weight=0.5,          # 0 is pure BM25, 1 is pure vector
/// )
/// ```
///
/// One vector per unit, flattened in that exact order — short units are
/// dropped before scoring, so the alignment is against every unit rather than
/// the surviving ones, and a wrong-sized list is refused rather than quietly
/// mis-ranked. Vectors need not be normalised.
///
/// Diversity still uses word overlap rather than vector distance. The
/// duplicate threshold is calibrated against overlap, and two paragraphs of
/// one article routinely exceed 0.8 cosine under a sentence transformer, so
/// swapping the measure without recalibrating would start discarding the
/// second half of every source.
#[pyfunction]
#[pyo3(signature = (query, articles, *, max_tokens = 2048, diversity = 0.35,
    max_tokens_per_source = None, include_breadcrumbs = true,
    query_vector = None, unit_vectors = None, semantic_weight = 0.5))]
#[allow(clippy::too_many_arguments)]
fn slim(
    py: Python<'_>,
    query: &str,
    articles: Vec<PyRef<'_, PyArticle>>,
    max_tokens: usize,
    diversity: f32,
    max_tokens_per_source: Option<usize>,
    include_breadcrumbs: bool,
    query_vector: Option<Vec<f32>>,
    unit_vectors: Option<Vec<Vec<f32>>>,
    semantic_weight: f32,
) -> PyResult<PyContext> {
    if !(0.0..=1.0).contains(&diversity) {
        return Err(PyValueError::new_err("diversity must be between 0.0 and 1.0"));
    }
    if !(0.0..=1.0).contains(&semantic_weight) {
        return Err(PyValueError::new_err("semantic_weight must be between 0.0 and 1.0"));
    }
    let owned: Vec<Article> = articles.into_iter().map(|a| a.inner.clone()).collect();

    // Both or neither: one without the other is a silent no-op, and the caller
    // would see ranking that quietly ignored the model they just ran.
    let vectors = match (&query_vector, &unit_vectors) {
        (Some(_), None) | (None, Some(_)) => {
            return Err(PyValueError::new_err(
                "query_vector and unit_vectors go together; pass both or neither",
            ));
        }
        (None, None) => None,
        (Some(q), Some(units)) => {
            let expected: usize = owned.iter().map(|a| a.units.len()).sum();
            if units.len() != expected {
                return Err(PyValueError::new_err(format!(
                    "unit_vectors has {} entries but the articles hold {expected} units. \
                     One vector per unit, flattened in order: \
                     [u.text for a in articles for u in a.units]",
                    units.len()
                )));
            }
            if let Some((i, bad)) = units.iter().enumerate().find(|(_, u)| u.len() != q.len()) {
                return Err(PyValueError::new_err(format!(
                    "unit_vectors[{i}] has {} dimensions and query_vector has {}. \
                     Embed the query with the same model as the units",
                    bad.len(),
                    q.len()
                )));
            }
            Some((q.as_slice(), units.as_slice()))
        }
    };

    let cfg = SlimConfig {
        max_tokens,
        diversity,
        max_tokens_per_source,
        include_breadcrumbs,
        semantic_weight,
        ..Default::default()
    };
    let inner = py.detach(|| match vectors {
        Some((q, units)) => crate::rank::slim_with_vectors(
            query,
            &owned,
            &cfg,
            Some(crate::rank::Vectors { query: q, units }),
        ),
        None => crate::rank::slim(query, &owned, &cfg),
    });
    Ok(PyContext { inner })
}

/// Search, read and compress in one call, using a throwaway client.
///
/// `max_tokens_per_source` caps how much any one page may contribute; see
/// `Client` for when that is worth doing.
#[pyfunction]
#[pyo3(signature = (query, *, max_sources = 5, max_tokens = 2048, max_tokens_per_source = None,
    providers = None, impersonate = "chrome", respect_robots = true, contact_email = None))]
#[allow(clippy::too_many_arguments)]
fn research(
    py: Python<'_>,
    query: &str,
    max_sources: usize,
    max_tokens: usize,
    max_tokens_per_source: Option<usize>,
    providers: Option<Vec<String>>,
    impersonate: &str,
    respect_robots: bool,
    contact_email: Option<String>,
) -> PyResult<PyResearch> {
    let client = PyClient::new(
        providers,
        16,
        20.0,
        impersonate,
        respect_robots,
        true,
        0.25,
        2,
        8 * 1024 * 1024,
        "en-US,en;q=0.9",
        false,
        contact_email,
        None,
        60.0,
        None,
        max_tokens,
        max_tokens_per_source,
        0.35,
        true,
        false,
        true,
        "auto",
        None,
        None,
    )?;
    client.research(py, query, max_sources)
}

/// Estimate how many LLM tokens a string costs.
#[pyfunction]
fn count_tokens(text: &str) -> usize {
    crate::text::estimate_tokens(text)
}

/// Split text into the tokens the ranker uses.
#[pyfunction]
fn tokenize(text: &str) -> Vec<String> {
    crate::text::tokenize(text)
}

/// Score a block of text for information density, `0.0`–`1.0`.
#[pyfunction]
fn density(text: &str) -> f32 {
    crate::rank::density(text).score
}

/// Normalise a URL to the identity used for deduplication.
#[pyfunction]
fn canonical_url(url: &str) -> Option<String> {
    crate::search::canonical_key(url)
}

/// Parse an RSS or Atom feed into a list of dicts.
#[pyfunction]
fn parse_feed(py: Python<'_>, xml: &str) -> PyResult<Py<PyAny>> {
    to_dict(py, &crate::search::parse_rss(xml)?)
}

/// Parse a sitemap into `{"urls": [...], "sitemaps": [...]}`.
#[pyfunction]
fn parse_sitemap(py: Python<'_>, xml: &str) -> PyResult<Py<PyAny>> {
    to_dict(py, &crate::search::parse_sitemap(xml)?)
}

/// The compiled extension module.
#[pymodule]
#[pyo3(name = "_rustai")]
pub fn rustai_module(m: &Bound<'_, PyModule>) -> PyResult<()> {
    m.add("__version__", env!("CARGO_PKG_VERSION"))?;

    m.add_class::<PyClient>()?;
    m.add_class::<PyArticle>()?;
    m.add_class::<PyPage>()?;
    m.add_class::<PyUnit>()?;
    m.add_class::<PyLink>()?;
    m.add_class::<PyMeta>()?;
    m.add_class::<PyStats>()?;
    m.add_class::<PySearchResult>()?;
    m.add_class::<PyContext>()?;
    m.add_class::<PyResearch>()?;

    m.add_function(wrap_pyfunction!(extract, m)?)?;
    m.add_function(wrap_pyfunction!(extract_many, m)?)?;
    m.add_function(wrap_pyfunction!(chunk_many, m)?)?;
    m.add_function(wrap_pyfunction!(slim, m)?)?;
    m.add_function(wrap_pyfunction!(research, m)?)?;
    m.add_function(wrap_pyfunction!(count_tokens, m)?)?;
    m.add_function(wrap_pyfunction!(tokenize, m)?)?;
    m.add_function(wrap_pyfunction!(density, m)?)?;
    m.add_function(wrap_pyfunction!(canonical_url, m)?)?;
    m.add_function(wrap_pyfunction!(parse_feed, m)?)?;
    m.add_function(wrap_pyfunction!(parse_sitemap, m)?)?;

    m.add("RustaiError", m.py().get_type::<RustaiError>())?;
    m.add("NetworkError", m.py().get_type::<NetworkError>())?;
    m.add("HttpStatusError", m.py().get_type::<HttpStatusError>())?;
    m.add("RobotsError", m.py().get_type::<RobotsError>())?;
    m.add("ExtractError", m.py().get_type::<ExtractError>())?;
    m.add("ProviderError", m.py().get_type::<ProviderError>())?;
    m.add("BrowserError", m.py().get_type::<BrowserError>())?;

    Ok(())
}

#[cfg(test)]
mod guard_tests {
    use super::reject_url_as_html;

    #[test]
    fn rejects_a_bare_url() {
        assert!(reject_url_as_html("https://example.com/x").is_err());
        assert!(reject_url_as_html("  http://example.com  ").is_err());
    }

    /// Everything that is plausibly markup, or prose, has to pass -- including
    /// a document that merely mentions a URL, and one with no tags at all.
    #[test]
    fn passes_anything_that_could_be_a_document() {
        assert!(reject_url_as_html("<p>hi</p>").is_ok());
        assert!(reject_url_as_html("").is_ok());
        assert!(reject_url_as_html("just some prose").is_ok());
        assert!(reject_url_as_html("see https://example.com for more").is_ok());
        assert!(reject_url_as_html("<a href=\"https://example.com\">x</a>").is_ok());
        assert!(reject_url_as_html("ftp://example.com/file").is_ok());
    }
}