dataprof-json 0.14.0

JSON and JSONL scanning support for dataprof
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
//! JSON and JSONL scanning and profiling for `dataprof`.
//!
//! This crate is an implementation detail of the `dataprof` facade, which
//! re-exports [`JsonParserConfig`], [`analyze_json_from_reader`], and
//! [`analyze_json_file`]. Depend on `dataprof` unless you need JSON support
//! without the rest of the workspace.
//!
//! Two entry shapes are offered. [`scan_json_from_reader`] hands each record to
//! a callback and reports what it read; [`analyze_json_from_reader`] and
//! [`analyze_json_file`] build column profiles and a full report on top of it.
//!
//! ```
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! use std::io::Cursor;
//!
//! use dataprof_json::{JsonParserConfig, analyze_json_from_reader};
//!
//! let jsonl = "{\"id\": 1, \"city\": \"Rome\"}\n{\"id\": 2, \"city\": \"Milan\"}\n";
//! let (profiles, _stats, rows_read, malformed_lines, _format) =
//!     analyze_json_from_reader(Cursor::new(jsonl), &JsonParserConfig::jsonl())?;
//!
//! assert_eq!(rows_read, 2);
//! assert_eq!(malformed_lines, 0);
//! assert_eq!(profiles[0].name, "id");
//! # Ok(())
//! # }
//! ```

use std::collections::{HashMap, HashSet};
use std::io::{BufRead, Read};
use std::path::Path;

pub use dataprof_core::JsonErrorPolicy;

#[doc(hidden)]
pub mod record;
use dataprof_core::{
    AnalysisOptions, ColumnProfile, DataProfilerError, DataSource, ExecutionMetadata, FileFormat,
    TruncationReason, Utf8BomReader,
};
use dataprof_runtime::{
    ProfileReport, ReportAssembler, StreamingColumnCollection, profile_builder,
};
use record::{
    JsonRecord, drain_to_end, json_document_error, json_value_kind, json_value_text,
    malformed_array_error, non_object_record_error, object_record, read_json_record,
    read_jsonl_line, rest_is_white_space, skip_ascii_whitespace, skip_leading_white_space,
    wide_integer_record_error,
};
use serde_json::Value;

/// Which grammar a JSON source is read with.
///
/// The two are deliberately distinct: whitespace is insignificant inside a
/// standard JSON document and load-bearing in JSONL, so one input cannot be
/// valid under both readings and mean the same thing. Callers pick with
/// `format="json"` / `format="jsonl"`, or by file extension.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum JsonFormat {
    /// A standard JSON document, in either of the two shapes that carry
    /// records: an array of objects (`[{...}, {...}]`), or a single object
    /// (`{...}`) as one record. Values may span lines and be pretty-printed,
    /// and exactly one document must fill the whole input.
    Json,
    /// JSON Lines — one record per physical line. A record may not span lines,
    /// and a line may not hold more than one value.
    Jsonl,
}

/// Configuration for JSON/JSONL parsing and scanning.
///
/// The default detects the grammar from the input and reads every record,
/// skipping malformed ones. The two format constructors say which grammar to
/// read with, which is what a caller who knows should do: detection cannot tell
/// a JSON object document from a JSONL file, since both open with `{`.
///
/// # Examples
///
/// The same two records under each grammar:
///
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use std::io::Cursor;
///
/// use dataprof_json::{JsonParserConfig, scan_json_from_reader};
///
/// let document = r#"[{"id": 1}, {"id": 2}]"#;
/// let lines = "{\"id\": 1}\n{\"id\": 2}\n";
///
/// let from_document = scan_json_from_reader(
///     Cursor::new(document),
///     &JsonParserConfig::json_document(),
///     |_| {},
/// )?;
/// let from_lines =
///     scan_json_from_reader(Cursor::new(lines), &JsonParserConfig::jsonl(), |_| {})?;
///
/// assert_eq!(from_document.rows_read, 2);
/// assert_eq!(from_lines.rows_read, 2);
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, Default)]
pub struct JsonParserConfig {
    /// The grammar to read with. `None` detects it from the first byte, which
    /// resolves `[` to [`JsonFormat::Json`] and everything else to
    /// [`JsonFormat::Jsonl`] — a leading `{` opens both a JSON object document
    /// and a JSONL file, so callers that know which they have (from the file
    /// extension or an explicit `format=`) should say so rather than rely on
    /// detection.
    pub format: Option<JsonFormat>,
    /// Maximum rows to process (None = all rows).
    pub max_rows: Option<usize>,
    /// How to react to a malformed record (default: skip).
    pub error_policy: JsonErrorPolicy,
}

impl JsonParserConfig {
    /// Set the maximum number of rows to process.
    ///
    /// The cap counts profileable records, not lines: blank lines and records
    /// skipped as malformed do not consume it.
    ///
    /// A cap is only *truncation* when a record still remained once it was
    /// reached, so a source holding exactly `max_rows` records reads as
    /// complete. [`JsonScanSummary::truncated`] carries that distinction, and
    /// [`analyze_json_file`] turns it into a [`TruncationReason::MaxRows`] on
    /// the report.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use std::io::Cursor;
    ///
    /// use dataprof_json::{JsonParserConfig, scan_json_from_reader};
    ///
    /// let lines = "{\"id\": 1}\n{\"id\": 2}\n{\"id\": 3}\n";
    ///
    /// // Two of three records: a third remained, so the scan was cut short.
    /// let capped = JsonParserConfig::jsonl().with_max_rows(2);
    /// let summary = scan_json_from_reader(Cursor::new(lines), &capped, |_| {})?;
    /// assert_eq!(summary.rows_read, 2);
    /// assert!(summary.truncated);
    ///
    /// // A cap the source never reaches past is a complete read, not a
    /// // truncated one.
    /// let exact = JsonParserConfig::jsonl().with_max_rows(3);
    /// let summary = scan_json_from_reader(Cursor::new(lines), &exact, |_| {})?;
    /// assert_eq!(summary.rows_read, 3);
    /// assert!(!summary.truncated);
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_max_rows(mut self, max_rows: usize) -> Self {
        self.max_rows = Some(max_rows);
        self
    }

    /// Set how malformed records are handled.
    ///
    /// Under the default [`JsonErrorPolicy::Skip`] a malformed record is
    /// counted in [`JsonScanSummary::malformed_lines`] and scanning continues,
    /// so a partial profile never looks like a clean one. Under
    /// [`JsonErrorPolicy::Strict`] the first one fails the scan.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use std::io::Cursor;
    ///
    /// use dataprof_json::{JsonErrorPolicy, JsonParserConfig, scan_json_from_reader};
    ///
    /// let lines = "{\"id\": 1}\nnot json\n{\"id\": 2}\n";
    ///
    /// let skipping = JsonParserConfig::jsonl();
    /// let summary = scan_json_from_reader(Cursor::new(lines), &skipping, |_| {})?;
    /// assert_eq!(summary.rows_read, 2);
    /// assert_eq!(summary.malformed_lines, 1);
    ///
    /// let strict = JsonParserConfig::jsonl().with_error_policy(JsonErrorPolicy::Strict);
    /// assert!(scan_json_from_reader(Cursor::new(lines), &strict, |_| {}).is_err());
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_error_policy(mut self, policy: JsonErrorPolicy) -> Self {
        self.error_policy = policy;
        self
    }

    /// Read as JSON Lines: one record per physical line.
    pub fn jsonl() -> Self {
        Self {
            format: Some(JsonFormat::Jsonl),
            ..Default::default()
        }
    }

    /// Read as a standard JSON document: an array of records, or a single
    /// object as one record.
    pub fn json_document() -> Self {
        Self {
            format: Some(JsonFormat::Json),
            ..Default::default()
        }
    }

    /// Set the grammar explicitly.
    pub fn with_format(mut self, format: JsonFormat) -> Self {
        self.format = Some(format);
        self
    }
}

/// Borrowed JSON object callback payload.
///
/// The workspace enables `serde_json/preserve_order`, so iterating this map
/// yields fields in the order they appear in the source document rather than
/// alphabetically. That is what makes the column-ordering contract on
/// [`analyze_json_from_reader`] possible.
pub type JsonObject = serde_json::Map<String, Value>;

/// Summary of a JSON/JSONL scan.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct JsonScanSummary {
    pub rows_read: usize,
    /// Records that were read but not profiled: malformed JSON, and valid JSON
    /// values that are not objects and therefore carry no fields. Both are
    /// counted so a tolerant scan never looks like a clean one.
    pub malformed_lines: usize,
    pub format: FileFormat,
    /// The scan stopped at `max_rows` while records still remained. A source
    /// holding exactly `max_rows` records was read in full, so this stays false.
    pub truncated: bool,
    /// Under the skip policy, the array scanner stopped at an element it could
    /// not read past and left input after it unread. Whether that input held
    /// records is unknown, so the source was not exhausted: reporting it as
    /// read in full let a drained remainder pass as a complete profile (#1106).
    pub unread_after_fault: bool,
}

/// Scan JSON or JSONL input and invoke `on_object` for each object record.
///
/// - **JSONL**: one record per physical line. A record may not span lines and a
///   line may not hold more than one value, so a concatenation whose delimiter
///   was lost is reported rather than read as several clean records. Blank lines
///   are separators: neither records nor errors.
/// - **JSON**: one standard document. An array of objects streams element by
///   element without buffering the whole input; a single object is read whole
///   and is one record, which is why it may be pretty-printed across lines.
///
/// # Record policy
///
/// Only JSON objects are profileable records — they are the only JSON value
/// with named fields to turn into columns. A record that is valid JSON but not
/// an object (a scalar, an array, `null`) is never silently discarded: under
/// [`JsonErrorPolicy::Skip`] it is counted in
/// [`JsonScanSummary::malformed_lines`] and scanning continues with the next
/// record, and under [`JsonErrorPolicy::Strict`] the first one fails the scan.
///
/// # Examples
///
/// Reading JSONL, keeping one field per record:
///
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use std::io::Cursor;
///
/// use dataprof_json::{JsonParserConfig, scan_json_from_reader};
///
/// let lines = "{\"city\": \"Rome\", \"pop\": 2800000}\n\
///              {\"city\": \"Milan\", \"pop\": 1400000}\n";
///
/// let mut cities = Vec::new();
/// let summary = scan_json_from_reader(
///     Cursor::new(lines),
///     &JsonParserConfig::jsonl(),
///     |object| {
///         if let Some(city) = object.get("city").and_then(|value| value.as_str()) {
///             cities.push(city.to_string());
///         }
///     },
/// )?;
///
/// assert_eq!(cities, ["Rome", "Milan"]);
/// assert_eq!(summary.rows_read, 2);
/// assert!(!summary.truncated);
/// # Ok(())
/// # }
/// ```
///
/// The same records as a JSON array. The array streams element by element, and
/// a record may be pretty-printed across lines because whitespace carries no
/// meaning under this grammar:
///
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use std::io::Cursor;
///
/// use dataprof_json::{JsonParserConfig, scan_json_from_reader};
///
/// let document = r#"[
///     {"city": "Rome", "pop": 2800000},
///     {"city": "Milan", "pop": 1400000}
/// ]"#;
///
/// let mut populations = Vec::new();
/// let summary = scan_json_from_reader(
///     Cursor::new(document),
///     &JsonParserConfig::json_document(),
///     |object| {
///         // A field that is absent, or present but not a number, stays
///         // `None`. Reading it as 0 instead would turn a missing value into
///         // a real measurement, which is the one thing a profile must never
///         // do.
///         populations.push(object.get("pop").and_then(|value| value.as_u64()));
///     },
/// )?;
///
/// assert_eq!(populations, [Some(2_800_000), Some(1_400_000)]);
/// assert_eq!(summary.rows_read, 2);
/// assert_eq!(summary.malformed_lines, 0);
/// # Ok(())
/// # }
/// ```
pub fn scan_json_from_reader<R, F>(
    reader: R,
    config: &JsonParserConfig,
    mut on_object: F,
) -> Result<JsonScanSummary, DataProfilerError>
where
    R: BufRead,
    F: FnMut(&JsonObject),
{
    let mut reader = Utf8BomReader::new(reader).map_err(DataProfilerError::from)?;
    // The Unicode White_Space before a document is skipped, so detection
    // and the array branch see past it as the object and JSONL readers'
    // `trim` does (#1146). An explicit JSONL source is read from its first
    // byte, as before, so its line numbers count every line.
    let leading = match config.format {
        Some(JsonFormat::Jsonl) => None,
        _ => Some(skip_leading_white_space(&mut reader)?),
    };
    let first = leading.as_ref().and_then(|leading| leading.first);
    // decode-audit: no-data — an explicit JSONL source skips nothing, so no
    // character was held back to chain in front of the reader.
    let pending = leading.map(|leading| leading.pending).unwrap_or_default();
    let mut reader = std::io::Cursor::new(pending).chain(reader);
    let format = match config.format {
        Some(JsonFormat::Json) => FileFormat::Json,
        Some(JsonFormat::Jsonl) => FileFormat::Jsonl,
        // A leading `{` is the first byte of both a JSON object document and a
        // JSONL file, so detection can only resolve the array case and has to
        // fall back to JSONL. Callers that know better pass `format`.
        None if first == Some(b'[') => FileFormat::Json,
        None => FileFormat::Jsonl,
    };

    let mut rows_read = 0;
    let mut malformed_lines = 0;
    let mut unread_after_fault = false;
    let mut truncated = false;

    match format {
        // JSONL is line-delimited: exactly one record per non-blank physical
        // line. Reading it as a whitespace-delimited stream of values instead
        // made `{"a":1}{"b":2}` — a concatenation with the delimiter lost —
        // profile as two clean rows, which is precisely the corruption a
        // profiler exists to surface.
        FileFormat::Jsonl => {
            let mut line = String::new();
            let mut line_number = 0;
            loop {
                if let Some(max) = config.max_rows
                    && rows_read >= max
                {
                    // Reaching the cap is not truncation unless a record
                    // actually remains: a file with exactly `max_rows` records
                    // was read in full. Blank lines are not records.
                    truncated = next_record_line(&mut reader, &mut line, &mut line_number)?;
                    break;
                }

                if !next_record_line(&mut reader, &mut line, &mut line_number)? {
                    break;
                }

                match read_jsonl_line(&line) {
                    JsonRecord::Object(obj) => {
                        on_object(&obj);
                        rows_read += 1;
                    }
                    JsonRecord::NonObject(kind) => {
                        if config.error_policy == JsonErrorPolicy::Strict {
                            return Err(non_object_record_error(
                                kind,
                                rows_read + malformed_lines + 1,
                            ));
                        }
                        malformed_lines += 1;
                    }
                    JsonRecord::Malformed(err) => {
                        if config.error_policy == JsonErrorPolicy::Strict {
                            return Err(record::malformed_jsonl_record_error(
                                line_number,
                                &line,
                                err,
                            ));
                        }
                        malformed_lines += 1;
                    }
                    JsonRecord::WideInteger => {
                        if config.error_policy == JsonErrorPolicy::Strict {
                            return Err(wide_integer_record_error(&format!(
                                "on line {line_number}"
                            )));
                        }
                        malformed_lines += 1;
                    }
                }
            }
        }
        FileFormat::Json => {
            // Which of the two record-carrying shapes this document is. The
            // first byte after the white space decides, and is left unconsumed
            // so the object branch still sees the value it opens.
            let found_array = first == Some(b'[');

            if !found_array {
                // The other shape a standard JSON document takes: a single
                // object, which is one record. It may be pretty-printed across
                // lines, which is why this is not the JSONL grammar.
                let (object_rows, object_malformed, object_truncated) =
                    scan_single_json_object(&mut reader, config, &mut on_object)?;
                rows_read += object_rows;
                malformed_lines += object_malformed;
                truncated |= object_truncated;
            } else {
                // The array loop starts after the opening bracket.
                consume_peeked(&mut reader)?;

                let mut expect_value = true;
                let mut allow_end = true;
                let mut array_closed = false;
                let mut drain_remainder = false;

                loop {
                    let Some(next) = consume_leading_whitespace(&mut reader)? else {
                        if config.error_policy == JsonErrorPolicy::Strict {
                            return Err(malformed_array_error(
                                "unexpected end of input before closing ']'",
                            ));
                        }
                        malformed_lines += 1;
                        drain_remainder = true;
                        break;
                    };

                    if expect_value {
                        if next == b']' {
                            if !allow_end {
                                if config.error_policy == JsonErrorPolicy::Strict {
                                    return Err(malformed_array_error(
                                        "trailing comma before closing ']'",
                                    ));
                                }
                                malformed_lines += 1;
                                drain_remainder = true;
                                break;
                            }
                            consume_peeked(&mut reader)?;
                            array_closed = true;
                            break;
                        }

                        if let Some(max) = config.max_rows
                            && rows_read >= max
                        {
                            // A value remains unread. Do not validate the unread
                            // suffix of an intentionally bounded scan.
                            truncated = true;
                            break;
                        }

                        if next == b',' {
                            if config.error_policy == JsonErrorPolicy::Strict {
                                return Err(malformed_array_error(
                                    "unexpected comma where an array value was required",
                                ));
                            }
                            malformed_lines += 1;
                            drain_remainder = true;
                            break;
                        }

                        match read_json_record(&mut reader, next)? {
                            JsonRecord::Object(obj) => {
                                on_object(&obj);
                                rows_read += 1;
                            }
                            JsonRecord::NonObject(kind) => {
                                if config.error_policy == JsonErrorPolicy::Strict {
                                    return Err(non_object_record_error(
                                        kind,
                                        rows_read + malformed_lines + 1,
                                    ));
                                }
                                // The element was consumed in full, so the array
                                // grammar is still intact and the objects after
                                // it are still profileable.
                                malformed_lines += 1;
                            }
                            JsonRecord::Malformed(err) => {
                                if config.error_policy == JsonErrorPolicy::Strict {
                                    return Err(malformed_record_error(err));
                                }
                                malformed_lines += 1;
                                drain_remainder = true;
                                break;
                            }
                            JsonRecord::WideInteger => {
                                if config.error_policy == JsonErrorPolicy::Strict {
                                    return Err(wide_integer_record_error(&format!(
                                        "at position {}",
                                        rows_read + malformed_lines + 1
                                    )));
                                }
                                // Read in full: the array grammar is intact.
                                malformed_lines += 1;
                            }
                        }
                        expect_value = false;
                    } else {
                        match next {
                            b',' => {
                                consume_peeked(&mut reader)?;
                                expect_value = true;
                                allow_end = false;
                            }
                            b']' => {
                                consume_peeked(&mut reader)?;
                                array_closed = true;
                                break;
                            }
                            _ => {
                                if config.error_policy == JsonErrorPolicy::Strict {
                                    return Err(malformed_array_error(
                                        "expected ',' or ']' after an array value",
                                    ));
                                }
                                malformed_lines += 1;
                                drain_remainder = true;
                                break;
                            }
                        }
                    }
                }

                if drain_remainder {
                    // Something left unread after the fault means the read
                    // stopped short, whatever that input held (#1106).
                    unread_after_fault = !rest_is_white_space(&mut reader)?.0;
                    drain_to_end(&mut reader)?;
                } else if array_closed && !rest_is_white_space(&mut reader)?.0 {
                    if config.error_policy == JsonErrorPolicy::Strict {
                        return Err(malformed_array_error(
                            "non-whitespace content follows the closing ']'",
                        ));
                    }
                    malformed_lines += 1;
                    drain_to_end(&mut reader)?;
                }
            }
        }
        _ => unreachable!("json scanner only returns json or jsonl formats"),
    }

    Ok(JsonScanSummary {
        rows_read,
        malformed_lines,
        format,
        truncated,
        unread_after_fault,
    })
}

/// Read the next line that holds a record into `line`, skipping blank ones.
///
/// Returns whether a record line was found. Blank lines are separators, not
/// records: they are skipped without counting as rows or as errors. `line_number`
/// counts every physical line read, blank ones included, so a diagnostic points
/// at the line the user would open the file to.
fn next_record_line<R: BufRead>(
    reader: &mut R,
    line: &mut String,
    line_number: &mut usize,
) -> Result<bool, DataProfilerError> {
    loop {
        line.clear();
        let read = reader.read_line(line).map_err(DataProfilerError::from)?;
        if read == 0 {
            return Ok(false);
        }
        *line_number += 1;
        if !line.trim().is_empty() {
            return Ok(true);
        }
    }
}

/// Read a whole-input single JSON object as one record.
///
/// Returns `(rows_read, malformed, truncated)`. Anything that is not exactly one object
/// filling the input is an error under [`JsonErrorPolicy::Strict`] and a counted
/// malformed record otherwise, so a truncated or concatenated document never
/// profiles as clean.
fn scan_single_json_object<R, F>(
    reader: &mut R,
    config: &JsonParserConfig,
    on_object: &mut F,
) -> Result<(usize, usize, bool), DataProfilerError>
where
    R: BufRead,
    F: FnMut(&JsonObject),
{
    let mut text = String::new();
    reader
        .read_to_string(&mut text)
        .map_err(DataProfilerError::from)?;

    if text.trim().is_empty() {
        return Ok((0, 0, false));
    }

    // A row cap of zero asks for no records, so the document is not read. The
    // record it holds is left unread, which is a truncation and has to be
    // reported as one — an unread record and an empty source must not produce
    // the same report.
    if config.max_rows == Some(0) {
        return Ok((0, 0, true));
    }

    match serde_json::from_str::<Value>(text.trim()) {
        Ok(Value::Object(obj)) => match object_record(obj, text.as_bytes()) {
            JsonRecord::Object(obj) => {
                on_object(&obj);
                Ok((1, 0, false))
            }
            _ => {
                if config.error_policy == JsonErrorPolicy::Strict {
                    return Err(wide_integer_record_error("at position 1"));
                }
                Ok((0, 1, false))
            }
        },
        Ok(value) => {
            if config.error_policy == JsonErrorPolicy::Strict {
                return Err(non_object_record_error(json_value_kind(&value), 1));
            }
            Ok((0, 1, false))
        }
        Err(err) => {
            if config.error_policy == JsonErrorPolicy::Strict {
                return Err(json_document_error(err));
            }
            Ok((0, 1, false))
        }
    }
}

/// Consume the byte [`consume_leading_whitespace`] just reported, along with the
/// whitespace it looked past.
///
/// That function only peeks — it leaves the whitespace queued so serde keeps its
/// line and column context — so consuming one byte would eat a space rather than
/// the delimiter. Getting this wrong made a pretty-printed JSON array report a
/// phantom malformed record, because the `]` survived the consume and then
/// looked like content after the closing bracket.
fn consume_peeked<R: BufRead>(reader: &mut R) -> Result<(), DataProfilerError> {
    skip_ascii_whitespace(reader)?;
    reader.consume(1);
    Ok(())
}

/// Build a strict-mode parse error from a serde failure. The serde message
/// carries line/column context but never the record contents, so it is safe to
/// surface directly.
fn malformed_record_error(err: serde_json::Error) -> DataProfilerError {
    let message = format!("malformed JSON record: {err}");
    DataProfilerError::json_parsing_with_source(message, err)
}

fn consume_leading_whitespace<R: BufRead>(reader: &mut R) -> Result<Option<u8>, DataProfilerError> {
    loop {
        let mut bytes_to_consume = 0;
        let first_non_whitespace = {
            let buf = reader.fill_buf().map_err(DataProfilerError::from)?;
            if buf.is_empty() {
                return Ok(None);
            }

            let first_non_whitespace = buf.iter().find(|byte| !byte.is_ascii_whitespace()).copied();
            if first_non_whitespace.is_none() {
                bytes_to_consume = buf.len();
            }
            first_non_whitespace
        };

        if first_non_whitespace.is_some() {
            return Ok(first_non_whitespace);
        }

        reader.consume(bytes_to_consume);
    }
}

/// Feed a JSON object's fields into a [`StreamingColumnCollection`].
///
/// Columns are registered in the order the fields appear in each record, so the
/// resulting column order is the first record's field order with later-only
/// fields appended where they were first seen.
///
/// `container_counts` tallies, per column, the values that were an object or an
/// array. It is what [`profile_builder::mark_container_columns`] later reads
/// to decide which columns hold nothing but containers.
fn feed_json_object(
    obj: &JsonObject,
    prior_rows: usize,
    known_columns: &mut Vec<String>,
    known_columns_set: &mut HashSet<String>,
    column_stats: &mut StreamingColumnCollection,
    container_counts: &mut HashMap<String, usize>,
) {
    for (key, value) in obj {
        if known_columns_set.insert(key.clone()) {
            known_columns.push(key.clone());
            column_stats.init_column_with_missing(key, prior_rows);
        }
        if matches!(value, Value::Array(_) | Value::Object(_)) {
            *container_counts.entry(key.clone()).or_default() += 1;
        }
    }

    let values: Vec<String> = known_columns
        .iter()
        .map(|column| {
            // decode-audit: no-data — a key absent from this object is a
            // missing field, and "" is the profiler's textual null.
            obj.get(column).map(json_value_text).unwrap_or_default()
        })
        .collect();
    let containers: Vec<usize> = known_columns
        .iter()
        .enumerate()
        .filter(|(_, column)| matches!(obj.get(*column), Some(Value::Array(_) | Value::Object(_))))
        .map(|(position, _)| position)
        .collect();

    column_stats.process_record_with_containers(known_columns, values, &containers);
}

/// Analyze JSON/JSONL data from a buffered reader using streaming statistics.
///
/// Returns `(column_profiles, streaming_stats, rows_read, malformed_lines, detected_format)`.
///
/// # Column order
///
/// Columns are returned in source order — the first record's field order, with
/// fields that only appear in later records appended in first-seen order. This
/// matches CSV (header order) and Parquet (schema order), so the same logical
/// dataset profiles to the same column order in every format.
///
/// # Examples
///
/// The second record lists its fields in a different order and adds one. The
/// first record still decides the order, and the new field is appended:
///
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use std::io::Cursor;
///
/// use dataprof_json::{JsonParserConfig, analyze_json_from_reader};
///
/// let lines = "{\"id\": 1, \"city\": \"Rome\"}\n\
///              {\"city\": \"Milan\", \"id\": 2, \"region\": \"Lombardy\"}\n";
///
/// let (profiles, _stats, rows_read, malformed_lines, format) =
///     analyze_json_from_reader(Cursor::new(lines), &JsonParserConfig::jsonl())?;
///
/// let names: Vec<&str> = profiles.iter().map(|profile| profile.name.as_str()).collect();
/// assert_eq!(names, ["id", "city", "region"]);
/// assert_eq!(rows_read, 2);
/// assert_eq!(malformed_lines, 0);
/// assert_eq!(format, dataprof_core::FileFormat::Jsonl);
///
/// // The first record has no `region`, which counts as a missing value.
/// let region = &profiles[2];
/// assert_eq!(region.total_count, 2);
/// assert_eq!(region.null_count, 1);
/// # Ok(())
/// # }
/// ```
pub fn analyze_json_from_reader<R: BufRead>(
    reader: R,
    config: &JsonParserConfig,
) -> Result<
    (
        Vec<ColumnProfile>,
        StreamingColumnCollection,
        usize,
        usize,
        FileFormat,
    ),
    DataProfilerError,
> {
    let options = AnalysisOptions::default();
    let (profiles, stats, rows_read, malformed_lines, format, _truncated, _unread) =
        analyze_json_from_reader_full(reader, config, &options)?;
    Ok((profiles, stats, rows_read, malformed_lines, format))
}

/// As [`analyze_json_from_reader`], but with the caller's analysis options, and
/// also reports whether the scan stopped early at a row cap, and whether it
/// left input unread after a fault. Kept private so the public tuple stays
/// stable.
#[allow(clippy::type_complexity)]
fn analyze_json_from_reader_full<R: BufRead>(
    reader: R,
    config: &JsonParserConfig,
    options: &AnalysisOptions,
) -> Result<
    (
        Vec<ColumnProfile>,
        StreamingColumnCollection,
        usize,
        usize,
        FileFormat,
        bool,
        bool,
    ),
    DataProfilerError,
> {
    let semantic_hints = options.semantic_hints();
    let mut column_stats = StreamingColumnCollection::new()
        .with_semantic_hints(semantic_hints)
        .with_duplicate_rows_exact_limit(options.duplicate_rows_exact_limit());
    let mut known_columns = Vec::new();
    let mut known_columns_set = HashSet::new();
    let mut container_counts = HashMap::new();
    let mut rows_seen = 0;

    let summary = scan_json_from_reader(reader, config, |obj| {
        feed_json_object(
            obj,
            rows_seen,
            &mut known_columns,
            &mut known_columns_set,
            &mut column_stats,
            &mut container_counts,
        );
        rows_seen += 1;
    })?;

    if let Some(indices) = options.column_indices(&column_stats.column_names())? {
        let available = column_stats.column_names();
        let selected = indices
            .into_iter()
            .map(|index| available[index].clone())
            .collect::<Vec<_>>();
        column_stats.retain_columns(&selected);
    }

    let profiles = profile_builder::mark_container_columns(
        profile_builder::profiles_from_streaming_with_hints(
            &column_stats,
            !options.include_statistics(),
            !options.include_patterns(),
            options.locale(),
            semantic_hints,
        ),
        &container_counts,
    );

    Ok((
        profiles,
        column_stats,
        summary.rows_read,
        summary.malformed_lines,
        summary.format,
        summary.truncated,
        summary.unread_after_fault,
    ))
}

/// Analyze a JSON or JSONL file, returning a full [`ProfileReport`].
///
/// With no explicit [`JsonParserConfig::format`] the file extension decides:
/// `.json` reads as a standard document, `.jsonl` and `.ndjson` as JSON Lines,
/// and any other name falls back to sniffing the first byte.
///
/// # Examples
///
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use std::io::Write;
///
/// use dataprof_json::{JsonParserConfig, analyze_json_file};
///
/// let mut file = tempfile::NamedTempFile::with_suffix(".jsonl")?;
/// writeln!(file, "{{\"id\": 1, \"score\": 9.5}}")?;
/// writeln!(file, "{{\"id\": 2, \"score\": 7.0}}")?;
/// file.flush()?;
///
/// let report = analyze_json_file(file.path(), &JsonParserConfig::default())?;
///
/// assert_eq!(report.execution.rows_processed, 2);
/// assert_eq!(report.execution.columns_detected, 2);
/// assert!(report.execution.truncation_reason.is_none());
/// # Ok(())
/// # }
/// ```
pub fn analyze_json_file(
    file_path: &Path,
    config: &JsonParserConfig,
) -> Result<ProfileReport, DataProfilerError> {
    analyze_json_file_with_options(file_path, config, &AnalysisOptions::default())
}

/// Analyze a JSON or JSONL file, honouring the caller's full analysis selection.
///
/// This is the entry point that carries metric packs and locale as well as
/// dimensions and hints, so a JSON profile reports exactly the analysis the
/// caller asked for — the same selection the CSV engines apply.
pub fn analyze_json_file_with_options(
    file_path: &Path,
    config: &JsonParserConfig,
    options: &AnalysisOptions,
) -> Result<ProfileReport, DataProfilerError> {
    // An explicit grammar wins; otherwise the file name gets a say before
    // content sniffing, which cannot tell a JSON object from a JSONL stream.
    let mut config = config.clone();
    if config.format.is_none() {
        config.format = grammar_for_extension(file_path);
    }
    let config = &config;
    let metadata = std::fs::metadata(file_path).map_err(|error| map_io_error(file_path, error))?;
    dataprof_core::binary_input::reject_binary_input(file_path)?;
    let start = std::time::Instant::now();

    let file = std::fs::File::open(file_path).map_err(|error| map_io_error(file_path, error))?;
    let buf_reader = std::io::BufReader::new(file);

    let (
        column_profiles,
        column_stats,
        rows_read,
        malformed_lines,
        format,
        truncated,
        unread_after_fault,
    ) = analyze_json_from_reader_full(buf_reader, config, options)?;
    let read_as_json_document = format == FileFormat::Json;

    let file_source = DataSource::File {
        path: file_path.display().to_string(),
        format,
        size_bytes: metadata.len(),
        modified_at: None,
        parquet_metadata: None,
        csv_metadata: None,
    };

    if rows_read == 0 {
        if malformed_lines > 0 {
            // Nothing parsed under the JSON grammar most often means the source
            // is JSONL, so say so here too: under the default skip policy this
            // is the only error the caller sees.
            let hint = if read_as_json_document {
                ". A JSON source must hold exactly one array or object; for one record per line use format=\"jsonl\""
            } else {
                ""
            };
            // Aggregate over many discarded records: no single decoder error
            // is the cause, so none is retained.
            return Err(DataProfilerError::json_parsing_error(&format!(
                "No valid JSON records found in file \
                 (every record was malformed, not a JSON object, or held an integer outside the 64-bit range){hint}"
            )));
        }
        // A row cap that stopped the scan before the first record still has to
        // be disclosed. Without this the report reads exactly like a complete
        // profile of an empty source, which is the one thing a truncated scan
        // must never be mistaken for.
        let mut execution =
            ExecutionMetadata::new(0, 0, start.elapsed().as_millis()).with_engine("json");
        if truncated && let Some(max) = config.max_rows {
            execution = execution.with_truncation(TruncationReason::MaxRows(max as u64));
        }
        return Ok(ReportAssembler::new(file_source, execution)
            .columns(column_profiles)
            .with_quality_data(HashMap::new())
            .with_analysis_options(options)
            .build());
    }

    let sample_columns = profile_builder::quality_check_samples(&column_stats);
    let scan_time_ms = start.elapsed().as_millis();
    let num_columns = column_profiles.len();

    let mut execution = ExecutionMetadata::new(rows_read, num_columns, scan_time_ms)
        .with_engine("json")
        // Tolerant scans surface skipped malformed records here so callers can
        // tell a partial profile from a clean one.
        .with_error_count(malformed_lines);
    // `truncated` is set only when a record still remained at the cap, so a source
    // holding exactly `max_rows` records is reported as fully read, not cut short.
    if truncated && let Some(max) = config.max_rows {
        execution = execution.with_truncation(TruncationReason::MaxRows(max as u64));
    }
    if unread_after_fault {
        execution = execution.with_source_exhausted(false);
    }

    Ok(ReportAssembler::new(file_source, execution)
        .columns(column_profiles)
        .with_quality_data(sample_columns)
        .with_row_duplicates(column_stats.row_duplicate_summary())
        .with_row_completeness(column_stats.row_completeness_summary())
        .with_exact_value_hint_bindings(column_stats.semantic_hint_bindings())
        .with_analysis_options(options)
        .build())
}

/// The grammar a file name advertises, if it advertises one.
///
/// Content sniffing resolves a leading `[` on its own, but not a leading `{`:
/// that is the first byte of both a JSON object document and a JSONL file. The
/// extension is the evidence that separates them, and a `.json` file holding one
/// pretty-printed object is an ordinary thing to profile. `None` means the name
/// says nothing and the content decides.
fn grammar_for_extension(file_path: &Path) -> Option<JsonFormat> {
    let extension = file_path.extension().and_then(|ext| ext.to_str())?;
    if extension.eq_ignore_ascii_case("json") {
        Some(JsonFormat::Json)
    } else if extension.eq_ignore_ascii_case("jsonl") || extension.eq_ignore_ascii_case("ndjson") {
        Some(JsonFormat::Jsonl)
    } else {
        None
    }
}

fn map_io_error(file_path: &Path, error: std::io::Error) -> DataProfilerError {
    if error.kind() == std::io::ErrorKind::NotFound {
        DataProfilerError::FileNotFound {
            path: file_path.display().to_string(),
        }
    } else {
        DataProfilerError::from(error)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::{Cursor, Write};
    use tempfile::NamedTempFile;

    /// A temp file with no extension, so `analyze_json_file` falls back to the
    /// JSONL grammar the way an unnamed stream does.
    fn write_file(content: &str) -> NamedTempFile {
        let mut file = NamedTempFile::new().unwrap();
        write!(file, "{}", content).unwrap();
        file.flush().unwrap();
        file
    }

    /// A temp file named `.json`, so `analyze_json_file` reads it as a standard
    /// JSON document — the grammar the extension advertises.
    fn write_json_file(content: &str) -> NamedTempFile {
        let mut file = NamedTempFile::with_suffix(".json").unwrap();
        write!(file, "{}", content).unwrap();
        file.flush().unwrap();
        file
    }

    fn write_bytes(content: &[u8]) -> NamedTempFile {
        let mut file = NamedTempFile::new().unwrap();
        file.write_all(content).unwrap();
        file.flush().unwrap();
        file
    }

    #[test]
    fn test_scan_jsonl_detects_format_and_rows() {
        let data = b"{\"x\":1}\n{\"x\":2}\n{\"x\":3}\n";
        let mut rows = 0;

        let summary = scan_json_from_reader(
            Cursor::new(data.as_ref()),
            &JsonParserConfig::default(),
            |_| {
                rows += 1;
            },
        )
        .unwrap();

        assert_eq!(summary.format, FileFormat::Jsonl);
        assert_eq!(summary.rows_read, 3);
        assert_eq!(summary.malformed_lines, 0);
        assert_eq!(rows, 3);
    }

    #[test]
    fn test_scan_json_array_detects_format_and_rows() {
        let data = br#"[{"name":"Alice"},{"name":"Bob"}]"#;
        let mut keys = Vec::new();

        let summary = scan_json_from_reader(
            Cursor::new(data.as_ref()),
            &JsonParserConfig::default(),
            |obj| keys.push(obj.keys().cloned().collect::<Vec<_>>()),
        )
        .unwrap();

        assert_eq!(summary.format, FileFormat::Json);
        assert_eq!(summary.rows_read, 2);
        assert_eq!(keys.len(), 2);
        assert_eq!(keys[0], vec!["name".to_string()]);
    }

    #[test]
    fn test_scan_accepts_one_leading_utf8_bom_for_json_and_jsonl() {
        for (data, config, expected_format) in [
            (
                b"\xEF\xBB\xBF[{\"x\":1},{\"x\":2}]".as_slice(),
                JsonParserConfig::default(),
                FileFormat::Json,
            ),
            (
                b"\xEF\xBB\xBF{\"x\":1}\n{\"x\":2}\n".as_slice(),
                JsonParserConfig::default(),
                FileFormat::Jsonl,
            ),
        ] {
            let mut rows = 0;
            let summary = scan_json_from_reader(Cursor::new(data), &config, |_| rows += 1)
                .expect("leading UTF-8 BOM should be accepted");

            assert_eq!(rows, 2);
            assert_eq!(summary.rows_read, 2);
            assert_eq!(summary.malformed_lines, 0);
            assert_eq!(summary.format, expected_format);
        }
    }

    #[test]
    fn test_scan_does_not_strip_nonleading_or_second_utf8_bom() {
        let strict = JsonParserConfig::jsonl().with_error_policy(JsonErrorPolicy::Strict);

        for data in [
            b" \xEF\xBB\xBF{\"x\":1}\n".as_slice(),
            b"\xEF\xBB\xBF\xEF\xBB\xBF{\"x\":1}\n".as_slice(),
            b"{\"x\":1}\n\xEF\xBB\xBF{\"x\":2}\n".as_slice(),
        ] {
            scan_json_from_reader(Cursor::new(data), &strict, |_| {})
                .expect_err("only the BOM at absolute byte offset zero may be stripped");
        }
    }

    #[test]
    fn test_bom_only_input_matches_empty_input_policy() {
        for config in [JsonParserConfig::default(), JsonParserConfig::jsonl()] {
            let empty = scan_json_from_reader(Cursor::new(b""), &config, |_| {}).unwrap();
            let bom =
                scan_json_from_reader(Cursor::new(b"\xEF\xBB\xBF".as_slice()), &config, |_| {})
                    .unwrap();
            assert_eq!(bom, empty);
        }
    }

    #[test]
    fn test_json_array_container_grammar_obeys_error_policy() {
        let cases = [
            (br#"[{"x":1}"#.as_ref(), 1, "missing closing bracket"),
            (br#"[{"x":1},"#.as_ref(), 1, "comma followed by EOF"),
            (br#"[{"x":1} {"x":2}]"#.as_ref(), 1, "missing comma"),
            (br#"[{"x":1},,{"x":2}]"#.as_ref(), 1, "doubled comma"),
            (br#"[,{"x":1}]"#.as_ref(), 0, "leading comma"),
            (br#"[{"x":1},]"#.as_ref(), 1, "trailing comma"),
            (br#"[{"x":1}] trailing"#.as_ref(), 1, "trailing content"),
            (
                br#"[{"x":1}][{"x":2}]"#.as_ref(),
                1,
                "second top-level value",
            ),
        ];

        for (data, expected_rows, case) in cases {
            let skip = JsonParserConfig::json_document();
            let summary =
                scan_json_from_reader(Cursor::new(data), &skip, |_| {}).expect("tolerant scan");
            assert_eq!(summary.rows_read, expected_rows, "{case}");
            assert_eq!(summary.malformed_lines, 1, "{case}");

            let strict =
                JsonParserConfig::json_document().with_error_policy(JsonErrorPolicy::Strict);
            let err = scan_json_from_reader(Cursor::new(data), &strict, |_| {})
                .expect_err("strict mode must reject invalid array grammar");
            assert!(
                err.to_string()
                    .to_lowercase()
                    .contains("malformed json array"),
                "{case}: {err}"
            );
        }
    }

    #[test]
    fn test_json_array_max_rows_does_not_validate_unread_values() {
        let data = br#"[{"x":1},not-valid-json"#;
        let config = JsonParserConfig::json_document().with_max_rows(1);
        let summary = scan_json_from_reader(Cursor::new(data.as_ref()), &config, |_| {}).unwrap();

        assert_eq!(summary.rows_read, 1);
        assert_eq!(summary.malformed_lines, 0);
        assert!(summary.truncated);
    }

    #[test]
    fn test_scan_respects_max_rows() {
        let data = b"{\"x\":1}\n{\"x\":2}\n{\"x\":3}\n{\"x\":4}\n";
        let config = JsonParserConfig::default().with_max_rows(2);
        let mut rows = 0;

        let summary =
            scan_json_from_reader(Cursor::new(data.as_ref()), &config, |_| rows += 1).unwrap();

        assert_eq!(summary.rows_read, 2);
        assert_eq!(rows, 2);
    }

    #[test]
    fn test_scan_skips_malformed_jsonl_lines() {
        let data = b"{\"x\":1}\n{\"x\":,bad}\n{\"x\":3}\n";
        let mut rows = 0;

        let summary = scan_json_from_reader(
            Cursor::new(data.as_ref()),
            &JsonParserConfig::jsonl(),
            |_| {
                rows += 1;
            },
        )
        .unwrap();

        assert_eq!(summary.format, FileFormat::Jsonl);
        assert_eq!(summary.rows_read, 2);
        assert_eq!(summary.malformed_lines, 1);
        assert_eq!(rows, 2);
    }

    /// A pretty-printed root object is one record under the JSON grammar and a
    /// malformed record under JSONL (#486). It cannot be both: whitespace is
    /// insignificant in a JSON document and is the record delimiter in JSONL, so
    /// reading a multi-line object as JSONL would mean each of its lines is a
    /// record — none of which is valid JSON on its own.
    #[test]
    fn test_pretty_printed_root_object_is_one_row_under_the_json_grammar() {
        let data = br#"{
    "type": "FeatureCollection",
    "features": [
        {"id": 1},
        {"id": 2}
  ]
}"#;
        let mut object_field_counts = Vec::new();

        let summary = scan_json_from_reader(
            Cursor::new(data.as_ref()),
            &JsonParserConfig::json_document(),
            |obj| object_field_counts.push(obj.len()),
        )
        .unwrap();

        assert_eq!(summary.format, FileFormat::Json);
        assert_eq!(summary.rows_read, 1);
        assert_eq!(summary.malformed_lines, 0);
        assert_eq!(object_field_counts, vec![2]);
    }

    #[test]
    fn test_pretty_printed_root_object_is_not_valid_jsonl() {
        let data = br#"{
    "type": "FeatureCollection"
}"#;
        let err = scan_json_from_reader(
            Cursor::new(data.as_ref()),
            &JsonParserConfig::jsonl().with_error_policy(JsonErrorPolicy::Strict),
            |_| {},
        )
        .expect_err("a record spanning lines is not JSONL");

        assert!(
            err.to_string().contains("malformed JSON record"),
            "{err}, expected the malformed category"
        );
    }

    /// Every JSON value that is not an object, so none of them can be a row.
    /// Numbers are listed twice on purpose: they are the one value serde reads
    /// from a reader by peeking one byte past the end.
    const NON_OBJECT_VALUES: &[(&str, &str)] = &[
        ("null", "null"),
        ("boolean", "true"),
        ("number", "42"),
        ("number", "-1.5e3"),
        ("string", r#""text""#),
        ("array", "[1, 2]"),
    ];

    #[test]
    fn test_jsonl_counts_non_object_records_and_keeps_scanning() {
        for (kind, value) in NON_OBJECT_VALUES {
            let data = format!("{{\"id\":1}}\n{value}\n{{\"id\":2}}\n");
            let mut rows = 0;

            let summary = scan_json_from_reader(
                Cursor::new(data.as_bytes()),
                &JsonParserConfig::jsonl(),
                |_| rows += 1,
            )
            .unwrap();

            assert_eq!(summary.rows_read, 2, "{kind}: record after it was lost");
            assert_eq!(summary.malformed_lines, 1, "{kind}: was silently dropped");
            assert_eq!(rows, 2, "{kind}");
        }
    }

    #[test]
    fn test_json_array_counts_non_object_elements_and_keeps_scanning() {
        for (kind, value) in NON_OBJECT_VALUES {
            let data = format!("[{{\"id\":1}}, {value}, {{\"id\":2}}]");
            let mut rows = 0;

            let summary = scan_json_from_reader(
                Cursor::new(data.as_bytes()),
                &JsonParserConfig::json_document(),
                |_| rows += 1,
            )
            .unwrap();

            assert_eq!(summary.rows_read, 2, "{kind}: element after it was lost");
            assert_eq!(summary.malformed_lines, 1, "{kind}: was silently dropped");
            assert_eq!(rows, 2, "{kind}");
        }
    }

    #[test]
    fn test_strict_policy_rejects_the_first_non_object_record() {
        for (kind, value) in NON_OBJECT_VALUES {
            for (config, data) in [
                (
                    JsonParserConfig::jsonl(),
                    format!("{{\"id\":1}}\n{value}\n{{\"id\":2}}\n"),
                ),
                (
                    JsonParserConfig::json_document(),
                    format!("[{{\"id\":1}}, {value}, {{\"id\":2}}]"),
                ),
            ] {
                let config = config.with_error_policy(JsonErrorPolicy::Strict);
                let err = scan_json_from_reader(Cursor::new(data.as_bytes()), &config, |_| {})
                    .expect_err("{kind}: strict mode must reject a non-object record");

                let message = err.to_string();
                assert!(message.contains("non-object JSON record"), "{message}");
                assert!(message.contains("at position 2"), "{message}");
                assert!(message.contains(&format!("found {kind}")), "{message}");
            }
        }
    }

    #[test]
    fn test_number_element_does_not_swallow_the_array_delimiter() {
        // serde ends a number by peeking one byte past it and drops that byte
        // with the deserializer; here it is the `,` the array scanner needs.
        let data = br#"[{"id":1}, 1, 2, 3, {"id":2}, 4, {"id":3}]"#;
        let mut rows = 0;

        let summary = scan_json_from_reader(
            Cursor::new(data.as_ref()),
            &JsonParserConfig::json_document(),
            |_| rows += 1,
        )
        .unwrap();

        assert_eq!(summary.rows_read, 3);
        assert_eq!(summary.malformed_lines, 4);
        assert_eq!(rows, 3);
    }

    #[test]
    fn test_number_shaped_garbage_stays_a_malformed_record() {
        // `1.2.3` is read by the byte-wise number scanner but is not a number,
        // so it must not be reported as a valid non-object record.
        let data = b"{\"id\":1}\n1.2.3\n";
        let config = JsonParserConfig::jsonl().with_error_policy(JsonErrorPolicy::Strict);
        let err = scan_json_from_reader(Cursor::new(data.as_ref()), &config, |_| {})
            .expect_err("number-shaped garbage should be malformed");

        assert!(
            err.to_string().contains("malformed JSON record"),
            "{err}, expected the malformed category"
        );
    }

    #[test]
    fn test_input_of_only_non_object_records_fails() {
        let file = write_file("\"just a string\"\n1\n[2]\n");
        let err = analyze_json_file(file.path(), &JsonParserConfig::jsonl())
            .expect_err("nothing profileable should not return a clean empty profile");

        assert!(
            err.to_string().contains("No valid JSON records found"),
            "{err}"
        );
    }

    #[test]
    /// The JSON grammar accepts both shapes that carry records, so a bare object
    /// is one row rather than an error (#486).
    fn test_json_grammar_reads_a_bare_object_as_one_row() {
        let data = br#"{"x":1}"#;
        let mut rows = 0;
        let summary = scan_json_from_reader(
            Cursor::new(data.as_ref()),
            &JsonParserConfig::json_document(),
            |_| rows += 1,
        )
        .unwrap();

        assert_eq!(summary.rows_read, 1);
        assert_eq!(summary.malformed_lines, 0);
        assert_eq!(rows, 1);
    }

    #[test]
    /// Several objects back to back are not a JSON document. The error names
    /// the option that reads them, because this is what a JSONL file looks like
    /// when it is read with the wrong grammar.
    fn test_json_grammar_rejects_concatenated_objects() {
        let data = br#"{"x":1}{"x":2}"#;
        let err = scan_json_from_reader(
            Cursor::new(data.as_ref()),
            &JsonParserConfig::json_document().with_error_policy(JsonErrorPolicy::Strict),
            |_| {},
        )
        .expect_err("two objects are not one JSON document");

        let message = err.to_string();
        assert!(message.contains("malformed JSON document"), "{message}");
        assert!(message.contains("format=\"jsonl\""), "{message}");
    }

    #[test]
    fn test_analyze_json_from_reader_jsonl_streaming() {
        let data = b"{\"x\":1,\"y\":\"a\"}\n{\"x\":2,\"y\":\"b\"}\n{\"x\":3,\"y\":\"c\"}\n";
        let cursor = Cursor::new(data.as_ref());
        let config = JsonParserConfig::default();

        let (profiles, _stats, rows, _malformed, format) =
            analyze_json_from_reader(cursor, &config).unwrap();
        assert_eq!(format, FileFormat::Jsonl);
        assert_eq!(rows, 3);
        assert_eq!(profiles.len(), 2);
    }

    #[test]
    fn test_analyze_json_from_reader_json_array() {
        let data = br#"[{"name":"Alice","age":25},{"name":"Bob","age":30}]"#;
        let cursor = Cursor::new(data.as_ref());
        let config = JsonParserConfig::default();

        let (profiles, _stats, rows, _malformed, format) =
            analyze_json_from_reader(cursor, &config).unwrap();
        assert_eq!(format, FileFormat::Json);
        assert_eq!(rows, 2);
        assert_eq!(profiles.len(), 2);
    }

    #[test]
    fn test_integer_negative_zero_profiles_as_integer_zero_in_every_shape() {
        for (data, config) in [
            (
                &b"[{\"v\":0},{\"v\":-0}]"[..],
                JsonParserConfig::json_document(),
            ),
            (&b"{\"v\":0}\n{\"v\":-0}\n"[..], JsonParserConfig::jsonl()),
            (&b"{\"v\":-0}"[..], JsonParserConfig::json_document()),
        ] {
            let (profiles, _stats, _rows, _malformed, _format) =
                analyze_json_from_reader(Cursor::new(data), &config).unwrap();
            assert_eq!(
                profiles[0].data_type,
                dataprof_core::DataType::Integer,
                "{data:?}"
            );
            assert_eq!(profiles[0].unique_count, Some(1), "{data:?}");
        }
    }

    #[test]
    fn test_analyze_json_from_reader_max_rows() {
        let data = b"{\"x\":1}\n{\"x\":2}\n{\"x\":3}\n{\"x\":4}\n{\"x\":5}\n";
        let cursor = Cursor::new(data.as_ref());
        let config = JsonParserConfig::default().with_max_rows(3);

        let (_profiles, _stats, rows, _malformed, _format) =
            analyze_json_from_reader(cursor, &config).unwrap();
        assert_eq!(rows, 3);
    }

    #[test]
    fn test_analyze_json_from_reader_missing_fields() {
        let data = b"{\"a\":1,\"b\":2}\n{\"a\":3}\n";
        let cursor = Cursor::new(data.as_ref());
        let config = JsonParserConfig::jsonl();

        let (profiles, _stats, rows, _malformed, _format) =
            analyze_json_from_reader(cursor, &config).unwrap();
        assert_eq!(rows, 2);

        let col_b = profiles.iter().find(|profile| profile.name == "b").unwrap();
        assert_eq!(col_b.total_count, 2);
    }

    #[test]
    fn test_identical_records_count_as_duplicates_across_a_late_key() {
        // Records 1 and 3 are byte-identical; `b` is only discovered between
        // them. Signing a row against whatever columns happened to be known at
        // the time would make the two look different and report no duplicate.
        let data = b"{\"a\": \"x\"}\n{\"a\": \"x\", \"b\": \"y\"}\n{\"a\": \"x\"}\n";
        let cursor = Cursor::new(data.as_ref());
        let config = JsonParserConfig::jsonl();

        let (_profiles, stats, rows, _malformed, _format) =
            analyze_json_from_reader(cursor, &config).unwrap();
        assert_eq!(rows, 3);

        let summary = stats
            .row_duplicate_summary()
            .expect("three rows were observed");
        assert_eq!(summary.rows_checked, 3);
        assert_eq!(summary.duplicate_rows, 1);
        assert!(!summary.approximate);
    }

    #[test]
    fn test_a_late_key_does_not_invent_duplicates() {
        // The counterpart guard: collapsing the trailing absent field must not
        // merge rows that differ in the columns they do share.
        let data = b"{\"a\": \"x\"}\n{\"a\": \"x\", \"b\": \"y\"}\n{\"a\": \"z\"}\n";
        let cursor = Cursor::new(data.as_ref());
        let config = JsonParserConfig::jsonl();

        let (_profiles, stats, _rows, _malformed, _format) =
            analyze_json_from_reader(cursor, &config).unwrap();

        let summary = stats
            .row_duplicate_summary()
            .expect("three rows were observed");
        assert_eq!(summary.duplicate_rows, 0);
    }

    #[test]
    fn test_analyze_json_file_quality_report() {
        let file = write_file(r#"[{"x":1},{"x":2}]"#);
        let config = JsonParserConfig::default();
        let report = analyze_json_file(file.path(), &config).unwrap();

        assert_eq!(report.execution.rows_processed, 2);
        assert_eq!(report.column_profiles.len(), 1);
        assert!(report.quality_score().unwrap() >= 0.0);
    }

    #[test]
    fn test_jsonl_skips_malformed_lines() {
        let data = b"{\"x\":1}\n{\"x\":,malformed}\n{\"x\":3}\n";
        let cursor = Cursor::new(data.as_ref());
        let config = JsonParserConfig::jsonl();

        let (profiles, _stats, rows, _malformed, format) =
            analyze_json_from_reader(cursor, &config).unwrap();
        assert_eq!(format, FileFormat::Jsonl);
        assert_eq!(rows, 2);
        assert_eq!(profiles[0].total_count, 2);
    }

    #[test]
    fn test_strict_policy_errors_on_malformed_jsonl() {
        // Malformed in first / middle / last position all abort under Strict.
        for data in [
            b"not-json\n{\"x\":1}\n{\"x\":2}\n".as_ref(),
            b"{\"x\":1}\nnot-json\n{\"x\":2}\n".as_ref(),
            b"{\"x\":1}\n{\"x\":2}\nnot-json\n".as_ref(),
        ] {
            let config = JsonParserConfig::jsonl().with_error_policy(JsonErrorPolicy::Strict);
            let err = scan_json_from_reader(Cursor::new(data), &config, |_| {})
                .expect_err("strict mode must reject malformed records");
            let message = err.to_string().to_lowercase();
            assert!(message.contains("malformed json record"), "got: {message}");
            // The offending record text must never be echoed back.
            assert!(
                !err.to_string().contains("not-json"),
                "leaked record: {err}"
            );
        }
    }

    #[test]
    fn test_tolerant_policy_counts_skipped_records() {
        let data = b"{\"x\":1}\nnot-json\n{\"x\":2}\n";
        let config = JsonParserConfig::jsonl(); // default Skip
        let summary = scan_json_from_reader(Cursor::new(data.as_ref()), &config, |_| {}).unwrap();
        assert_eq!(summary.rows_read, 2);
        assert_eq!(summary.malformed_lines, 1);
    }

    #[test]
    fn test_blank_lines_are_not_counted_as_malformed() {
        let data = b"{\"x\":1}\n\n   \n{\"x\":2}\n";
        for policy in [JsonErrorPolicy::Skip, JsonErrorPolicy::Strict] {
            let config = JsonParserConfig::jsonl().with_error_policy(policy);
            let summary =
                scan_json_from_reader(Cursor::new(data.as_ref()), &config, |_| {}).unwrap();
            assert_eq!(summary.rows_read, 2, "policy {policy:?}");
            assert_eq!(summary.malformed_lines, 0, "policy {policy:?}");
        }
    }

    #[test]
    fn test_truncated_final_record_obeys_error_policy() {
        let data = b"{\"x\":1}\n{\"x\":2";

        let skip = JsonParserConfig::jsonl().with_error_policy(JsonErrorPolicy::Skip);
        let summary = scan_json_from_reader(Cursor::new(data.as_ref()), &skip, |_| {}).unwrap();
        assert_eq!(summary.rows_read, 1);
        assert_eq!(summary.malformed_lines, 1);

        let strict = JsonParserConfig::jsonl().with_error_policy(JsonErrorPolicy::Strict);
        let err = scan_json_from_reader(Cursor::new(data.as_ref()), &strict, |_| {})
            .expect_err("strict mode must reject an incomplete trailing record");
        assert!(
            err.to_string()
                .to_lowercase()
                .contains("malformed json record")
        );
    }

    #[test]
    fn test_all_malformed_file_fails() {
        let file = write_file("not-json\nalso-bad\n");
        let config = JsonParserConfig::jsonl();
        let err = analyze_json_file(file.path(), &config)
            .expect_err("a file with no valid records must fail");
        let message = err.to_string().to_lowercase();
        assert!(message.contains("no valid json records"), "got: {message}");
    }

    #[test]
    fn test_tolerant_file_reports_error_count() {
        let file = write_file("{\"x\":1}\nnot-json\n{\"x\":2}\n");
        let config = JsonParserConfig::jsonl();
        let report = analyze_json_file(file.path(), &config).unwrap();
        assert_eq!(report.execution.rows_processed, 2);
        assert_eq!(report.execution.error_count, 1);
    }

    #[test]
    fn test_strict_file_errors_on_malformed() {
        let file = write_file("{\"x\":1}\nnot-json\n{\"x\":2}\n");
        let config = JsonParserConfig::jsonl().with_error_policy(JsonErrorPolicy::Strict);
        let err = analyze_json_file(file.path(), &config)
            .expect_err("strict mode must reject the malformed record");
        assert!(
            err.to_string()
                .to_lowercase()
                .contains("malformed json record")
        );
    }

    #[test]
    fn test_analyze_json_with_large_leading_whitespace() {
        let data = format!("{}[{{\"x\":1}}]", " ".repeat(10_000));
        let cursor = Cursor::new(data.into_bytes());
        let config = JsonParserConfig::default();

        let (_profiles, _stats, rows, malformed, format) =
            analyze_json_from_reader(cursor, &config).unwrap();
        assert_eq!(format, FileFormat::Json);
        assert_eq!(rows, 1);
        assert_eq!(malformed, 0);
    }

    #[test]
    fn test_analyze_json_array() {
        let json = write_file(r#"[{"name":"Alice","age":25},{"name":"Bob","age":30}]"#);
        let config = JsonParserConfig::default();
        let report = analyze_json_file(json.path(), &config).unwrap();
        let profiles = &report.column_profiles;

        assert_eq!(profiles.len(), 2);
        let names: Vec<&str> = profiles
            .iter()
            .map(|profile| profile.name.as_str())
            .collect();
        assert!(names.contains(&"name"));
        assert!(names.contains(&"age"));

        let age = profiles
            .iter()
            .find(|profile| profile.name == "age")
            .unwrap();
        assert_eq!(age.total_count, 2);
        assert_eq!(age.null_count, 0);
    }

    #[test]
    fn test_analyze_jsonl() {
        let jsonl = write_file("{\"x\":1}\n{\"x\":2}\n{\"x\":3}\n");
        let config = JsonParserConfig::default();
        let report = analyze_json_file(jsonl.path(), &config).unwrap();
        let profiles = &report.column_profiles;

        assert_eq!(profiles.len(), 1);
        assert_eq!(profiles[0].name, "x");
        assert_eq!(profiles[0].total_count, 3);
    }

    #[test]
    fn test_analyze_json_with_nulls() {
        let json = write_file(r#"[{"a":"hello","b":1},{"a":null,"b":2},{"a":"world","b":null}]"#);
        let config = JsonParserConfig::default();
        let report = analyze_json_file(json.path(), &config).unwrap();
        let profiles = &report.column_profiles;

        let col_a = profiles.iter().find(|profile| profile.name == "a").unwrap();
        assert_eq!(col_a.null_count, 1);

        let col_b = profiles.iter().find(|profile| profile.name == "b").unwrap();
        assert_eq!(col_b.null_count, 1);
    }

    #[test]
    fn test_analyze_json_with_missing_fields() {
        let json = write_file(r#"[{"a":1,"b":2},{"a":3}]"#);
        let config = JsonParserConfig::default();
        let report = analyze_json_file(json.path(), &config).unwrap();
        let profiles = &report.column_profiles;

        let col_b = profiles.iter().find(|profile| profile.name == "b").unwrap();
        assert_eq!(col_b.total_count, 2);
    }

    /// Deliberately non-alphabetical field order: sorting would give
    /// `active, amount, date, id`, so any re-sort is visible.
    const UNSORTED_FIELDS: &str = r#"{"id":1,"amount":12.5,"active":true,"date":"2026-07-23"}"#;
    const UNSORTED_ORDER: [&str; 4] = ["id", "amount", "active", "date"];

    fn profile_names(report: &ProfileReport) -> Vec<&str> {
        report
            .column_profiles
            .iter()
            .map(|profile| profile.name.as_str())
            .collect()
    }

    #[test]
    fn test_json_column_order_follows_source_not_alphabet() {
        let array = write_file(&format!("[{UNSORTED_FIELDS},{UNSORTED_FIELDS}]"));
        let jsonl = write_file(&format!("{UNSORTED_FIELDS}\n{UNSORTED_FIELDS}\n"));

        for file in [&array, &jsonl] {
            let report = analyze_json_file(file.path(), &JsonParserConfig::default()).unwrap();
            assert_eq!(profile_names(&report), UNSORTED_ORDER);
        }
    }

    #[test]
    fn test_json_column_order_appends_later_keys_in_first_seen_order() {
        // Each record introduces two keys in reverse-alphabetical order, so
        // sorting would reshuffle both the leading pair and the appended pair.
        let data = b"{\"zulu\":1,\"mike\":2}\n{\"zulu\":3,\"mike\":4,\"delta\":5,\"alpha\":6}\n";
        let file = write_bytes(data);
        let report = analyze_json_file(file.path(), &JsonParserConfig::jsonl()).unwrap();

        assert_eq!(profile_names(&report), ["zulu", "mike", "delta", "alpha"]);
    }

    #[test]
    fn test_json_column_order_survives_report_serialization() {
        let file = write_file(&format!("[{UNSORTED_FIELDS}]"));
        let report = analyze_json_file(file.path(), &JsonParserConfig::default()).unwrap();

        let json = serde_json::to_string(&report).unwrap();
        let restored: Value = serde_json::from_str(&json).unwrap();
        let names: Vec<&str> = restored["column_profiles"]
            .as_array()
            .unwrap()
            .iter()
            .map(|profile| profile["name"].as_str().unwrap())
            .collect();

        assert_eq!(names, UNSORTED_ORDER);
    }

    #[test]
    fn test_analyze_json_backfills_columns_discovered_after_first_row() {
        let json = write_file(r#"[{"a":1},{"a":2,"b":3}]"#);
        let config = JsonParserConfig::default();
        let report = analyze_json_file(json.path(), &config).unwrap();
        let col_b = report
            .column_profiles
            .iter()
            .find(|profile| profile.name == "b")
            .unwrap();

        assert_eq!(col_b.total_count, 2);
        assert_eq!(col_b.null_count, 1);
        assert_eq!(col_b.unique_count, Some(1));
    }

    #[test]
    fn test_analyze_json_empty_array() {
        let json = write_file("[]");
        let config = JsonParserConfig::default();
        let report = analyze_json_file(json.path(), &config).unwrap();
        assert!(report.column_profiles.is_empty());
        // An empty dataset has nothing to assess: no score is fabricated.
        assert_eq!(report.quality_score(), None);
    }

    #[test]
    fn test_analyze_json_malformed_returns_error() {
        let json = write_file("this is entirely invalid json");
        let config = JsonParserConfig::default();
        let err = analyze_json_file(json.path(), &config)
            .expect_err("malformed JSON should return an error");

        let message = err.to_string().to_lowercase();
        assert!(message.contains("malformed") && message.contains("json"));
    }

    #[test]
    fn test_analyze_json_file_detects_format() {
        let json_array = write_file(r#"[{"x":1}]"#);
        let config = JsonParserConfig::default();
        let report = analyze_json_file(json_array.path(), &config).unwrap();
        assert!(matches!(
            report.data_source,
            DataSource::File {
                format: FileFormat::Json,
                ..
            }
        ));

        let jsonl = write_file("{\"x\":1}\n{\"x\":2}\n");
        let report = analyze_json_file(jsonl.path(), &config).unwrap();
        assert!(matches!(
            report.data_source,
            DataSource::File {
                format: FileFormat::Jsonl,
                ..
            }
        ));
    }

    #[test]
    fn test_bom_prefixed_file_preserves_source_size() {
        let data = b"\xEF\xBB\xBF[{\"x\":1}]";
        let json = write_bytes(data);
        let report = analyze_json_file(json.path(), &JsonParserConfig::json_document()).unwrap();

        assert_eq!(report.execution.rows_processed, 1);
        assert!(matches!(
            report.data_source,
            DataSource::File {
                format: FileFormat::Json,
                size_bytes,
                ..
            } if size_bytes == data.len() as u64
        ));
    }

    #[test]
    fn test_analyze_json_file_empty() {
        let json = write_file("");
        let config = JsonParserConfig::default();
        let report = analyze_json_file(json.path(), &config).unwrap();
        assert_eq!(report.execution.rows_processed, 0);
        assert!(report.column_profiles.is_empty());
    }

    #[test]
    fn test_analyze_json_boolean_and_nested() {
        let json =
            write_file(r#"[{"flag":true,"nested":{"a":1}},{"flag":false,"nested":{"b":2}}]"#);
        let config = JsonParserConfig::default();
        let report = analyze_json_file(json.path(), &config).unwrap();
        let profiles = &report.column_profiles;

        let flag = profiles
            .iter()
            .find(|profile| profile.name == "flag")
            .unwrap();
        assert_eq!(flag.total_count, 2);

        let nested = profiles
            .iter()
            .find(|profile| profile.name == "nested")
            .unwrap();
        assert_eq!(nested.total_count, 2);
    }

    #[test]
    fn test_single_root_object_compact_yields_one_row() {
        let data = br#"{"type":"FeatureCollection","features":[1,2,3]}"#;
        let cursor = Cursor::new(data.as_ref());
        let config = JsonParserConfig::default();

        let (profiles, _stats, rows, malformed, _format) =
            analyze_json_from_reader(cursor, &config).unwrap();
        assert_eq!(rows, 1);
        assert_eq!(malformed, 0);
        assert_eq!(profiles.len(), 2);

        let names: Vec<&str> = profiles
            .iter()
            .map(|profile| profile.name.as_str())
            .collect();
        assert!(names.contains(&"type"));
        assert!(names.contains(&"features"));
    }

    #[test]
    fn test_jsonl_multi_object_still_works() {
        let data = b"{\"x\":1}\n{\"x\":2}\n{\"x\":3}\n";
        let cursor = Cursor::new(data.as_ref());
        let config = JsonParserConfig::default();

        let (_profiles, _stats, rows, _malformed, format) =
            analyze_json_from_reader(cursor, &config).unwrap();
        assert_eq!(format, FileFormat::Jsonl);
        assert_eq!(rows, 3);
    }

    #[test]
    fn test_single_root_object_via_analyze_json_file() {
        let file =
            write_json_file(r#"{"type":"FeatureCollection","features":[{"id":1},{"id":2}]}"#);
        let config = JsonParserConfig::default();
        let report = analyze_json_file(file.path(), &config).unwrap();

        assert_eq!(report.execution.rows_processed, 1);
        assert_eq!(report.column_profiles.len(), 2);
    }

    #[test]
    fn test_single_root_object_pretty_printed_yields_one_row() {
        let data = br#"{
  "type": "FeatureCollection",
  "features": [
    {"id": 1},
    {"id": 2}
  ]
}"#;
        let cursor = Cursor::new(data.as_ref());
        // A reader has no file name, so the grammar cannot be inferred and is
        // named explicitly; `analyze_json_file` takes it from the extension.
        let config = JsonParserConfig::json_document();

        let (profiles, _stats, rows, malformed, format) =
            analyze_json_from_reader(cursor, &config).unwrap();
        assert_eq!(format, FileFormat::Json);
        assert_eq!(rows, 1);
        assert_eq!(malformed, 0);
        assert_eq!(profiles.len(), 2);
    }

    #[test]
    fn test_single_root_object_pretty_printed_via_analyze_json_file() {
        let file = write_json_file(
            "{\n  \"type\": \"FeatureCollection\",\n  \"features\": [\n    {\"id\": 1},\n    {\"id\": 2}\n  ]\n}\n",
        );
        let config = JsonParserConfig::default();
        let report = analyze_json_file(file.path(), &config).unwrap();

        assert_eq!(report.execution.rows_processed, 1);
        assert_eq!(report.column_profiles.len(), 2);
    }
}