qsv 16.1.0

A Blazing-Fast Data-wrangling toolkit.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
static USAGE: &str = r#"
Validates CSV data using two main modes:

JSON SCHEMA VALIDATION MODE:
===========================

This mode is invoked if a JSON Schema file (draft 2020-12) is provided.

The CSV data is validated against the JSON Schema. If the CSV data is valid, no output
files are created and the command returns an exit code of 0.

If invalid records are found, they are put into an "invalid" file, with the rest of the
records put into a "valid"" file.

A "validation-errors.tsv" report is also created with the following columns:

  * row_number: the row number of the invalid record
  * field: the field name of the invalid field
  * error: a validation error message detailing why the field is invalid

It uses the JSON Schema Validation Specification (draft 2020-12) to validate the CSV.
It validates the structure of the file, as well as the data types and domain/range of the fields.
See https://json-schema.org/draft/2020-12/json-schema-validation.html

qsv supports a custom format - `currency`. This format will only accept a valid currency, defined as:

 1. ISO Currency Symbol (optional): This is the ISO 4217 three-character code or currency symbol
    (e.g. USD, EUR, JPY, $, €, ¥, etc.)
 2. Amount: This is the numerical value of the currency. More than 2 decimal places are allowed.
 3. Formats: Valid currency formats include:
      Standard: $1,000.00 or USD1000.00
      Negative amounts: ($100.00) or -$100.00
      Different styles: 1.000,00 (used in some countries for euros)

qsv also supports two custom keywords - `dynamicEnum` and `uniqueCombinedWith`.

dynamicEnum
===========
`dynamicEnum` allows for dynamic validation against a reference CSV file.
It can be used to validate against a set of values unknown at the time of schema creation or
when the set of valid values is dynamic or too large to hardcode into the JSON Schema with `enum`.
The reference CSV file can be local or a URL (http/https, dathere & ckan schemes supported).
The "dynamicEnum" value has the form:

  // qsvlite binary variant only supports URIs which can be files on the local filesystem
  // or remote files (http and https schemes supported)
  dynamicEnum = "URI|colname" where colname is the column name or column index (0-based)

    // use data.csv from the current working directory; use the 1st column for validation
    dynamicEnum = "data.csv"

    // use data.csv in /lookup_dir directory; use the column "Agency" for validation
    dynamicEnum = "/lookupdir/data.csv|Agency"

    // get data.csv; use the 3rd column for validation (2 as the col index is 0-based)
    dynamicEnum = "https://example.com/data.csv|2"

  // on other qsv binary variants, dynamicEnum has expanded caching functionality
  dynamicEnum = "[cache_name;cache_age]|URI|colname" where cache_name and cache_age are optional

    // use data.csv from current working directory; cache it as data with a default
    // cache age of 3600 seconds i.e. the cached data.csv expires after 1 hour
    dynamicEnum = "data.csv"

    // get data.csv; cache it as custom_name, cache age 600 seconds
    dynamicEnum = "custom_name;600|https://example.com/data.csv"

    // get data.csv; cache it as data, cache age 800 seconds
    dynamicEnum = ";800|https://example.com/data.csv"

    // get the top matching result for nyc_neighborhoods (signaled by trailing ?),
    // cache it as nyc_neighborhood_data.csv (NOTE: cache name is required when using CKAN scheme)
    // with a default cache age of 3600 seconds
    // be sure to set --ckan-api, otherwise it will default to datHere's CKAN (data.dathere.com)
    dynamicEnum = "nyc_neighborhood_data|ckan:://nyc_neighborhoods?"

    // get CKAN resource with id 1234567, cache it as resname, 3600 secs cache age
    // note that if the resource is a private resource, you'll need to set --ckan-token
    dynamicEnum = "resname|ckan:://1234567"

    // same as above but with a cache age of 100 seconds; use the borough column for validation
    dynamicEnum = "resname;100|ckan:://1234567|borough

    // get us_states.csv from datHere lookup tables
    dynamicEnum = "dathere://us_states.csv"

If colname is not specified, the first column of the CSV file is read and used for validation.

uniqueCombinedWith
==================
`uniqueCombinedWith` allows you to validate that combinations of values across specified columns
are unique. It can be used with either column names or column indices (0-based). For example:

    // Validate that combinations of name and email are unique
    uniqueCombinedWith = ["name", "email"]

    // Validate that combinations of columns at indices 1 and 2 are unique
    uniqueCombinedWith = [1, 2]

    // Validate that the combinations of named and indexed columns are unique
    uniqueCombinedWith = ["name", 2]

When a duplicate combination is found, the validation will fail and the error message will indicate
which columns had duplicate combinations (named columns first, then indexed columns). The invalid
records will be written to the .invalid file, while valid records will be written to the .valid file.

`uniqueCombinedWith` complements the standard `uniqueItems` keyword, which can only validate
uniqueness across a single column.

-------------------------------------------------------

You can create a JSON Schema file from a reference CSV file using the `qsv schema` command.
Once the schema is created, you can fine-tune it to your needs and use it to validate other CSV
files that have the same structure.

Be sure to select a "training" CSV file that is representative of the data you want to validate
when creating a schema. The data types, domain/range and regular expressions inferred from the
reference CSV file should be appropriate for the data you want to validate.

Typically, after creating a schema, you should edit it to fine-tune each field's inferred
validation rules.

For example, if we created a JSON schema file called "reference.schema.json" using the `schema` command.
And want to validate "mydata.csv" which we know has validation errors, the output files from running
`qsv validate mydata.csv reference.schema.json` are:

  * mydata.csv.valid
  * mydata.csv.invalid
  * mydata.csv.validation-errors.tsv

With an exit code of 1 to indicate a validation error.

If we validate another CSV file, "mydata2.csv", which we know is valid, there are no output files,
and the exit code is 0.

If piped from stdin, the filenames will use `stdin.csv` as the base filename. For example:
  `cat mydata.csv | qsv validate reference.schema.json`

   * stdin.csv.valid
   * stdin.csv.invalid
   * stdin.csv.validation-errors.tsv


JSON SCHEMA SCHEMA VALIDATION SUBMODE:
---------------------------------------
`validate` also has a `schema` subcommand to validate JSON Schema files themselves. E.g.
     `qsv validate schema myjsonschema.json`
     // ignore format validation
     `qsv validate schema --no-format-validation myjsonschema.json`

RFC 4180 VALIDATION MODE:
========================

If run without a JSON Schema file, the CSV is validated for RFC 4180 CSV standard compliance
(see https://github.com/dathere/qsv#rfc-4180-csv-standard).

It also confirms if the CSV is UTF-8 encoded.

For both modes, returns exit code 0 when the CSV file is valid, exitcode > 0 otherwise.
If all records are valid, no output files are produced.

Examples:

  # Validate a CSV file. Use this to check if a CSV file is readable by qsv. 
  qsv validate data.csv

  # Validate a TSV file against a JSON Schema
  qsv validate data.tsv schema.json

  # Validate multiple CSV files using various dialects against a JSON Schema
  qsv validate data1.csv data2.tab data3.ssv schema.json

  # Validate all CSV files in a directory against a JSON Schema
  qsv validate /path/to/csv_directory schema.json

  # Validate CSV files listed in a '.infile-list' file against a JSON Schema
  qsv validate files.infile-list schema.json

For more examples, see the tests included in this file (denoted by '#[test]') or see
https://github.com/dathere/qsv/blob/master/tests/test_validate.rs.

Usage:
    qsv validate schema [--no-format-validation] [<json-schema>]
    qsv validate [options] [<input>...]
    qsv validate [options] [<input>] <json-schema>
    qsv validate --help

Validate arguments:
    <input>...                 Input CSV file(s) to validate. If not provided, will read from stdin.
                               If input is a directory, all files in the directory will be validated.
                               If the input is a file with a '.infile-list' extension, the file will
                               be read as a list of input files. If the input are snappy-compressed
                               files(s), it will be decompressed automatically.
                               Extended Input Support is only available for RFC 4180 validation mode.
    <json-schema>              JSON Schema file to validate against. If not provided, `validate`
                               will run in RFC 4180 validation mode. The file can be a local file
                               or a URL (http and https schemes supported).

Validate options:
    --trim                     Trim leading and trailing whitespace from fields before validating.
    --no-format-validation     Disable JSON Schema format validation. Ignores all JSON Schema
                               "format" keywords (e.g. date,email, uri, currency, etc.). This is
                               useful when you want to validate the structure of the CSV file
                               w/o worrying about the data types and domain/range of the fields.
    --fail-fast                Stops on first error.
    --valid <suffix>           Valid record output file suffix. [default: valid]
    --invalid <suffix>         Invalid record output file suffix. [default: invalid]
    --json                     When validating without a JSON Schema, return the RFC 4180 check
                               as a JSON file instead of a message.
    --pretty-json              Same as --json, but pretty printed.
    --valid-output <file>      Change validation mode behavior so if ALL rows are valid, to pass it to
                               output, return exit code 1, and set stderr to the number of valid rows.
                               Setting this will override the default behavior of creating
                               a valid file only when there are invalid records.
                               To send valid records to stdout, use `-` as the filename.
    -j, --jobs <arg>           The number of jobs to run in parallel.
                               When not set, the number of jobs is set to the
                               number of CPUs detected.
    -b, --batch <size>         The number of rows per batch to load into memory,
                               before running in parallel. Automatically determined
                               for CSV files with more than 50000 rows.
                               Set to 0 to load all rows in one batch.
                               Set to 1 to force batch optimization even for files with
                               less than 50000 rows. [default: 50000]

                               FANCY REGEX OPTIONS:
    --fancy-regex              Use the fancy regex engine instead of the default regex engine
                               for validation.
                               The fancy engine supports advanced regex features such as
                               lookaround and backreferences, but is not as performant as
                               the default regex engine which guarantees linear-time matching,
                               prevents DoS attacks, and is more efficient for simple patterns.
    --backtrack-limit <limit>  Set the approximate number of backtracking steps allowed.
                               This is only used when --fancy-regex is set.
                               [default: 1000000]

                               OPTIONS FOR BOTH REGEX ENGINES:
    --size-limit <mb>          Set the approximate size limit, in megabytes, of a compiled regex.
                               [default: 50]
    --dfa-size-limit <mb>      Set the approximate capacity, in megabytes, of the cache of transitions
                               used by the engine's lazy Discrete Finite Automata.
                               [default: 10]

    --timeout <seconds>        Timeout for downloading json-schemas on URLs and for
                               'dynamicEnum' lookups on URLs. If 0, no timeout is used.
                               [default: 30]
    --cache-dir <dir>          The directory to use for caching downloaded dynamicEnum resources.
                               If the directory does not exist, qsv will attempt to create it.
                               If the QSV_CACHE_DIR envvar is set, it will be used instead.
                               Not available on qsvlite.
                               [default: ~/.qsv-cache]
    --ckan-api <url>           The URL of the CKAN API to use for downloading dynamicEnum
                               resources with the "ckan://" scheme.
                               If the QSV_CKAN_API envvar is set, it will be used instead.
                               Not available on qsvlite.
                               [default: https://data.dathere.com/api/3/action]
    --ckan-token <token>       The CKAN API token to use. Only required if downloading
                               private resources.
                               If the QSV_CKAN_TOKEN envvar is set, it will be used instead.
                               Not available on qsvlite.

                                EMAIL VALIDATION OPTIONS:
    --email-required-tld        Require the email to have a valid Top-Level Domain (TLD)
                                (e.g. .com, .org, .net, etc.).
                                e.g. "john.doe@example" is VALID if this option is NOT set.
    --email-display-text        Allow display text in emails.
                                e.g. "John Doe <john.doe@example.com>" is INVALID if this option is NOT set.
    --email-min-subdomains <n>  Minimum number of subdomains required in the email.
                                e.g. "jdoe@example.com" is INVALID if this option is set to 3,
                                but "jdoe@sub.example.com" is VALID.
                                [default: 2]
    --email-domain-literal      Allow domain literals in emails.
                                e.g. "john.doe@[127.0.0.1]" is VALID if this option is set.

Common options:
    -h, --help                 Display this message
    -n, --no-headers           When set, the first row will not be interpreted
                               as headers. It will be validated with the rest
                               of the rows. Otherwise, the first row will always
                               appear as the header row in the output.
                               Note that this option is only valid when running
                               in RFC 4180 validation mode as JSON Schema validation
                               requires headers.
    -d, --delimiter <arg>      The field delimiter for reading CSV data.
                               Must be a single character.
    -p, --progressbar          Show progress bars. Not valid for stdin.
    -q, --quiet                Do not display validation summary message.
"#;

use std::{
    env,
    fs::File,
    io::{BufReader, BufWriter, Read, Write},
    path::PathBuf,
    str,
    sync::{
        OnceLock,
        atomic::{AtomicU16, Ordering},
    },
};

use bitvec::prelude::*;
use csv::ByteRecord;
use foldhash::{HashSet, HashSetExt};
use indicatif::HumanCount;
#[cfg(any(feature = "feature_capable", feature = "lite"))]
use indicatif::{ProgressBar, ProgressDrawTarget};
use jsonschema::{
    EmailOptions, Keyword, PatternOptions, ValidationError, Validator, paths::Location,
};
use log::debug;
use qsv_currency::Currency;
use rayon::{
    iter::{IndexedParallelIterator, ParallelIterator},
    prelude::IntoParallelRefIterator,
};
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value, json, value::Number};
#[cfg(feature = "lite")]
use tempfile::NamedTempFile;

#[cfg(not(feature = "lite"))]
use crate::lookup;
#[cfg(not(feature = "lite"))]
use crate::lookup::{LookupTableOptions, load_lookup_table};
use crate::{
    CliError, CliResult,
    config::{Config, DEFAULT_RDR_BUFFER_CAPACITY, DEFAULT_WTR_BUFFER_CAPACITY, Delimiter},
    util,
};

// to save on repeated init/allocs
static NULL_TYPE: OnceLock<Value> = OnceLock::new();

static TIMEOUT_SECS: AtomicU16 = AtomicU16::new(30);

#[cfg(not(feature = "lite"))]
static QSV_CACHE_DIR: OnceLock<String> = OnceLock::new();

#[cfg(not(feature = "lite"))]
static CKAN_API: OnceLock<String> = OnceLock::new();

#[cfg(not(feature = "lite"))]
static CKAN_TOKEN: OnceLock<Option<String>> = OnceLock::new();
static DELIMITER: OnceLock<Option<Delimiter>> = OnceLock::new();

/// write to stderr and log::error, using ValidationError
macro_rules! fail_validation_error {
    ($($t:tt)*) => {{
        use log::error;
        let err = format!($($t)*);
        error!("{err}");
        Err(ValidationError::custom(err))
    }};
}

#[derive(Deserialize)]
#[allow(dead_code)]
struct Args {
    cmd_schema:                bool,
    flag_trim:                 bool,
    flag_no_format_validation: bool,
    flag_fail_fast:            bool,
    flag_valid:                Option<String>,
    flag_invalid:              Option<String>,
    flag_json:                 bool,
    flag_pretty_json:          bool,
    flag_valid_output:         Option<String>,
    flag_jobs:                 Option<usize>,
    flag_batch:                usize,
    flag_no_headers:           bool,
    flag_delimiter:            Option<Delimiter>,
    flag_progressbar:          bool,
    flag_quiet:                bool,
    arg_input:                 Vec<std::path::PathBuf>,
    arg_json_schema:           Option<String>,
    flag_fancy_regex:          bool,
    flag_backtrack_limit:      usize,
    flag_size_limit:           usize,
    flag_dfa_size_limit:       usize,
    flag_timeout:              u16,
    flag_cache_dir:            String,
    flag_ckan_api:             String,
    flag_ckan_token:           Option<String>,
    flag_email_required_tld:   bool,
    flag_email_display_text:   bool,
    flag_email_min_subdomains: usize,
    flag_email_domain_literal: bool,
}

enum JSONtypes {
    String,
    Number,
    Integer,
    Boolean,
    Unsupported,
}

#[derive(Serialize, Deserialize)]
struct RFC4180Struct {
    delimiter_char: char,
    header_row:     bool,
    quote_char:     char,
    num_records:    u64,
    num_fields:     u64,
    fields:         Vec<String>,
}

impl From<ValidationError<'_>> for CliError {
    fn from(err: ValidationError) -> CliError {
        CliError::Other(format!("{err}"))
    }
}

#[inline]
/// Checks if a given string represents a valid currency format.
fn currency_format_checker(s: &str) -> bool {
    Currency::from_str(s).is_ok_and(|c| {
        if c.symbol().is_empty() {
            true // allow empty currency symbol
        } else {
            qsv_currency::Currency::is_iso_currency(&c)
        }
    })
}

struct DynEnumValidator {
    dynenum_set: HashSet<String>,
}

impl DynEnumValidator {
    #[allow(dead_code)]
    const fn new(dynenum_set: HashSet<String>) -> Self {
        Self { dynenum_set }
    }
}

impl Keyword for DynEnumValidator {
    #[inline]
    fn validate<'instance>(
        &self,
        instance: &'instance Value,
    ) -> Result<(), ValidationError<'instance>> {
        if self.dynenum_set.contains(instance.as_str().unwrap()) {
            Ok(())
        } else {
            let error =
                ValidationError::custom(format!("{instance} is not a valid dynamicEnum value"));
            Err(error)
        }
    }

    #[inline]
    fn is_valid(&self, instance: &Value) -> bool {
        if let Value::String(s) = instance {
            self.dynenum_set.contains(s)
        } else {
            false
        }
    }
}

struct UniqueCombinedWithValidator {
    column_names:      Vec<String>,
    column_indices:    Vec<usize>,
    seen_combinations: std::sync::RwLock<HashSet<String>>,
}

impl UniqueCombinedWithValidator {
    fn new(column_names: Vec<String>, column_indices: Vec<usize>) -> Self {
        Self {
            column_names,
            column_indices,
            seen_combinations: std::sync::RwLock::new(HashSet::new()),
        }
    }
}

impl Keyword for UniqueCombinedWithValidator {
    fn validate<'instance>(
        &self,
        instance: &'instance Value,
    ) -> Result<(), ValidationError<'instance>> {
        let obj = instance
            .as_object()
            .ok_or_else(|| ValidationError::custom("Instance must be an object"))?;

        let mut values = Vec::with_capacity(self.column_names.len() + self.column_indices.len());

        // Get values from column names
        for name in &self.column_names {
            if let Some(value) = obj.get(name) {
                values.push(value.to_string());
            }
        }

        // Get values from column indices by converting to array first
        if !self.column_indices.is_empty() {
            let array: Vec<_> = obj.values().collect();
            for &idx in &self.column_indices {
                if let Some(value) = array.get(idx) {
                    values.push(value.to_string());
                }
            }
        }

        let combination = values.join("|");
        let mut seen = self.seen_combinations.write().unwrap();

        if seen.contains(&combination) {
            let mut column_desc_parts =
                Vec::with_capacity(self.column_names.len() + self.column_indices.len());

            // Add named columns
            if !self.column_names.is_empty() {
                column_desc_parts.extend(self.column_names.iter().cloned());
            }

            // Add indexed columns
            if !self.column_indices.is_empty() {
                column_desc_parts.extend(
                    self.column_indices
                        .iter()
                        .map(std::string::ToString::to_string),
                );
            }

            let column_desc = column_desc_parts.join(", ");
            return Err(ValidationError::custom(format!(
                "Combination of values for columns {column_desc} is not unique"
            )));
        }

        seen.insert(combination);
        drop(seen);
        Ok(())
    }

    fn is_valid(&self, instance: &Value) -> bool {
        let Some(obj) = instance.as_object() else {
            return false;
        };

        let mut values = Vec::with_capacity(self.column_names.len() + self.column_indices.len());

        // Get values from column names
        for name in &self.column_names {
            if let Some(value) = obj.get(name) {
                values.push(value.to_string());
            }
        }

        // Get values from column indices by converting to array first
        if !self.column_indices.is_empty() {
            let array: Vec<_> = obj.values().collect();
            for &idx in &self.column_indices {
                if let Some(value) = array.get(idx) {
                    values.push(value.to_string());
                }
            }
        }

        let combination = values.join("|");
        let seen = self.seen_combinations.read().unwrap();
        !seen.contains(&combination)
    }
}

#[allow(clippy::result_large_err)]
fn unique_combined_with_validator_factory<'a>(
    _parent: &'a Map<String, Value>,
    value: &'a Value,
    _location: Location,
) -> Result<Box<dyn Keyword>, ValidationError<'a>> {
    // Get the array of column names/indices
    let columns = value.as_array().ok_or_else(|| {
        ValidationError::custom("'uniqueCombinedWith' must be an array of column names or indices")
    })?;

    let col_len = columns.len();
    let mut column_names = Vec::with_capacity(col_len);
    let mut column_indices = Vec::with_capacity(col_len);

    // Convert each column name/index to appropriate type
    for col in columns {
        // Try parsing as index first
        if let Some(idx) = col.as_u64() {
            column_indices.push(idx as usize);
        } else {
            // Try as string
            let name = col.as_str().ok_or_else(|| {
                ValidationError::custom("Column names must be strings or numbers")
            })?;
            column_names.push(name.to_string());
        }
    }

    // Validate that we have at least one column
    if column_names.is_empty() && column_indices.is_empty() {
        return Err(ValidationError::custom(
            "'uniqueCombinedWith' must specify at least one column",
        ));
    }

    Ok(Box::new(UniqueCombinedWithValidator::new(
        column_names,
        column_indices,
    )))
}

/// Parse the dynamicEnum URI string to extract cache_name, final_uri, cache_age and column
/// Format: "[cache_name;cache_age]|URL[|column]" where cache_name, cache_age and column are
/// optional
///
/// # Arguments
/// * `uri` - The dynamicEnum URI string to parse
///
/// # uri parsing examples:
/// lookup.csv
///    - cache_name: lookup, final_uri: lookup.csv, cache_age: 3600, column: None
///
/// lookup.csv|name
///    - cache_name: lookup, final_uri: lookup.csv, cache_age: 3600, column: Some(name)
///
/// lookup_name;600|lookup.csv
///    - cache_name: lookup_name, final_uri: lookup.csv, cache_age: 600, column: None
///
/// remote_lookup|https://example.com/remote.csv|col1
///    - cache_name: remote_lookup, final_uri: https://example.com/remote.csv, cache_age: 3600,
///      column: Some(col1)
///
/// https://example.com/remote.csv
///    - cache_name: remote, final_uri: https://example.com/remote.csv, cache_age: 3600, column:
///      None
///
/// # Returns
/// * `(String, String, i64, Option<String>)` - Tuple containing:
///   - cache_name: Name to use for caching the lookup table
///   - final_uri: The actual URI/URL to load the lookup table from
///   - cache_age: How long to cache the lookup table in seconds
///   - column: Optional column name/index to use from the lookup table
#[cfg(not(feature = "lite"))]
fn parse_dynenum_uri(uri: &str) -> (String, String, i64, Option<String>) {
    const DEFAULT_CACHE_AGE_SECS: i64 = 3600; // 1 hour

    // Extract cache name from URI (handles both URLs and local files)
    fn get_cache_name(uri: &str) -> String {
        // For URIs with schemes (http://, dathere://, ckan://, etc.)
        if uri.contains("://") {
            // Split on "://" and take everything after it
            let after_scheme = uri.split("://").nth(1).unwrap_or(uri);
            // Then take the last part of the path and remove .csv
            after_scheme
                .split('/')
                .next_back()
                .unwrap_or(after_scheme)
                .trim_end_matches(".csv")
                .to_string()
        } else {
            // For regular paths, split on both / and \ and take the last part
            uri.split(['/', '\\'])
                .next_back()
                .unwrap_or(uri)
                .trim_end_matches(".csv")
                .to_string()
        }
    }

    // Handle simple URL case with no pipe separators
    if !uri.contains('|') {
        let final_uri = uri.to_string();
        let cache_name = get_cache_name(&final_uri);
        return (cache_name, final_uri, DEFAULT_CACHE_AGE_SECS, None);
    }

    // Split the URI into parts
    let parts: Vec<&str> = uri.split('|').collect();

    // Get the final URI and handle cache configuration
    let (final_uri, cache_name, cache_age) = if parts[0].contains(';') {
        // Has cache config: "name;age|uri"
        let config_parts: Vec<&str> = parts[0].split(';').collect();
        let name = if config_parts[0].is_empty() {
            get_cache_name(parts[1])
        } else {
            config_parts[0].trim_end_matches(".csv").to_string()
        };
        let age = config_parts
            .get(1)
            .and_then(|s| s.parse::<i64>().ok())
            .unwrap_or(DEFAULT_CACHE_AGE_SECS);
        (parts[1].to_string(), name, age)
    } else if parts[1].contains("://") {
        // Has URL/scheme: "name|scheme://uri"
        (
            parts[1].to_string(),
            get_cache_name(parts[0]),
            DEFAULT_CACHE_AGE_SECS,
        )
    } else {
        // Simple case: "uri|column"
        (
            parts[0].to_string(),
            get_cache_name(parts[0]),
            DEFAULT_CACHE_AGE_SECS,
        )
    };

    // Extract column if present (last part if it's not the URI)
    let column = if parts.len() > 2 {
        Some(parts[2].to_string())
    } else if parts.len() == 2
        && !parts[1].contains("://")
        && !parts[1].to_lowercase().ends_with(".csv")
    {
        Some(parts[1].to_string())
    } else {
        None
    };

    (cache_name, final_uri, cache_age, column)
}

#[cfg(not(feature = "lite"))]
#[test]
fn test_parse_dynenum_uri() {
    // Test simple URL with no pipe separators
    let (cache_name, uri, cache_age, column) = parse_dynenum_uri("https://example.com/data.csv");
    assert_eq!(cache_name, "data");
    assert_eq!(uri, "https://example.com/data.csv");
    assert_eq!(cache_age, 3600);
    assert_eq!(column, None);

    // Test with custom cache name and age
    let (cache_name, uri, cache_age, column) =
        parse_dynenum_uri("custom_name;600|https://example.com/data.csv");
    assert_eq!(cache_name, "custom_name");
    assert_eq!(uri, "https://example.com/data.csv");
    assert_eq!(cache_age, 600);
    assert_eq!(column, None);

    // Test with column name
    let (cache_name, uri, cache_age, column) = parse_dynenum_uri("lookup.csv|name");
    assert_eq!(cache_name, "lookup");
    assert_eq!(uri, "lookup.csv");
    assert_eq!(cache_age, 3600);
    assert_eq!(column, Some("name".to_string()));

    // Test with cache config and column
    let (cache_name, uri, cache_age, column) = parse_dynenum_uri("MyCache;1800|lookup.csv|code");
    assert_eq!(cache_name, "MyCache");
    assert_eq!(uri, "lookup.csv");
    assert_eq!(cache_age, 1800);
    assert_eq!(column, Some("code".to_string()));

    // Test empty cache name with age and column
    let (cache_name, uri, cache_age, column) = parse_dynenum_uri(";1800|lookup.csv|code");
    assert_eq!(cache_name, "lookup");
    assert_eq!(uri, "lookup.csv");
    assert_eq!(cache_age, 1800);
    assert_eq!(column, Some("code".to_string()));

    // Test empty cache name with age but no column
    let (cache_name, uri, cache_age, column) = parse_dynenum_uri(";1800|lookup.csv");
    assert_eq!(cache_name, "lookup");
    assert_eq!(uri, "lookup.csv");
    assert_eq!(cache_age, 1800);
    assert_eq!(column, None);

    // Test simple local file path
    let (cache_name, uri, cache_age, column) = parse_dynenum_uri("lookup.csv");
    assert_eq!(cache_name, "lookup");
    assert_eq!(uri, "lookup.csv");
    assert_eq!(cache_age, 3600);
    assert_eq!(column, None);

    // Test simple fully qualified local file path in Windows
    let (cache_name, uri, cache_age, column) = parse_dynenum_uri(r#"c:\Users\jdoe\lookup.csv"#);
    assert_eq!(cache_name, "lookup");
    assert_eq!(uri, r#"c:\Users\jdoe\lookup.csv"#);
    assert_eq!(cache_age, 3600);
    assert_eq!(column, None);

    // Test simple local file path on *nix filesystem, with column
    let (cache_name, uri, cache_age, column) = parse_dynenum_uri("/tmp/lookup.csv|first_col");
    assert_eq!(cache_name, "lookup");
    assert_eq!(uri, "/tmp/lookup.csv");
    assert_eq!(cache_age, 3600);
    assert_eq!(column, Some("first_col".to_string()));

    // Test case-insensitive cache name generation
    let (cache_name, uri, cache_age, column) = parse_dynenum_uri("LookUp.csv");
    assert_eq!(cache_name, "LookUp");
    assert_eq!(uri, "LookUp.csv");
    assert_eq!(cache_age, 3600);
    assert_eq!(column, None);

    // Test CKAN URL with custom cache name
    let (cache_name, uri, cache_age, column) =
        parse_dynenum_uri("NYC_neighborhood_data|ckan://nyc_neighborhoods?");
    assert_eq!(cache_name, "NYC_neighborhood_data");
    assert_eq!(uri, "ckan://nyc_neighborhoods?");
    assert_eq!(cache_age, 3600);
    assert_eq!(column, None);

    // Test CKAN URL with custom cache name and age
    let (cache_name, uri, cache_age, column) =
        parse_dynenum_uri("NYC_neighborhood_data;5000|ckan://nyc_neighborhoods?");
    assert_eq!(cache_name, "NYC_neighborhood_data");
    assert_eq!(uri, "ckan://nyc_neighborhoods?");
    assert_eq!(cache_age, 5000);
    assert_eq!(column, None);

    // Test CKAN URL with custom cache name, age and column
    let (cache_name, uri, cache_age, column) =
        parse_dynenum_uri("NYC_neighborhood_data;5000|ckan://nyc_neighborhoods?|Neighborhood_Col");
    assert_eq!(cache_name, "NYC_neighborhood_data");
    assert_eq!(uri, "ckan://nyc_neighborhoods?");
    assert_eq!(cache_age, 5000);
    assert_eq!(column, Some("Neighborhood_Col".to_string()));

    // Test dathere URL with no options
    let (cache_name, uri, cache_age, column) = parse_dynenum_uri("dathere://us_states.csv");
    assert_eq!(cache_name, "us_states");
    assert_eq!(uri, "dathere://us_states.csv");
    assert_eq!(cache_age, 3600);
    assert_eq!(column, None);

    // Test dathere URL with column
    let (cache_name, uri, cache_age, column) =
        parse_dynenum_uri("dathere://us_states.csv|state_col");
    assert_eq!(cache_name, "us_states");
    assert_eq!(uri, "dathere://us_states.csv");
    assert_eq!(cache_age, 3600);
    assert_eq!(column, Some("state_col".to_string()));

    // Test dathere URL with custom cache name, age and column
    let (cache_name, uri, cache_age, column) =
        parse_dynenum_uri("usl_lookup;6000|dathere://us_states.csv|state_col");
    assert_eq!(cache_name, "usl_lookup");
    assert_eq!(uri, "dathere://us_states.csv");
    assert_eq!(cache_age, 6000);
    assert_eq!(column, Some("state_col".to_string()));
}

/// Factory function that creates a DynEnumValidator for validating against dynamic enums loaded
/// from CSV files.
///
/// This function takes a CSV file path or URL and loads its first column into a HashSet to validate
/// against. The CSV can be loaded from:
/// - Local filesystem
/// - HTTP/HTTPS URLs
/// - CKAN resources (requires --ckan-api and optionally --ckan-token)
/// - datHere lookup tables
///
/// The dynamicEnum value format is: "[cache_name;cache_age]|URL" where cache_name and cache_age are
/// optional. Examples:
/// - "https://example.com/data.csv" - Cache as data.csv with 1 hour default cache
/// - "custom_name;600|https://example.com/data.csv" - Cache as custom_name.csv for 600 seconds
/// - "resname|ckan://1234567" - Get CKAN resource ID 1234567, cache as resname.csv
///
/// # Arguments
/// * `_parent` - Parent JSON Schema object (unused)
/// * `value` - The dynamicEnum value string specifying the CSV source
/// * `location` - Location in the schema for error reporting
///
/// # Returns
/// * `Ok(Box<DynEnumValidator>)` - Validator initialized with values from first CSV column
/// * `Err(ValidationError)` - If loading/parsing CSV fails or value is not a string
#[cfg(not(feature = "lite"))]
#[allow(clippy::result_large_err)]
fn dyn_enum_validator_factory<'a>(
    _parent: &'a Map<String, Value>,
    value: &'a Value,
    _location: Location,
) -> Result<Box<dyn Keyword>, ValidationError<'a>> {
    let uri = value.as_str().ok_or_else(|| {
        ValidationError::custom(
            "'dynamicEnum' must be set to a CSV file on the local filesystem or on a URL.",
        )
    })?;

    let (lookup_name, final_uri, cache_age_secs, column) = parse_dynenum_uri(uri);

    // Create lookup table options
    let opts = LookupTableOptions {
        name: lookup_name,
        uri: final_uri,
        cache_age_secs,
        cache_dir: QSV_CACHE_DIR.get().unwrap().to_string(),
        delimiter: DELIMITER.get().copied().flatten(),
        ckan_api_url: CKAN_API.get().cloned(),
        ckan_token: CKAN_TOKEN.get().and_then(std::clone::Clone::clone),
        timeout_secs: TIMEOUT_SECS.load(Ordering::Relaxed),
    };

    // Load the lookup table
    let lookup_result = match load_lookup_table(&opts) {
        Ok(result) => result,
        Err(e) => return fail_validation_error!("Error loading dynamicEnum lookup table: {e}"),
    };

    // Read the specified column into a HashSet
    let mut enum_set = HashSet::with_capacity(lookup_result.headers.len());
    let rconfig = Config::new(Some(lookup_result.filepath).as_ref());
    let mut rdr = match rconfig
        .flexible(true)
        .comment(Some(b'#'))
        .skip_format_check(true)
        .reader()
    {
        Ok(reader) => reader,
        Err(e) => return fail_validation_error!("Error opening dynamicEnum file: {e}"),
    };

    // Get column index based on name or default to first column
    let column_idx = if let Some(col_name) = column {
        // Try parsing as index first
        if let Ok(idx) = col_name.parse::<usize>() {
            idx
        } else {
            // Try finding column by name
            match rdr.headers() {
                Ok(headers) => {
                    let idx = headers.iter().position(|h| h == col_name);
                    match idx {
                        Some(i) => i,
                        None => {
                            return fail_validation_error!(
                                "Column '{}' not found in lookup table",
                                col_name
                            );
                        },
                    }
                },
                Err(e) => return fail_validation_error!("Error reading headers: {e}"),
            }
        }
    } else {
        0
    };

    for result in rdr.records() {
        match result {
            Ok(record) => {
                if let Some(value) = record.get(column_idx) {
                    enum_set.insert(value.to_owned());
                }
            },
            Err(e) => return fail_validation_error!("Error reading dynamicEnum file - {e}"),
        }
    }

    Ok(Box::new(DynEnumValidator::new(enum_set)))
}

#[cfg(feature = "lite")]
#[allow(clippy::result_large_err)]
fn dyn_enum_validator_factory<'a>(
    _parent: &'a Map<String, Value>,
    value: &'a Value,
    _location: Location,
) -> Result<Box<dyn Keyword>, ValidationError<'a>> {
    if let Value::String(uri) = value {
        let temp_download = match NamedTempFile::new() {
            Ok(file) => file,
            Err(e) => return fail_validation_error!("Failed to create temporary file: {e}"),
        };

        // Split URI to get column specification
        let parts: Vec<&str> = uri.split('|').collect();
        let base_uri = parts[0];
        let column = parts.get(1).map(std::string::ToString::to_string);

        let dynenum_path = if base_uri.starts_with("http") {
            let valid_url = reqwest::Url::parse(base_uri).map_err(|e| {
                ValidationError::custom(format!("Error parsing dynamicEnum URL: {e}"))
            })?;

            // download the CSV file from the URL
            let download_timeout = TIMEOUT_SECS.load(Ordering::Relaxed);
            let future = util::download_file(
                valid_url.as_str(),
                temp_download.path().to_path_buf(),
                false,
                None,
                Some(download_timeout),
                None,
            );
            match tokio::runtime::Runtime::new() {
                Ok(runtime) => {
                    if let Err(e) = runtime.block_on(future) {
                        return fail_validation_error!("Error downloading dynamicEnum file - {e}");
                    }
                },
                Err(e) => {
                    return fail_validation_error!("Error creating Tokio runtime - {e}");
                },
            }

            temp_download.path().to_str().unwrap().to_string()
        } else {
            // its a local file
            let uri_path = std::path::Path::new(base_uri);
            let uri_exists = uri_path.exists();
            if !uri_exists {
                return fail_validation_error!("dynamicEnum file not found - {base_uri}");
            }
            uri_path.to_str().unwrap().to_string()
        };

        // read the specified column into a HashSet
        let mut enum_set = HashSet::with_capacity(50);
        let rconfig = Config::new(Some(dynenum_path).as_ref());
        let mut rdr = match rconfig
            .flexible(true)
            .comment(Some(b'#'))
            .skip_format_check(true)
            .reader()
        {
            Ok(reader) => reader,
            Err(e) => return fail_validation_error!("Error opening dynamicEnum file: {e}"),
        };

        // Get column index based on name or default to first column
        let column_idx = if let Some(col_name) = column {
            // Try parsing as index first
            if let Ok(idx) = col_name.parse::<usize>() {
                idx
            } else {
                // Try finding column by name
                match rdr.headers() {
                    Ok(headers) => headers.iter().position(|h| h == col_name).unwrap_or(0),
                    Err(_) => 0,
                }
            }
        } else {
            0
        };

        for result in rdr.records() {
            match result {
                Ok(record) => {
                    if let Some(value) = record.get(column_idx) {
                        enum_set.insert(value.to_owned());
                    }
                },
                Err(e) => return fail_validation_error!("Error reading dynamicEnum file - {e}"),
            };
        }

        Ok(Box::new(DynEnumValidator::new(enum_set)))
    } else {
        Err(ValidationError::custom(
            "'dynamicEnum' must be set to a CSV file on the local filesystem or on a URL.",
        ))
    }
}

pub fn run(argv: &[&str]) -> CliResult<()> {
    let args: Args = util::get_args(USAGE, argv)?;

    // Is the JSON Schema file valid?
    if args.cmd_schema {
        if let Some(ref schema) = args.arg_json_schema {
            let schema_json_string = load_json(schema)?;
            let schema_json = serde_json::from_str(&schema_json_string)?;
            // First, validate the JSON Schema
            if let Err(e) = jsonschema::meta::validate(&schema_json) {
                return fail_clierror!("JSON Schema Meta-Reference Error: {e}");
            }
            // Now, validate the JSON Schema formats
            let test_validator = if args.flag_no_format_validation {
                Validator::options()
                    .should_validate_formats(false)
                    .should_ignore_unknown_formats(true)
                    .build(&schema_json)
            } else {
                Validator::options()
                    .should_validate_formats(true)
                    .should_ignore_unknown_formats(false)
                    .build(&schema_json)
            };
            if let Err(e) = test_validator {
                return fail_clierror!("JSON Schema Format Validation Error: {e}");
            }
            if !args.flag_quiet {
                winfo!("Valid JSON Schema.");
            }
            return Ok(());
        }
        return fail_clierror!("No JSON Schema file supplied.");
    }

    TIMEOUT_SECS.store(
        util::timeout_secs(args.flag_timeout)? as u16,
        Ordering::Relaxed,
    );

    // Check if the last argument is a JSON schema file
    let has_json_schema = if let Some(last_input) = args.arg_input.last() {
        last_input
            .extension()
            .and_then(std::ffi::OsStr::to_str)
            .is_some_and(|ext| ext.to_lowercase() == "json")
    } else {
        false
    };

    // if no JSON Schema supplied, only let csv reader RFC4180-validate csv file
    if !has_json_schema && args.arg_json_schema.is_none() {
        // For RFC 4180 validation mode, we support Extended Input Support
        return validate_rfc4180_mode(&args);
    }

    // Extract JSON schema from input list if it's the last argument
    let (input_files, json_schema_path) = if has_json_schema {
        // safety: we know the schema is_some() because we checked above
        let schema_path = args.arg_input.last().unwrap().clone();
        let input_files = args.arg_input[..args.arg_input.len() - 1].to_vec();
        (input_files, Some(schema_path))
    } else {
        (args.arg_input.clone(), None)
    };

    // Update args.arg_json_schema if we extracted it from the input list
    let json_schema_arg = if let Some(schema_path) = &json_schema_path {
        Some(schema_path.to_string_lossy().to_string())
    } else {
        args.arg_json_schema.clone()
    };

    // JSON Schema validation only supports a single input file
    if input_files.len() > 1 {
        return fail_clierror!(
            "JSON Schema validation only supports a single input file. Use RFC 4180 validation \
             mode for multiple files."
        );
    }

    let input_path = input_files.first().ok_or_else(|| {
        if has_json_schema && args.arg_input.len() == 1 {
            CliError::Other(
                "Only a JSON Schema file was provided, but no data file to validate. Please \
                 provide a data file to validate against the schema."
                    .to_string(),
            )
        } else {
            CliError::Other("No input file provided for JSON Schema validation".to_string())
        }
    })?;

    let mut rconfig = Config::new(Some(&input_path.to_string_lossy().to_string()))
        .no_headers_flag(args.flag_no_headers)
        .set_read_buffer(if std::env::var("QSV_RDR_BUFFER_CAPACITY").is_err() {
            DEFAULT_RDR_BUFFER_CAPACITY * 10
        } else {
            DEFAULT_RDR_BUFFER_CAPACITY
        });

    if args.flag_delimiter.is_some() {
        rconfig = rconfig.delimiter(args.flag_delimiter);
    }
    DELIMITER.set(args.flag_delimiter).unwrap();

    let mut rdr = rconfig.reader()?;

    // if we're here, we're validating with a JSON Schema
    // JSONSchema validation requires headers
    if args.flag_no_headers {
        return fail_clierror!("Cannot validate CSV without headers against a JSON Schema.");
    }

    // prep progress bar
    #[cfg(any(feature = "feature_capable", feature = "lite"))]
    let progress = ProgressBar::with_draw_target(None, ProgressDrawTarget::stderr_with_hz(5));

    #[cfg(any(feature = "feature_capable", feature = "lite"))]
    let show_progress =
        (args.flag_progressbar || util::get_envvar_flag("QSV_PROGRESSBAR")) && !rconfig.is_stdin();

    // for full row count, prevent CSV reader from aborting on inconsistent column count
    rconfig = rconfig.flexible(true);
    let record_count = util::count_rows(&rconfig)?;
    rconfig = rconfig.flexible(false);

    #[cfg(any(feature = "feature_capable", feature = "lite"))]
    if show_progress {
        util::prep_progress(&progress, record_count);
    } else {
        progress.set_draw_target(ProgressDrawTarget::hidden());
    }

    let headers = rdr.byte_headers()?.clone();
    let header_len = headers.len();

    #[cfg(not(feature = "lite"))]
    let qsv_cache_dir = lookup::set_qsv_cache_dir(&args.flag_cache_dir)?;
    #[cfg(not(feature = "lite"))]
    QSV_CACHE_DIR.set(qsv_cache_dir)?;

    // check the QSV_CKAN_API environment variable
    #[cfg(not(feature = "lite"))]
    CKAN_API.set(if let Ok(api) = std::env::var("QSV_CKAN_API") {
        api
    } else {
        args.flag_ckan_api.clone()
    })?;

    // check the QSV_CKAN_TOKEN environment variable
    #[cfg(not(feature = "lite"))]
    CKAN_TOKEN
        .set(if let Ok(token) = std::env::var("QSV_CKAN_TOKEN") {
            Some(token)
        } else {
            args.flag_ckan_token.clone()
        })
        .unwrap();

    // parse and compile supplied JSON Schema
    let json_schema_path =
        json_schema_path.unwrap_or_else(|| PathBuf::from(json_schema_arg.as_ref().unwrap()));
    let (schema_json, schema_compiled, has_unique_combined): (Value, Validator, bool) =
            // safety: we know the schema is_some() because we checked above
            match load_json(&json_schema_path.to_string_lossy()) {
            Ok(s) => {
                // Check for custom formats and keywords before parsing
                let has_currency_format = s.contains(r#""format": "currency""#);
                let has_dynamic_enum = s.contains("dynamicEnum");
                let has_unique_combined = s.contains("uniqueCombinedWith");
                let has_email_format = s.contains(r#""format": "email""#);
                debug!("Custom formats/keywords: currency: {has_currency_format}, dynamicEnum: {has_dynamic_enum}");
                debug!("uniqueCombinedWith: {has_unique_combined}, email: {has_email_format}");

                // parse JSON string - use platform-appropriate JSON deserialization
                #[cfg(target_endian = "big")]
                let json_result = serde_json::from_str::<Value>(&s);
                #[cfg(target_endian = "little")]
                let json_result = {
                    let mut s_slice = s.as_bytes().to_vec();
                    simd_json::serde::from_slice::<Value>(&mut s_slice)
                };

                match json_result {
                    Ok(json) => {
                        // compile JSON Schema
                        let mut validator_options = Validator::options()
                            .should_validate_formats(!args.flag_no_format_validation);

                        // Add custom validators based on pre-checked flags
                        if has_email_format {
                            let mut email_options = EmailOptions::default();
                            if args.flag_email_required_tld {
                                email_options = email_options.with_required_tld();
                            }
                            if !args.flag_email_display_text {
                                email_options = email_options.without_display_text();
                            }
                            if args.flag_email_min_subdomains > 2 {
                                email_options = email_options.with_minimum_sub_domains(args.flag_email_min_subdomains);
                            }
                            if !args.flag_email_domain_literal {
                                email_options = email_options.without_domain_literal();
                            }
                            validator_options = validator_options.with_email_options(email_options);
                        }

                        if has_currency_format {
                            validator_options = validator_options.with_format("currency", currency_format_checker);
                        }

                        if has_dynamic_enum {
                            validator_options = validator_options.with_keyword("dynamicEnum", dyn_enum_validator_factory);
                        }

                        if has_unique_combined {
                            validator_options = validator_options.with_keyword("uniqueCombinedWith", unique_combined_with_validator_factory);
                        }

                        if args.flag_fancy_regex {
                            let fancy_regex_options = PatternOptions::fancy_regex()
                                .backtrack_limit(args.flag_backtrack_limit)
                                .size_limit(args.flag_size_limit * (1 << 20))
                                .dfa_size_limit(args.flag_dfa_size_limit * (1 << 20));
                            validator_options = validator_options.with_pattern_options(fancy_regex_options);
                        } else {
                            let regex_options = PatternOptions::regex()
                                .size_limit(args.flag_size_limit * (1 << 20))
                                .dfa_size_limit(args.flag_dfa_size_limit * (1 << 20));
                            validator_options = validator_options.with_pattern_options(regex_options);
                        }

                        match validator_options.build(&json) {
                            Ok(schema) => (json, schema, has_unique_combined),
                            Err(e) => {
                                return fail_clierror!(r#"Cannot compile JSONschema. error: {e}
Try running `qsv validate schema {}` to check the JSON Schema file."#, json_schema_path.to_string_lossy());
                            },
                        }
                    },
                    Err(e) => {
                        return fail_clierror!(r#"Unable to parse JSONschema. error: {e}
Try running `qsv validate schema {}` to check the JSON Schema file."#, json_schema_arg.as_ref().unwrap());
                    },
                }
            },
            Err(e) => {
                return fail_clierror!("Unable to retrieve JSONschema. error: {e}");
            },
        };

    if log::log_enabled!(log::Level::Debug) {
        // only log if debug is enabled
        // as it can be quite large and expensive to deserialize the schema
        debug!("schema json: {:?}", &schema_json);
    }

    // set this once, as this is used repeatedly in a hot loop
    NULL_TYPE.set(Value::String("null".to_string())).unwrap();

    // get JSON types for each column in CSV file
    let header_types = get_json_types(&headers, &schema_json)?;

    // how many rows read and processed as batches
    let mut row_number: u64 = 0;
    // how many invalid rows found
    let mut invalid_count: u64 = 0;

    // amortize memory allocation by reusing record
    let mut record = csv::ByteRecord::with_capacity(500, header_len);

    let num_jobs = util::njobs(args.flag_jobs);

    // amortize allocations
    let mut valid_flags: BitVec = BitVec::with_capacity(record_count as usize);
    let batch_size = util::optimal_batch_size(&rconfig, args.flag_batch, num_jobs);
    let mut batch = Vec::with_capacity(batch_size);
    let mut batch_validation_results: Vec<Option<String>> = Vec::with_capacity(batch_size);
    let mut validation_error_messages: Vec<String> = Vec::with_capacity(50);
    let flag_trim = args.flag_trim;
    let flag_fail_fast = args.flag_fail_fast;
    let mut itoa_buffer = itoa::Buffer::new();
    let batch_pariter_min_len = batch_size / num_jobs;

    // main loop to read CSV and construct batches for parallel processing.
    // each batch is processed via Rayon parallel iterator.
    // loop exits when batch is empty.
    'batch_loop: loop {
        for _ in 0..batch_size {
            match rdr.read_byte_record(&mut record) {
                Ok(true) => {
                    row_number += 1;
                    record.push_field(itoa_buffer.format(row_number).as_bytes());
                    if flag_trim {
                        record.trim();
                    }
                    // we use mem::take() to avoid cloning & clearing the record
                    batch.push(std::mem::take(&mut record));
                },
                Ok(false) => break, // nothing else to add to batch
                Err(e) => {
                    return fail_clierror!("Error reading row: {row_number}: {e}");
                },
            }
        }

        if batch.is_empty() {
            // break out of infinite loop when at EOF
            break 'batch_loop;
        }

        // do actual validation via Rayon parallel iterator
        // validation_results vector should have same row count and in same order as input CSV
        batch
            .par_iter()
            .with_min_len(batch_pariter_min_len)
            .map(|record| {
                // convert CSV record to JSON instance
                let json_instance = match to_json_instance(&header_types, header_len, record) {
                    Ok(obj) => obj,
                    Err(e) => {
                        // Only convert to string when we have an error
                        // safety: row number was added as last column. We can do index access, not
                        // use get(), and unwrap_unchecked safely since we know its there
                        let row_number_string = unsafe {
                            simdutf8::basic::from_utf8(&record[header_len]).unwrap_unchecked()
                        };
                        return Some(format!("{row_number_string}\t<RECORD>\t{e}"));
                    },
                };

                // validate JSON instance against JSON Schema
                // if the schema has no stateful validators (like uniqueCombinedWith),
                // and the record is valid, then short-circuit and return None
                let evaluation = if !has_unique_combined && schema_compiled.is_valid(&json_instance)
                {
                    return None;
                } else {
                    // otherwise, fully evaluate the record
                    schema_compiled.evaluate(&json_instance)
                };

                if evaluation.flag().valid {
                    None
                } else {
                    // Only convert to string when we have validation errors
                    // safety: see safety comment above
                    let row_number_string = unsafe {
                        simdutf8::basic::from_utf8(&record[header_len]).unwrap_unchecked()
                    };

                    // Collect errors into a vector
                    let errors: Vec<_> = evaluation.iter_errors().collect();

                    // Preallocate the vector with the known size
                    let mut error_messages = Vec::with_capacity(errors.len());

                    // there can be multiple validation errors for a single record,
                    // squash multiple errors into one long String with linebreaks
                    for e in errors {
                        error_messages.push(format!(
                            "{row_number_string}\t{field}\t{error}",
                            field = e.instance_location.as_str().trim_start_matches('/'),
                            error = e.error
                        ));
                    }
                    Some(error_messages.join("\n"))
                }
            })
            .collect_into_vec(&mut batch_validation_results);

        // write to validation error report, but keep Vec<bool> to gen valid/invalid files later
        // because Rayon collect() guarantees original order, we can sequentially append results
        // to vector with each batch
        let start_idx = valid_flags.len();
        valid_flags.extend(std::iter::repeat_n(true, batch_size));
        for (i, result) in batch_validation_results.iter().enumerate() {
            if let Some(validation_error_msg) = result {
                invalid_count += 1;
                // safety: we know the index is in bounds because we just extended the vector
                unsafe { valid_flags.set_unchecked(start_idx + i, false) };
                validation_error_messages.push(validation_error_msg.to_owned());
            }
        }

        #[cfg(any(feature = "feature_capable", feature = "lite"))]
        if show_progress {
            progress.inc(batch.len() as u64);
        }
        batch.clear();

        // for fail-fast, exit loop if batch has any error
        if flag_fail_fast && invalid_count > 0 {
            break 'batch_loop;
        }
    } // end batch loop

    #[cfg(any(feature = "feature_capable", feature = "lite"))]
    if show_progress {
        progress.set_message(format!(
            " validated {} records.",
            HumanCount(progress.length().unwrap())
        ));
        util::finish_progress(&progress);
    }

    if invalid_count == 0 {
        // no invalid records found
        // see if we need to pass all valid records to output
        if let Some(valid_output) = args.flag_valid_output {
            // pass all valid records to output and return exit code 1
            let valid_path = if valid_output == "-" {
                // write to stdout
                None
            } else {
                Some(valid_output)
            };

            let mut valid_wtr = Config::new(valid_path.as_ref()).writer()?;
            valid_wtr.write_byte_record(&headers)?;

            let mut rdr = rconfig.reader()?;
            let mut record = csv::ByteRecord::new();
            while rdr.read_byte_record(&mut record)? {
                valid_wtr.write_byte_record(&record)?;
            }
            valid_wtr.flush()?;
            // return 1 as an exitcode and the number of valid rows to stderr
            return fail_clierror!("{row_number}");
        }
    } else {
        // there are invalid records. write out invalid/valid/errors output files.
        // if 100% invalid, valid file isn't needed, but this is rare so OK creating empty file.
        woutinfo!("Writing invalid/valid/error files...");

        let input_path = args.arg_input.first().map_or_else(
            || "stdin.csv".to_string(),
            |p| p.to_string_lossy().to_string(),
        );

        write_error_report(&input_path, validation_error_messages)?;

        let valid_suffix = args.flag_valid.unwrap_or_else(|| "valid".to_string());
        let invalid_suffix = args.flag_invalid.unwrap_or_else(|| "invalid".to_string());

        split_invalid_records(
            &rconfig,
            &valid_flags[..],
            &headers,
            &input_path,
            &valid_suffix,
            &invalid_suffix,
        )?;

        // done with validation; print output
        let fail_fast_msg = if args.flag_fail_fast {
            format!(
                "fail-fast enabled. stopped after row {}.\n",
                HumanCount(row_number)
            )
        } else {
            String::new()
        };

        return fail_clierror!(
            "{fail_fast_msg}{} out of {} records invalid.",
            HumanCount(invalid_count),
            HumanCount(row_number)
        );
    }

    if !args.flag_quiet {
        winfo!("All {} records valid.", HumanCount(row_number));
    }
    Ok(())
}

/// Validate multiple files in RFC 4180 mode with Extended Input Support
fn validate_rfc4180_mode(args: &Args) -> CliResult<()> {
    use tempfile::tempdir;

    let tmpdir = tempdir()?;
    let processed_inputs = util::process_input(args.arg_input.clone(), &tmpdir, "")?;
    let input_count = processed_inputs.len();

    let flag_json = args.flag_json || args.flag_pretty_json;
    let flag_pretty_json = args.flag_pretty_json;

    let mut all_valid = true;
    let mut total_files = 0;
    let mut valid_files = 0;

    for input_path in processed_inputs {
        total_files += 1;

        if !args.flag_quiet && input_count > 1 {
            woutinfo!("Validating: {}", input_path.display());
        }

        let mut rconfig = Config::new(Some(&input_path.to_string_lossy().to_string()))
            .no_headers_flag(args.flag_no_headers)
            .set_read_buffer(if std::env::var("QSV_RDR_BUFFER_CAPACITY").is_err() {
                DEFAULT_RDR_BUFFER_CAPACITY * 10
            } else {
                DEFAULT_RDR_BUFFER_CAPACITY
            });

        if args.flag_delimiter.is_some() {
            rconfig = rconfig.delimiter(args.flag_delimiter);
        }

        let mut rdr = match rconfig.reader() {
            Ok(reader) => reader,
            Err(e) => {
                if flag_json {
                    let file_error = json!({
                        "errors": [{
                            "title": "File validation error",
                            "detail": format!("Cannot read file {}: {}", input_path.display(), e),
                            "meta": {
                                "file": input_path.to_string_lossy()
                            }
                        }]
                    });
                    let json_error = if flag_pretty_json {
                        // safety: we know file_error is valid JSON
                        simd_json::to_string_pretty(&file_error).unwrap()
                    } else {
                        file_error.to_string()
                    };
                    return fail_clierror!("{json_error}");
                }
                return fail_clierror!("Cannot read file {}: {}", input_path.display(), e);
            },
        };

        // Validate the file
        let validation_result = validate_single_file_rfc4180(
            &mut rdr,
            &rconfig,
            flag_json,
            flag_pretty_json,
            args.flag_quiet,
        );

        match validation_result {
            Ok(()) => {
                valid_files += 1;
            },
            Err(e) => {
                all_valid = false;
                if !args.flag_quiet && input_count > 1 {
                    woutinfo!("❌ {}: {}", input_path.display(), e);
                }
                // For single files, return the error directly to maintain backward compatibility
                if input_count == 1 {
                    return Err(e);
                }
            },
        }
    }

    // Summary
    if !args.flag_quiet && input_count > 1 {
        if all_valid {
            winfo!("✅ All {} files are valid.", total_files);
        } else {
            winfo!(
                "❌ {} out of {} files are invalid.",
                total_files - valid_files,
                total_files
            );
        }
    }

    if all_valid {
        Ok(())
    } else if input_count > 1 {
        fail_clierror!(
            "{} out of {} files failed validation",
            total_files - valid_files,
            total_files
        )
    } else {
        // For single files, just return the error without the summary message
        Err(CliError::Other("Validation failed".to_string()))
    }
}

/// Validate a single file in RFC 4180 mode
fn validate_single_file_rfc4180(
    rdr: &mut csv::Reader<Box<dyn std::io::Read + Send + 'static>>,
    rconfig: &Config,
    flag_json: bool,
    flag_pretty_json: bool,
    quiet: bool,
) -> CliResult<()> {
    // first, let's validate the header row
    let mut header_msg = String::new();
    let mut header_len = 0_usize;
    let mut field_vec: Vec<String> = Vec::new();
    if !rconfig.no_headers {
        let fields_result = rdr.headers();
        match fields_result {
            Ok(fields) => {
                header_len = fields.len();
                field_vec.reserve(header_len);
                for field in fields {
                    field_vec.push(field.to_string());
                }
                let field_list = field_vec.join(r#"", ""#);
                header_msg = format!(
                    "{} Columns: (\"{field_list}\");",
                    HumanCount(header_len as u64)
                );
            },
            Err(e) => {
                // we're returning a JSON error for the header,
                // so we have more machine-friendly details
                if flag_json {
                    // there's a UTF-8 error, so we report utf8 error metadata
                    if let csv::ErrorKind::Utf8 { pos, err } = e.kind() {
                        let header_error = json!({
                            "errors": [{
                                "title" : "Header UTF-8 validation error",
                                "detail" : format!("{e}"),
                                "meta": {
                                    "record_position": format!("{pos:?}"),
                                    "record_error": format!("{err}"),
                                }
                            }]
                        });
                        let json_error = if flag_pretty_json {
                            // safety: we know header_error is valid JSON
                            simd_json::to_string_pretty(&header_error).unwrap()
                        } else {
                            header_error.to_string()
                        };

                        return fail_encoding_clierror!("{json_error}");
                    }
                    // it's not a UTF-8 error, so we report a generic
                    // header validation error
                    let header_error = json!({
                        "errors": [{
                            "title" : "Header Validation error",
                            "detail" : format!("{e}"),
                        }]
                    });
                    let json_error = if flag_pretty_json {
                        // safety: we know header_error is valid JSON
                        simd_json::to_string_pretty(&header_error).unwrap()
                    } else {
                        header_error.to_string()
                    };
                    return fail_encoding_clierror!("{json_error}");
                }
                // we're not returning a JSON error, so we can use
                // a user-friendly error message with suggestions
                if let csv::ErrorKind::Utf8 { pos, err } = e.kind() {
                    return fail_encoding_clierror!(
                        "non-utf8 sequence detected in header, position {pos:?}.\n{err}\nUse `qsv \
                         input` to fix formatting and to handle non-utf8 sequences.\n
                         Alternatively, transcode your data to UTF-8 first using `iconv` or \
                         `recode`."
                    );
                }
                // its not a UTF-8 error, report a generic header validation error
                return fail_clierror!("Header Validation error: {e}.");
            },
        }
    }

    // Now, let's validate the rest of the records the fastest way possible.
    // We do this by using csv::ByteRecord, which does not validate utf8
    // making for higher throughput and lower memory usage compared to csv::StringRecord
    // which validates each field SEPARATELY as a utf8 string.
    // Combined with simdutf8::basic::from_utf8(), we utf8-validate the entire record in one go
    // as a slice of bytes, this approach is much faster than csv::StringRecord's
    // per-field validation.
    let mut record = csv::ByteRecord::with_capacity(500, header_len);
    let mut result;
    let mut record_idx: u64 = 0;

    'rfc4180_check: loop {
        result = rdr.read_byte_record(&mut record);
        if let Err(e) = result {
            // read_byte_record() does not validate utf8, so we know this is not a utf8 error
            if flag_json {
                // we're returning a JSON error, so we have more machine-friendly details
                // using the JSON API error format

                let validation_error = json!({
                    "errors": [{
                        "title" : "Validation error",
                        "detail" : format!("{e}"),
                        "meta": {
                            "last_valid_record": format!("{record_idx}"),
                        }
                    }]
                });

                let json_error = if flag_pretty_json {
                    // safety: we know validation_error is valid JSON
                    simd_json::to_string_pretty(&validation_error).unwrap()
                } else {
                    validation_error.to_string()
                };

                return fail!(json_error);
            }

            // we're not returning a JSON error, so we can use a
            // user-friendly error message with a fixlengths suggestion
            if let csv::ErrorKind::UnequalLengths {
                expected_len: _,
                len: _,
                pos: _,
            } = e.kind()
            {
                return fail_clierror!(
                    "Validation error: {e}.\nUse `qsv fixlengths` to fix record length issues."
                );
            }
            return fail_clierror!("Validation error: {e}.\nLast valid record: {record_idx}");
        }

        // use SIMD accelerated UTF-8 validation, validate the entire record in one go
        if simdutf8::basic::from_utf8(record.as_slice()).is_err() {
            // there's a UTF-8 error, so we report utf8 error metadata
            if flag_json {
                let validation_error = json!({
                    "errors": [{
                        "title" : "UTF-8 validation error",
                        "detail" : "Cannot parse CSV record as UTF-8",
                        "meta": {
                            "last_valid_record": format!("{record_idx}"),
                            "invalid_record": format!("{record:?}"),
                        }
                    }]
                });

                let json_error = if flag_pretty_json {
                    // safety: we know validation_error is valid JSON
                    simd_json::to_string_pretty(&validation_error).unwrap()
                } else {
                    validation_error.to_string()
                };
                return fail_encoding_clierror!("{json_error}");
            }
            // we're not returning a JSON error, so we can use a
            // user-friendly error message with utf8 transcoding suggestions
            return fail_encoding_clierror!(
                r#"non-utf8 sequence at record {record_idx}.
Invalid record: {record:?}
Use `qsv input` to fix formatting and to handle non-utf8 sequences.
Alternatively, transcode your data to UTF-8 first using `iconv` or `recode`."#
            );
        }

        if result.is_ok_and(|more_data| !more_data) {
            // we've read the CSV to the end, so break out of loop
            break 'rfc4180_check;
        }
        record_idx += 1;
    } // end rfc4180_check loop

    // if we're here, we know the CSV is valid
    let msg = if flag_json {
        let rfc4180 = RFC4180Struct {
            delimiter_char: rconfig.get_delimiter() as char,
            header_row:     !rconfig.no_headers,
            quote_char:     rconfig.quote as char,
            num_records:    record_idx,
            num_fields:     header_len as u64,
            fields:         field_vec,
        };

        if flag_pretty_json {
            // safety: we know rfc4180 is populated and serializable as JSON
            simd_json::to_string_pretty(&rfc4180).unwrap()
        } else {
            // safety: we know rfc4180 is populated and serializable as JSON
            simd_json::to_string(&rfc4180).unwrap()
        }
    } else {
        let delim_display = if rconfig.get_delimiter() == b'\t' {
            "TAB".to_string()
        } else {
            (rconfig.get_delimiter() as char).to_string()
        };
        format!(
            "Valid: {header_msg} Records: {}; Delimiter: {delim_display}",
            HumanCount(record_idx)
        )
    };
    if !quiet {
        woutinfo!("{msg}");
    }

    Ok(())
}

fn split_invalid_records(
    rconfig: &Config,
    valid_flags: &BitSlice,
    headers: &ByteRecord,
    input_path: &str,
    valid_suffix: &str,
    invalid_suffix: &str,
) -> CliResult<()> {
    // track how many rows read for splitting into valid/invalid
    // should not exceed row_number when aborted early due to fail-fast
    let mut split_row_num: usize = 0;

    // prepare output writers
    let mut valid_wtr =
        Config::new(Some(input_path.to_owned() + "." + valid_suffix).as_ref()).writer()?;
    valid_wtr.write_byte_record(headers)?;

    let mut invalid_wtr =
        Config::new(Some(input_path.to_owned() + "." + invalid_suffix).as_ref()).writer()?;
    invalid_wtr.write_byte_record(headers)?;

    let mut rdr = rconfig.reader()?;

    let valid_flags_len = valid_flags.len();

    let mut record = csv::ByteRecord::new();
    while rdr.read_byte_record(&mut record)? {
        // length of valid_flags is max number of rows we can split
        if split_row_num > valid_flags_len {
            break;
        }

        if valid_flags[split_row_num] {
            valid_wtr.write_byte_record(&record)?;
        } else {
            invalid_wtr.write_byte_record(&record)?;
        }
        split_row_num += 1;
    }

    valid_wtr.flush()?;
    invalid_wtr.flush()?;

    Ok(())
}

fn write_error_report(input_path: &str, validation_error_messages: Vec<String>) -> CliResult<()> {
    let wtr_capacitys = env::var("QSV_WTR_BUFFER_CAPACITY")
        .unwrap_or_else(|_| DEFAULT_WTR_BUFFER_CAPACITY.to_string());
    let wtr_buffer_size: usize = wtr_capacitys.parse().unwrap_or(DEFAULT_WTR_BUFFER_CAPACITY);

    let output_file = File::create(input_path.to_owned() + ".validation-errors.tsv")?;

    let mut output_writer = BufWriter::with_capacity(wtr_buffer_size, output_file);

    output_writer.write_all(b"row_number\tfield\terror\n")?;

    // write out error report
    for error_msg in validation_error_messages {
        output_writer.write_all(error_msg.as_bytes())?;
        // since writer is buffered, it's more efficient to do additional write than append Newline
        // to message
        output_writer.write_all(b"\n")?;
    }

    // flush error report; file gets closed automagically when out-of-scope
    output_writer.flush()?;

    Ok(())
}

/// convert CSV Record into JSON instance by referencing JSON types
#[inline]
fn to_json_instance(
    header_types: &[(String, JSONtypes)],
    header_len: usize,
    record: &ByteRecord,
) -> CliResult<Value> {
    let mut json_object_map = Map::with_capacity(header_len);

    let mut json_value;

    for ((key, json_type), value) in header_types.iter().zip(record.iter()) {
        if value.is_empty() {
            json_object_map.insert(key.clone(), Value::Null);
            continue;
        }

        json_value = match json_type {
            JSONtypes::String => {
                if let Ok(v) = simdutf8::basic::from_utf8(value) {
                    Value::String(v.to_owned())
                } else {
                    // don't return an error if the string fails utf8 validation
                    // send the lossy utf8 value
                    Value::String(String::from_utf8_lossy(value).into_owned())
                }
            },
            JSONtypes::Number => {
                if let Ok(float) = fast_float2::parse(value) {
                    Value::Number(Number::from_f64(float).unwrap_or_else(|| Number::from(0)))
                } else {
                    return fail_clierror!(
                        "Can't cast to Number. key: {key}, value: {}",
                        String::from_utf8_lossy(value)
                    );
                }
            },
            JSONtypes::Integer => {
                if let Ok(int) = atoi_simd::parse::<i64>(value) {
                    Value::Number(Number::from(int))
                } else {
                    return fail_clierror!(
                        "Can't cast to Integer. key: {key}, value: {}",
                        String::from_utf8_lossy(value)
                    );
                }
            },
            JSONtypes::Boolean => match value {
                b"true" | b"1" => Value::Bool(true),
                b"false" | b"0" => Value::Bool(false),
                _ => {
                    return fail_clierror!(
                        "Can't cast to Boolean. key: {key}, value: {}",
                        String::from_utf8_lossy(value)
                    );
                },
            },
            JSONtypes::Unsupported => unreachable!("we should never get an unsupported JSON type"),
        };

        json_object_map.insert(key.clone(), json_value);
    }

    Ok(Value::Object(json_object_map))
}

/// get JSON types for each column in CSV file
/// returns a Vector of tuples of column/header name (String) & JSON type (JSONtypes enum)
#[inline]
fn get_json_types(headers: &ByteRecord, schema: &Value) -> CliResult<Vec<(String, JSONtypes)>> {
    // make sure schema has expected structure
    let Some(schema_properties) = schema.get("properties") else {
        return fail_clierror!("JSON Schema missing 'properties' object");
    };

    // safety: we set NULL_TYPE in main() and it's never changed
    let null_type = NULL_TYPE.get().unwrap();

    let mut field_def: &Value;
    let mut field_type_def: &Value;
    let mut json_type: JSONtypes;
    let mut header_types: Vec<(String, JSONtypes)> = Vec::with_capacity(headers.len());

    // iterate over each CSV field and convert to JSON type
    for header in headers {
        let Ok(key) = simdutf8::basic::from_utf8(header) else {
            let s = String::from_utf8_lossy(header);
            return fail_encoding_clierror!("CSV header is not valid UTF-8: {s}");
        };

        field_def = schema_properties.get(key).unwrap_or(&Value::Null);
        field_type_def = field_def.get("type").unwrap_or(&Value::Null);

        json_type = match field_type_def {
            Value::String(s) => match s.as_str() {
                "string" => JSONtypes::String,
                "number" => JSONtypes::Number,
                "integer" => JSONtypes::Integer,
                "boolean" => JSONtypes::Boolean,
                _ => JSONtypes::Unsupported,
            },
            Value::Array(vec) => {
                let mut return_val = JSONtypes::String;
                for val in vec {
                    if *val == *null_type {
                        continue;
                    }
                    return_val = if let Some(s) = val.as_str() {
                        match s {
                            "string" => JSONtypes::String,
                            "number" => JSONtypes::Number,
                            "integer" => JSONtypes::Integer,
                            "boolean" => JSONtypes::Boolean,
                            _ => JSONtypes::Unsupported,
                        }
                    } else {
                        JSONtypes::String
                    };
                }
                return_val
            },
            _ => JSONtypes::String,
        };

        header_types.push((key.to_owned(), json_type));
    }
    Ok(header_types)
}

fn load_json(uri: &str) -> Result<String, String> {
    let json_string = match uri {
        url if url.to_lowercase().starts_with("http") => {
            let client = match util::create_reqwest_blocking_client(
                None,
                TIMEOUT_SECS.load(Ordering::Relaxed),
                Some(uri.to_string()),
            ) {
                Ok(c) => c,
                Err(e) => return fail_format!("Cannot build reqwest client: {e}."),
            };

            match client.get(url).send() {
                Ok(response) => response.text().unwrap_or_default(),
                Err(e) => return fail_format!("Cannot read JSON at url {url}: {e}."),
            }
        },
        path => {
            let mut buffer = String::new();
            match File::open(path) {
                Ok(p) => {
                    BufReader::new(p)
                        .read_to_string(&mut buffer)
                        .unwrap_or_default();
                },
                Err(e) => return fail_format!("Cannot read JSON file {path}: {e}."),
            }
            buffer
        },
    };

    Ok(json_string)
}

/// Validate JSON instance against compiled JSON Schema
/// If invalid, returns Some(Vec<(String,String)>) holding the error messages
/// this is just for the tests below and is equivalent to the validation logic
/// in the main `validate` function which was inlined for performance reasons
#[cfg(test)]
fn validate_json_instance(
    instance: &Value,
    schema_compiled: &Validator,
) -> Option<Vec<(String, String)>> {
    // Use is_valid() for fast boolean check on valid records (doesn't walk full tree)
    // Only call evaluate() when invalid to get detailed errors
    if schema_compiled.is_valid(instance) {
        None
    } else {
        Some(
            schema_compiled
                .evaluate(instance)
                .iter_errors()
                .map(|e| (e.instance_location.to_string(), e.error.to_string()))
                .collect(),
        )
    }
}

#[cfg(test)]
mod tests_for_csv_to_json_conversion {

    use serde_json::json;

    use super::*;

    /// get schema used for unit tests
    fn schema_json() -> Value {
        // from https://json-schema.org/learn/miscellaneous-examples.html
        serde_json::json!({
            "$id": "https://example.com/test.schema.json",
            "$schema": "https://json-schema.org/draft/2020-12/schema",
            "title": "test",
            "type": "object",
            "properties": {
                "A": {
                    "type": "string",
                },
                "B": {
                    "type": "number",
                },
                "C": {
                    "type": "integer",
                },
                "D": {
                    "type": "boolean",
                },
                "E": {
                    "type": ["string", "null"],
                },
                "F": {
                    "type": ["number", "null"],
                },
                "G": {
                    "type": ["integer", "null"],
                },
                "H": {
                    "type": ["boolean", "null"],
                },
                "I": {
                    "type": ["string", "null"],
                },
                "J": {
                    "type": ["number", "null"],
                },
                "K": {
                    "type": ["null", "integer"],
                },
                "L": {
                    "type": ["boolean", "null"],
                },
            }
        })
    }

    #[test]
    #[allow(clippy::approx_constant)]
    fn test_to_json_instance() {
        let _ = NULL_TYPE.get_or_init(|| Value::String("null".to_string()));
        let csv = "A,B,C,D,E,F,G,H,I,J,K,L
        hello,3.1415,300000000,true,,,,,hello,3.1415,300000000,true";

        let mut rdr = csv::Reader::from_reader(csv.as_bytes());
        let headers = rdr.byte_headers().unwrap().clone();
        let header_types = get_json_types(&headers, &schema_json()).unwrap();
        let mut record = rdr.byte_records().next().unwrap().unwrap();
        record.trim();

        assert_eq!(
            to_json_instance(&header_types, headers.len(), &record)
                .expect("can't convert csv to json instance"),
            json!({
                "A": "hello",
                "B": 3.1415,
                "C": 300_000_000,
                "D": true,
                "E": null,
                "F": null,
                "G": null,
                "H": null,
                "I": "hello",
                "J": 3.1415,
                "K": 300_000_000,
                "L": true,
            })
        );
    }

    #[test]
    fn test_to_json_instance_cast_integer_error() {
        let _ = NULL_TYPE.get_or_init(|| Value::String("null".to_string()));
        let csv = "A,B,C,D,E,F,G,H
        hello,3.1415,3.0e8,true,,,,";

        let mut rdr = csv::Reader::from_reader(csv.as_bytes());
        let headers = rdr.byte_headers().unwrap().clone();
        let header_types = get_json_types(&headers, &schema_json()).unwrap();

        let result = to_json_instance(
            &header_types,
            headers.len(),
            &rdr.byte_records().next().unwrap().unwrap(),
        );
        assert!(&result.is_err());
        let error = result.err().unwrap().to_string();
        assert_eq!("Can't cast to Integer. key: C, value: 3.0e8", error);
    }
}

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

    fn schema_json() -> Value {
        // from https://json-schema.org/learn/miscellaneous-examples.html
        serde_json::json!({
            "$id": "https://example.com/person.schema.json",
            "$schema": "https://json-schema.org/draft/2020-12/schema",
            "title": "Person",
            "type": "object",
            "properties": {
                "title": {
                    "type": "string",
                    "description": "The person's title.",
                    "minLength": 2
                },
                "name": {
                    "type": "string",
                    "description": "The person's name.",
                    "minLength": 2
                },
                "age": {
                    "description": "Age in years which must be equal to or greater than 18.",
                    "type": "integer",
                    "minimum": 18
                }
            }
        })
    }

    fn compiled_schema() -> Validator {
        Validator::options()
            .build(&schema_json())
            .expect("Invalid schema")
    }

    #[test]
    fn test_validate_with_no_errors() {
        let _ = NULL_TYPE.get_or_init(|| Value::String("null".to_string()));
        let csv = "title,name,age
        Professor,Xaviers,60";

        let mut rdr = csv::Reader::from_reader(csv.as_bytes());
        let headers = rdr.byte_headers().unwrap().clone();
        let header_types = get_json_types(&headers, &schema_json()).unwrap();

        let record = &rdr.byte_records().next().unwrap().unwrap();

        let instance = to_json_instance(&header_types, headers.len(), record).unwrap();

        let result = validate_json_instance(&instance, &compiled_schema());

        assert!(result.is_none());
    }

    #[test]
    fn test_validate_with_error() {
        let _ = NULL_TYPE.get_or_init(|| Value::String("null".to_string()));
        let csv = "title,name,age
        Professor,X,60";

        let mut rdr = csv::Reader::from_reader(csv.as_bytes());
        let headers = rdr.byte_headers().unwrap().clone();
        let header_types = get_json_types(&headers, &schema_json()).unwrap();

        let record = &rdr.byte_records().next().unwrap().unwrap();

        let instance = to_json_instance(&header_types, headers.len(), record).unwrap();

        let result = validate_json_instance(&instance, &compiled_schema());

        assert!(result.is_some());

        assert_eq!(
            vec![(
                "/name".to_string(),
                "\"X\" is shorter than 2 characters".to_string()
            )],
            result.unwrap()
        );
    }
}

#[test]
fn test_validate_currency_email_dynamicenum_validator() {
    #[cfg(not(feature = "lite"))]
    let qsv_cache_dir = lookup::set_qsv_cache_dir("~/.qsv-cache").unwrap();
    #[cfg(not(feature = "lite"))]
    QSV_CACHE_DIR.get_or_init(|| qsv_cache_dir);

    fn schema_currency_json() -> Value {
        serde_json::json!({
            "$id": "https://example.com/person.schema.json",
            "$schema": "https://json-schema.org/draft/2020-12/schema",
            "title": "Person",
            "type": "object",
            "properties": {
                "title": {
                    "type": "string",
                    "description": "The person's title.",
                    "minLength": 2
                },
                "name": {
                    "type": "string",
                    "description": "The person's name.",
                    "minLength": 2
                },
                "fee": {
                    "description": "The required fee to see the person.",
                    "type": "string",
                    "format": "currency",
                },
                "email": {
                    "description": "The person's email.",
                    "type": "string",
                    "format": "email",
                },
                "agency": {
                    "description": "The person's agency.",
                    "type": "string",
                    "dynamicEnum": "https://raw.githubusercontent.com/dathere/qsv/refs/heads/master/scripts/NYC_agencies.csv",
                }
            }
        })
    }

    let _ = NULL_TYPE.get_or_init(|| Value::String("null".to_string()));
    let csv = "title,name,fee
    Professor,Xaviers,Ð 100.00";

    let mut rdr = csv::Reader::from_reader(csv.as_bytes());
    let headers = rdr.byte_headers().unwrap().clone();
    let header_types = get_json_types(&headers, &schema_currency_json()).unwrap();

    let record = &rdr.byte_records().next().unwrap().unwrap();

    let instance = to_json_instance(&header_types, headers.len(), record).unwrap();

    let compiled_schema = Validator::options()
        .with_format("currency", currency_format_checker)
        .with_keyword("dynamicEnum", dyn_enum_validator_factory)
        .should_validate_formats(true)
        .build(&schema_currency_json())
        .expect("Invalid schema");

    let result = validate_json_instance(&instance, &compiled_schema);

    // Dogecoin is not an ISO currency
    assert_eq!(
        result,
        Some(vec![(
            "/fee".to_owned(),
            "\"Ð 100.00\" is not a \"currency\"".to_owned()
        )])
    );

    let csv = "title,name,fee,email
    Professor,Xaviers,Ð 100.00,thisisnotanemail";

    let mut rdr = csv::Reader::from_reader(csv.as_bytes());
    let headers = rdr.byte_headers().unwrap().clone();
    let header_types = get_json_types(&headers, &schema_currency_json()).unwrap();

    let record = &rdr.byte_records().next().unwrap().unwrap();

    let instance = to_json_instance(&header_types, headers.len(), record).unwrap();

    let compiled_schema = Validator::options()
        .with_format("currency", currency_format_checker)
        .with_keyword("dynamicEnum", dyn_enum_validator_factory)
        .should_validate_formats(true)
        .build(&schema_currency_json())
        .expect("Invalid schema");

    let result = validate_json_instance(&instance, &compiled_schema);

    assert_eq!(
        result,
        Some(vec![
            (
                "/fee".to_owned(),
                "\"Ð 100.00\" is not a \"currency\"".to_owned()
            ),
            (
                "/email".to_owned(),
                "\"thisisnotanemail\" is not a \"email\"".to_owned()
            )
        ])
    );

    let csv = r#"title,name,fee,email,agency
    Professor,Xaviers,"USD60.02",x@men.com,DOITT
    He-man,Wolverine,"$100.00",claws@men.com,DPR
    Mr,Deadpool,"¥1,000,000.00",landfill@nomail.net,DSNY
    Mrs,T,"-€ 1.000.000,00",t+sheher@t.com,MODA
    Madam,X,"(EUR 1.999.000,12)",x123@aol.com,DOB
    SilicoGod,Vision,"1.000.000,00",singularity+is@here.ai,DOITT
    Dr,Strange,"€ 1.000.000,00",stranger.danger@xmen.com,NYFD
    Dr,Octopus,"WAX 100.000,00",octopussy@bond.net,DFTA
    Mr,Robot,"B 1,000,000",71076.964-compuserve,ABCD"#;

    let mut rdr = csv::Reader::from_reader(csv.as_bytes());
    let headers = rdr.byte_headers().unwrap().clone();
    let header_types = get_json_types(&headers, &schema_currency_json()).unwrap();

    let compiled_schema = Validator::options()
        .with_format("currency", currency_format_checker)
        .with_keyword("dynamicEnum", dyn_enum_validator_factory)
        .should_validate_formats(true)
        .build(&schema_currency_json())
        .expect("Invalid schema");

    for (i, record) in rdr.byte_records().enumerate() {
        let record = record.unwrap();
        let instance = to_json_instance(&header_types, headers.len(), &record).unwrap();

        let result = validate_json_instance(&instance, &compiled_schema);

        match i {
            0 => assert_eq!(result, None),
            1 => assert_eq!(result, None),
            2 => assert_eq!(result, None),
            3 => assert_eq!(
                result,
                Some(vec![
                    (
                        "/name".to_owned(),
                        "\"T\" is shorter than 2 characters".to_owned()
                    ),
                    (
                        "/agency".to_owned(),
                        "\"MODA\" is not a valid dynamicEnum value".to_owned()
                    )
                ])
            ),
            4 => assert_eq!(
                result,
                Some(vec![(
                    "/name".to_owned(),
                    "\"X\" is shorter than 2 characters".to_owned()
                )])
            ),
            5 => assert_eq!(result, None),
            6 => assert_eq!(
                result,
                Some(vec![(
                    "/agency".to_owned(),
                    "\"NYFD\" is not a valid dynamicEnum value".to_owned()
                )])
            ),
            7 => assert_eq!(
                result,
                Some(vec![(
                    "/fee".to_owned(),
                    "\"WAX 100.000,00\" is not a \"currency\"".to_owned()
                )])
            ),
            8 => assert_eq!(
                result,
                Some(vec![
                    (
                        "/fee".to_owned(),
                        "\"B 1,000,000\" is not a \"currency\"".to_owned()
                    ),
                    (
                        "/email".to_owned(),
                        "\"71076.964-compuserve\" is not a \"email\"".to_owned()
                    ),
                    (
                        "/agency".to_owned(),
                        "\"ABCD\" is not a valid dynamicEnum value".to_owned()
                    )
                ])
            ),
            _ => unreachable!(),
        }
    }
}

#[test]
fn test_load_json_via_url() {
    #[cfg(not(feature = "lite"))]
    let qsv_cache_dir = lookup::set_qsv_cache_dir("~/.qsv-cache").unwrap();
    #[cfg(not(feature = "lite"))]
    QSV_CACHE_DIR.get_or_init(|| qsv_cache_dir);

    let json_string_result = load_json("https://geojson.org/schema/FeatureCollection.json");
    assert!(&json_string_result.is_ok());

    let json_result: Result<Value, serde_json::Error> =
        serde_json::from_str(&json_string_result.unwrap());
    assert!(&json_result.is_ok());
}

#[test]
fn test_dyn_enum_validator() {
    #[cfg(not(feature = "lite"))]
    let qsv_cache_dir = lookup::set_qsv_cache_dir("~/.qsv-cache").unwrap();
    #[cfg(not(feature = "lite"))]
    QSV_CACHE_DIR.get_or_init(|| qsv_cache_dir);

    let schema = json!({"dynamicEnum": "https://raw.githubusercontent.com/dathere/qsv/refs/heads/master/resources/test/fruits.csv", "type": "string"});
    let validator = jsonschema::options()
        .with_keyword("dynamicEnum", dyn_enum_validator_factory)
        .build(&schema)
        .unwrap();

    assert!(validator.is_valid(&json!("banana")));
    assert!(validator.is_valid(&json!("strawberry")));
    assert!(validator.is_valid(&json!("apple")));
    assert!(!validator.is_valid(&json!("Apple")));
    assert!(!validator.is_valid(&json!("starapple")));
    assert!(!validator.is_valid(&json!("bananana")));
    assert!(!validator.is_valid(&json!("")));
    assert!(!validator.is_valid(&json!(5)));
    match validator.validate(&json!("lanzones")) {
        Err(e) => {
            assert_eq!(
                format!("{e:?}"),
                "ValidationError { repr: ValidationErrorRepr { instance: String(\"lanzones\"), \
                 kind: Custom { keyword: \"dynamicEnum\", message: \"\\\"lanzones\\\" is not a \
                 valid dynamicEnum value\" }, instance_path: Location(\"\"), schema_path: \
                 Location(\"/dynamicEnum\"), .. } }"
            );
        },
        _ => {
            unreachable!("Expected an error, but validation succeeded.");
        },
    }
}