xbrlkit 0.1.1

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

use regex::Regex;
use std::collections::HashMap;
use std::sync::LazyLock as Lazy;

/// A rule: the text the filing shows in, the normalised value out.
type Transformation = fn(&str) -> Result<String, TransformationError>;

/// Rules by local name, e.g. `numwordsen`.
type TransformationRegistry = HashMap<&'static str, Transformation>;

/// Why a transformation produced no value.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum TransformationError {
    /// The text is not something the rule can read: the value, then the rule.
    #[error("cannot read {0:?} as {1}")]
    InvalidInput(String, String),
}

// --- Transformation Function Implementations ---

/// Converts SEC checkbox characters to boolean strings
///
/// ## Examples
/// ```
/// use xbrlkit::transformations::bool_ballot_box;
///
/// assert_eq!(bool_ballot_box("☐").unwrap(), "false");
/// assert_eq!(bool_ballot_box("☑").unwrap(), "true");
/// ```
pub fn bool_ballot_box(value: &str) -> Result<String, TransformationError> {
    match value.trim() {
        "☐" => Ok("false".to_string()),
        "☑" | "☒" => Ok("true".to_string()),
        _ => Err(TransformationError::InvalidInput(
            value.to_string(),
            "bool_ballot_box: expected ☐, ☑, or ☒".to_string(),
        )),
    }
}

/// Converts English number words to numeric strings
///
/// Supports numbers from zero to 999,999,999,999 (999 billion).
/// Handles both short form and variations with "and", commas, and hyphens.
///
/// ## Examples
/// - "one" → "1"
/// - "seventy thousand and one" → "70001"
/// - "nineteen hundred forty-four" → "1944"
/// - "six million four hundred thousand five" → "6400005"
pub fn num_words_en(value: &str) -> Result<String, TransformationError> {
    let trimmed = value.trim();
    if trimmed.is_empty()
        || trimmed.eq_ignore_ascii_case("none")
        || trimmed.eq_ignore_ascii_case("no")
        || trimmed.eq_ignore_ascii_case("nil")
    {
        return Ok("0".to_string());
    }

    // Word to number mappings
    let small_numbers: HashMap<&str, i64> = [
        ("zero", 0),
        ("one", 1),
        ("two", 2),
        ("three", 3),
        ("four", 4),
        ("five", 5),
        ("six", 6),
        ("seven", 7),
        ("eight", 8),
        ("nine", 9),
        ("ten", 10),
        ("eleven", 11),
        ("twelve", 12),
        ("thirteen", 13),
        ("fourteen", 14),
        ("fifteen", 15),
        ("sixteen", 16),
        ("seventeen", 17),
        ("eighteen", 18),
        ("nineteen", 19),
        ("twenty", 20),
        ("thirty", 30),
        ("forty", 40),
        ("fifty", 50),
        ("sixty", 60),
        ("seventy", 70),
        ("eighty", 80),
        ("ninety", 90),
    ]
    .iter()
    .cloned()
    .collect();

    let magnitudes: HashMap<&str, i64> = [
        ("hundred", 100),
        ("thousand", 1_000),
        ("million", 1_000_000),
        ("billion", 1_000_000_000),
        ("trillion", 1_000_000_000_000),
    ]
    .iter()
    .cloned()
    .collect();

    // Convert to lowercase and split on whitespace, hyphens, commas, and "and"
    let lowercase = trimmed.to_lowercase();
    let words: Vec<&str> = lowercase
        .split(|c: char| c.is_whitespace() || c == '-' || c == ',')
        .filter(|s| !s.is_empty() && *s != "and")
        .collect();

    let mut result: i64 = 0;
    let mut current: i64 = 0;

    for word in words {
        if let Some(&num) = small_numbers.get(word) {
            current += num;
        } else if let Some(&mag) = magnitudes.get(word) {
            if word == "hundred" {
                current *= mag;
            } else {
                // thousand, million, billion, etc.
                current *= mag;
                result += current;
                current = 0;
            }
        } else {
            return Err(TransformationError::InvalidInput(
                value.to_string(),
                "numwordsen".to_string(),
            ));
        }
    }

    result += current;
    Ok(result.to_string())
}

/// Converts English duration words to ISO 8601 duration format
///
/// Parses durations with years, months, and/or days expressed in words or numbers.
///
/// ## Examples
/// - "9 years, 2 months" → "P9Y2M"
/// - "Five years, two months" → "P5Y2M"
/// - "three years four months no days" → "P3Y4M"
pub fn dur_words_en(value: &str) -> Result<String, TransformationError> {
    // Unicode dashes: Armenian hyphen (U+058A), Hebrew maqaf (U+05BE),
    // hyphens/dashes (U+2010-2015), small em dash (U+FE58),
    // small hyphen-minus (U+FE63), fullwidth hyphen-minus (U+FF0D), and ASCII hyphen
    // Pattern matches: "N year(s)", "M month(s)", "D day(s)" in any combination
    static DURATION_REGEX: Lazy<Regex> = Lazy::new(|| {
        Regex::new(r"(?i)(?:(\d+|[a-z]+)[\s\u{058A}\u{05BE}\u{2010}-\u{2015}\u{FE58}\u{FE63}\u{FF0D}\-]*years?)?[,\s\u{058A}\u{05BE}\u{2010}-\u{2015}\u{FE58}\u{FE63}\u{FF0D}\-]*(and\s+)?(?:(\d+|[a-z]+)[\s\u{058A}\u{05BE}\u{2010}-\u{2015}\u{FE58}\u{FE63}\u{FF0D}\-]*months?)?[,\s\u{058A}\u{05BE}\u{2010}-\u{2015}\u{FE58}\u{FE63}\u{FF0D}\-]*(and\s+)?(?:(\d+|[a-z]+)[\s\u{058A}\u{05BE}\u{2010}-\u{2015}\u{FE58}\u{FE63}\u{FF0D}\-]*days?)?").unwrap()
    });

    let input = value.trim().to_lowercase();

    if let Some(caps) = DURATION_REGEX.captures(&input) {
        let mut parts = Vec::new();

        // Parse years (group 1)
        if let Some(year_str) = caps.get(1) {
            let year_val = parse_word_or_num(year_str.as_str())?;
            if year_val > 0 {
                parts.push(format!("{}Y", year_val));
            }
        }

        // Parse months (group 3, because group 2 is the "and" after years)
        if let Some(month_str) = caps.get(3) {
            let month_val = parse_word_or_num(month_str.as_str())?;
            if month_val > 0 {
                parts.push(format!("{}M", month_val));
            }
        }

        // Parse days (group 5, because group 4 is the "and" after months)
        if let Some(day_str) = caps.get(5) {
            let day_val = parse_word_or_num(day_str.as_str())?;
            if day_val > 0 {
                parts.push(format!("{}D", day_val));
            }
        }

        if parts.is_empty() {
            Ok("P0D".to_string())
        } else {
            Ok(format!("P{}", parts.join("")))
        }
    } else {
        Err(TransformationError::InvalidInput(
            value.to_string(),
            "durwordsen".to_string(),
        ))
    }
}

/// Helper function to parse a word or number string
fn parse_word_or_num(s: &str) -> Result<i64, TransformationError> {
    let trimmed = s.trim().to_lowercase();

    // Try parsing as a number first
    if let Ok(num) = trimmed.parse::<i64>() {
        return Ok(num);
    }

    // Handle special cases (matching Python's durwordZeroNoPattern and numwordsNoPattern)
    if trimmed == "no" || trimmed == "zero" || trimmed == "none" || trimmed == "nil" {
        return Ok(0);
    }

    // Try word-to-number conversion for small numbers
    let small_numbers: HashMap<&str, i64> = [
        ("one", 1),
        ("two", 2),
        ("three", 3),
        ("four", 4),
        ("five", 5),
        ("six", 6),
        ("seven", 7),
        ("eight", 8),
        ("nine", 9),
        ("ten", 10),
        ("eleven", 11),
        ("twelve", 12),
        ("thirteen", 13),
        ("fourteen", 14),
        ("fifteen", 15),
        ("sixteen", 16),
        ("seventeen", 17),
        ("eighteen", 18),
        ("nineteen", 19),
        ("twenty", 20),
        ("thirty", 30),
        ("forty", 40),
        ("fifty", 50),
        ("sixty", 60),
        ("seventy", 70),
        ("eighty", 80),
        ("ninety", 90),
    ]
    .iter()
    .cloned()
    .collect();

    if let Some(&num) = small_numbers.get(trimmed.as_str()) {
        Ok(num)
    } else {
        Err(TransformationError::InvalidInput(
            s.to_string(),
            "word_or_num".to_string(),
        ))
    }
}

/// A number with `.` for the decimal point: drops the thousands separators,
/// whether commas, spaces or apostrophes.
///
/// ## Examples
/// - "1,000,000" → "1000000"
/// - "123,456.789" → "123456.789"
/// - "1 234.5" → "1234.5"
pub fn num_dot_decimal(value: &str) -> Result<String, TransformationError> {
    Ok(value
        .chars()
        .filter(|c| !is_group_separator(*c) && *c != ',')
        .collect())
}

/// A number with `,` for the decimal point, as most of Europe writes it.
///
/// ## Examples
/// - "1.234,56" → "1234.56"
/// - "1 234,5" → "1234.5"
pub fn num_comma_decimal(value: &str) -> Result<String, TransformationError> {
    Ok(value
        .chars()
        .filter(|c| !is_group_separator(*c) && *c != '.')
        .map(|c| if c == ',' { '.' } else { c })
        .collect())
}

/// A number written as whole units and a fraction of one, each with its
/// name: the text between the two numbers is the decimal point.
///
/// ## Examples
/// - "3 dollars 50 cents" → "3.50"
/// - "1,234 dollars and 5 cents" → "1234.05"
pub fn num_unit_decimal(value: &str) -> Result<String, TransformationError> {
    static UNIT_DECIMAL: Lazy<Regex> = Lazy::new(|| {
        Regex::new(r"^\s*([0-9][0-9.,]*)[^0-9.,][^0-9]*([0-9]{1,2})[^0-9]*$").unwrap()
    });
    let caps = UNIT_DECIMAL.captures(value).ok_or_else(|| {
        TransformationError::InvalidInput(value.to_string(), "num-unit-decimal".to_string())
    })?;
    let whole: String = caps[1].chars().filter(char::is_ascii_digit).collect();
    Ok(format!("{whole}.{:0>2}", &caps[2]))
}

/// What separates groups of digits besides the comma or the point: spaces of
/// any width, and the apostrophes of Swiss notation.
fn is_group_separator(c: char) -> bool {
    c.is_whitespace() || matches!(c, '\'' | '’' | '`' | '´')
}

/// Returns the fixed value "false" regardless of input
pub fn fixed_false(_value: &str) -> Result<String, TransformationError> {
    Ok("false".to_string())
}

/// Returns the fixed value "true" regardless of input
pub fn fixed_true(_value: &str) -> Result<String, TransformationError> {
    Ok("true".to_string())
}

/// Returns the fixed value "0" regardless of input
pub fn fixed_zero(_value: &str) -> Result<String, TransformationError> {
    Ok("0".to_string())
}

/// Returns nothing regardless of input: the fact is reported with no value.
pub fn fixed_empty(_value: &str) -> Result<String, TransformationError> {
    Ok(String::new())
}

/// Returns "false" (boolean false)
pub fn boolean_false(_value: &str) -> Result<String, TransformationError> {
    Ok("false".to_string())
}

/// Returns "true" (boolean true)
pub fn boolean_true(_value: &str) -> Result<String, TransformationError> {
    Ok("true".to_string())
}

/// Converts dash (-) to zero (0) for numeric fields
///
/// This is a standard iXBRL transformation used when a dash represents
/// a zero value in financial statements.
///
/// ## Examples
/// - "-" → "0"
/// - "  -  " → "0" (with whitespace)
pub fn zero_dash(value: &str) -> Result<String, TransformationError> {
    let trimmed = value.trim();
    if trimmed == "-" || trimmed == "—" || trimmed == "–" {
        Ok("0".to_string())
    } else {
        // If it's not a dash, return the original value trimmed
        Ok(trimmed.to_string())
    }
}

/// Returns positive infinity for float/double types
pub fn num_inf(_value: &str) -> Result<String, TransformationError> {
    Ok("INF".to_string())
}

/// Returns negative infinity for float/double types
pub fn num_neg_inf(_value: &str) -> Result<String, TransformationError> {
    Ok("-INF".to_string())
}

/// Returns NaN (not-a-number) for float/double types
pub fn num_nan(_value: &str) -> Result<String, TransformationError> {
    Ok("NaN".to_string())
}

/// Converts ballot box unicode characters to Yes/No text values
///
/// Translates:
/// - ☐ (U+2610 BALLOT BOX) → "No"
/// - ☑ (U+2611 BALLOT BOX WITH CHECK) → "Yes"
/// - ☒ (U+2612 BALLOT BOX WITH X) → "Yes"
pub fn yesno_ballot_box(value: &str) -> Result<String, TransformationError> {
    let input = value.trim();

    if input.is_empty() {
        return Err(TransformationError::InvalidInput(
            value.to_string(),
            "yesno_ballot_box: empty input".to_string(),
        ));
    }

    match input.chars().next() {
        Some('\u{2610}') => Ok("No".to_string()),
        Some('\u{2611}') => Ok("Yes".to_string()),
        Some('\u{2612}') => Ok("Yes".to_string()),
        _ => Err(TransformationError::InvalidInput(
            value.to_string(),
            format!("yesno_ballot_box: invalid ballot box character: {}", input),
        )),
    }
}

/// Normalizes exchange names to standard codes using SEC regex patterns
///
/// Based on SEC EDGAR specifications. Handles variations with "The", "Inc.", "LLC", etc.
///
/// ## Examples
/// - "New York Stock Exchange" → "NYSE"
/// - "The NASDAQ Stock Market, LLC" → "NASDAQ"
/// - "Cboe BZX Exchange, Inc." → "CboeBZX"
pub fn exchnameen(value: &str) -> Result<String, TransformationError> {
    // Use simple normalization for matching - remove "The", case-insensitive, trim punctuation
    let normalized = value
        .trim()
        .to_lowercase()
        .replace("the ", "")
        .replace(",", "")
        .replace(".", "")
        .replace("inc", "")
        .replace("llc", "")
        .trim()
        .to_string();

    // Match against normalized patterns
    if normalized.contains("box exchange") {
        return Ok("BOX".to_string());
    }
    if normalized.contains("cboe byx exchange") {
        return Ok("CboeBYX".to_string());
    }
    if normalized.contains("cboe bzx exchange") {
        return Ok("CboeBZX".to_string());
    }
    if normalized.contains("cboe c2 exchange") {
        return Ok("C2".to_string());
    }
    if normalized.contains("cboe edga exchange") {
        return Ok("CboeEDGA".to_string());
    }
    if normalized.contains("cboe edgx exchange") {
        return Ok("CboeEDGX".to_string());
    }
    if normalized.contains("cboe exchange") {
        return Ok("CBOE".to_string());
    }
    if normalized.contains("chicago stock exchange") {
        return Ok("CHX".to_string());
    }
    if normalized.contains("investors exchange") {
        return Ok("IEX".to_string());
    }
    if normalized.contains("miami international securities exchange") {
        return Ok("MIAX".to_string());
    }
    if normalized.contains("miax pearl") {
        return Ok("PEARL".to_string());
    }
    if normalized.contains("nasdaq bx") {
        return Ok("BX".to_string());
    }
    if normalized.contains("nasdaq gemx") {
        return Ok("GEMX".to_string());
    }
    if normalized.contains("nasdaq ise") {
        return Ok("ISE".to_string());
    }
    if normalized.contains("nasdaq mrx") {
        return Ok("MRX".to_string());
    }
    if normalized.contains("nasdaq phlx") {
        return Ok("Phlx".to_string());
    }
    // Check NYSE variants - most specific first
    if normalized.contains("nyse american") {
        return Ok("NYSEAMER".to_string());
    }
    if normalized.contains("nyse arca") {
        return Ok("NYSEArca".to_string());
    }
    if normalized.contains("nyse national") {
        return Ok("NYSENAT".to_string());
    }
    if normalized.contains("new york stock exchange") || normalized == "nyse" {
        return Ok("NYSE".to_string());
    }
    // Check NASDAQ variants
    if normalized.contains("nasdaq") {
        return Ok("NASDAQ".to_string());
    }

    Err(TransformationError::InvalidInput(
        value.to_string(),
        "exchnameen: no matching exchange pattern".to_string(),
    ))
}

/// One piece of a written date, in the order a format expects them.
#[derive(Debug, Clone, Copy, PartialEq)]
enum DatePart {
    Day,
    /// A month as a number.
    Month,
    /// A month by its English name or abbreviation.
    MonthName,
    Year,
}

/// `"sept"` → `9`. Takes the full name or any abbreviation of three letters
/// or more, in any case.
fn month_number(name: &str) -> Option<u32> {
    const MONTHS: [&str; 12] = [
        "january",
        "february",
        "march",
        "april",
        "may",
        "june",
        "july",
        "august",
        "september",
        "october",
        "november",
        "december",
    ];
    let name = name.to_ascii_lowercase();
    if name.len() < 3 {
        return None;
    }
    let month = MONTHS.iter().position(|month| month.starts_with(&name))?;
    Some(month as u32 + 1)
}

fn days_in_month(month: u32, year: Option<u32>) -> u32 {
    match month {
        4 | 6 | 9 | 11 => 30,
        // Without a year, the day a leap year has is a day the month can have.
        2 => match year {
            Some(y) if !(y % 4 == 0 && (y % 100 != 0 || y % 400 == 0)) => 28,
            _ => 29,
        },
        _ => 31,
    }
}

/// Reads a date written as `parts`, whatever separates them — `9/30/2025`,
/// `30.09.25`, `Sept. 30, 2025`, `30th of September 2025` — into the XML
/// Schema form of what it holds: `2025-09-30` for a full date, `--09-30` for
/// a month and day, `2025-09` for a month and year.
///
/// A two-digit year is in this century, as the registry has it.
fn read_date(value: &str, format: &str, parts: &[DatePart]) -> Result<String, TransformationError> {
    let invalid = || TransformationError::InvalidInput(value.to_string(), format.to_string());

    // Runs of digits and runs of letters; everything else separates them.
    let mut tokens: Vec<&str> = Vec::new();
    let mut start = None;
    let mut chars = value.char_indices().peekable();
    while let Some((i, c)) = chars.next() {
        if !c.is_alphanumeric() {
            continue;
        }
        let begin = *start.get_or_insert(i);
        let run_ends = match chars.peek() {
            Some((_, next)) => {
                !next.is_alphanumeric() || next.is_ascii_digit() != c.is_ascii_digit()
            }
            None => true,
        };
        if run_ends {
            tokens.push(&value[begin..i + c.len_utf8()]);
            start = None;
        }
    }
    // "30th", "1st", and the "of" in "30th of September".
    tokens.retain(|token| {
        !["st", "nd", "rd", "th", "of"]
            .iter()
            .any(|filler| token.eq_ignore_ascii_case(filler))
    });
    if tokens.len() != parts.len() {
        return Err(invalid());
    }

    let (mut day, mut month, mut year) = (None, None, None);
    for (token, part) in tokens.iter().zip(parts) {
        let number = || token.parse::<u32>().ok();
        match part {
            DatePart::Day => day = Some(number().filter(|_| token.len() <= 2).ok_or_else(invalid)?),
            DatePart::Month => {
                month = Some(number().filter(|_| token.len() <= 2).ok_or_else(invalid)?)
            }
            DatePart::MonthName => month = Some(month_number(token).ok_or_else(invalid)?),
            DatePart::Year => {
                year = Some(match token.len() {
                    4 => number().ok_or_else(invalid)?,
                    1 | 2 => 2000 + number().ok_or_else(invalid)?,
                    _ => return Err(invalid()),
                })
            }
        }
    }

    let month = month.filter(|m| (1..=12).contains(m)).ok_or_else(invalid)?;
    if let Some(day) = day {
        if day == 0 || day > days_in_month(month, year) {
            return Err(invalid());
        }
    }
    Ok(match (year, day) {
        (Some(year), Some(day)) => format!("{year:04}-{month:02}-{day:02}"),
        (Some(year), None) => format!("{year:04}-{month:02}"),
        (None, Some(day)) => format!("--{month:02}-{day:02}"),
        (None, None) => return Err(invalid()),
    })
}

/// A date written month first, by name: `ixt:date-monthname-day-year-en`.
///
/// ## Examples
/// - "August 22, 2025" → "2025-08-22"
/// - "Sept. 30, 2025" → "2025-09-30"
pub fn date_month_day_year_en(value: &str) -> Result<String, TransformationError> {
    use DatePart::*;
    read_date(value, "date-monthname-day-year-en", &[MonthName, Day, Year])
}

/// Converts quarter notation to end-of-quarter date
///
/// Parses expressions like:
/// - "Q3 2023", "3rd 2023", "third quarter 2023" → "2023-09-30"
/// - "2023 Q2", "2023 second", "2023 2nd" → "2023-06-30"
/// - "last 2023" → "2023-12-31"
///
/// Based on SEC EDGAR pattern matching with two formats:
/// 1. Optional prefix + quarter + year
/// 2. Year + quarter + optional suffix
pub fn date_quarter_end(value: &str) -> Result<String, TransformationError> {
    static QUARTER_PATTERN: Lazy<Regex> = Lazy::new(|| {
        // Simplified pattern - matches common quarter notations
        // Pattern 1: Q1 2023, 1st 2023, first 2023, etc.
        // Pattern 2: 2023 Q1, 2023 first, etc.
        Regex::new(r"(?ix)^[ \t\n\r]*
            (?:
                (?:Q\s*)?(1|[Ff]irst|2|[Ss]econd|3|[Tt]hird|4|[Ff]ourth|[Ll]ast)(?:\s*quarter)?\s+([0-9]{4})
                |
                ([0-9]{4})\s+(?:Q\s*)?(1|[Ff]irst|2|[Ss]econd|3|[Tt]hird|4|[Ff]ourth|[Ll]ast)
            )
        [ \t\n\r]*$").unwrap()
    });

    let input = value.trim();

    if let Some(caps) = QUARTER_PATTERN.captures(input) {
        // Extract year and quarter from either pattern
        let year_str = caps
            .get(2)
            .or_else(|| caps.get(3))
            .ok_or_else(|| {
                TransformationError::InvalidInput(
                    value.to_string(),
                    "date_quarter_end: no year found".to_string(),
                )
            })?
            .as_str();

        let quarter_str = caps
            .get(1)
            .or_else(|| caps.get(4))
            .ok_or_else(|| {
                TransformationError::InvalidInput(
                    value.to_string(),
                    "date_quarter_end: no quarter found".to_string(),
                )
            })?
            .as_str()
            .to_lowercase();

        let year: i32 = year_str.parse().map_err(|_| {
            TransformationError::InvalidInput(
                value.to_string(),
                "date_quarter_end: invalid year".to_string(),
            )
        })?;

        // Map quarter to month
        let month = match quarter_str.as_str() {
            "first" | "1" => 3,
            "second" | "2" => 6,
            "third" | "3" => 9,
            "fourth" | "last" | "4" => 12,
            _ => {
                return Err(TransformationError::InvalidInput(
                    value.to_string(),
                    format!("date_quarter_end: invalid quarter: {}", quarter_str),
                ));
            }
        };

        // Calculate last day of the quarter month
        let day = match month {
            3 => {
                // March - check for leap year
                if (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) {
                    // Leap year: Jan 31 + Feb 29 + Mar 31 = 91 days in Q1
                    31
                } else {
                    31
                }
            }
            6 => 30,  // June
            9 => 30,  // September
            12 => 31, // December
            _ => unreachable!(),
        };

        Ok(format!("{:04}-{:02}-{:02}", year, month, day))
    } else {
        Err(TransformationError::InvalidInput(
            value.to_string(),
            "date_quarter_end: no valid quarter pattern".to_string(),
        ))
    }
}

/// Converts US state/province names to 2-letter codes using SEC regex pattern
///
/// Supports all 50 US states, DC, US territories, and Canadian provinces.
///
/// ## Examples
/// - "Utah" → "UT"
/// - "Delaware" → "DE"
/// - "British Columbia" → "BC"
/// - "Puerto Rico" → "PR"
pub fn stateprovnameen(value: &str) -> Result<String, TransformationError> {
    static STATE_PROV_PATTERN: Lazy<Regex> = Lazy::new(|| {
        Regex::new(
            r"(?ix)^[ \t\n\r]*
            (
                ([Aa]labama)|([Aa]laska)|([Aa]rizona)|([Aa]rkansas)|([Cc]alifornia)|
                ([Cc]olorado)|([Cc]onnecticut)|([Dd]elaware)|([Ff]lorida)|([Gg]eorgia)|
                ([Hh]awaii)|([Ii]daho)|([Ii]llinois)|([Ii]ndiana)|([Ii]owa)|([Kk]ansas)|
                ([Kk]entucky)|([Ll]ouisiana)|([Mm]aine)|([Mm]aryland)|([Mm]assachusetts)|
                ([Mm]ichigan)|([Mm]innesota)|([Mm]ississippi)|([Mm]issouri)|([Mm]ontana)|
                ([Nn]ebraska)|([Nn]evada)|([Nn]ew\s+[Hh]ampshire)|([Nn]ew\s+[Jj]ersey)|
                ([Nn]ew\s+[Mm]exico)|([Nn]ew\s+[Yy]ork)|([Nn]orth\s+[Cc]arolina)|
                ([Nn]orth\s+[Dd]akota)|([Oo]hio)|([Oo]klahoma)|([Oo]regon)|
                ([Pp]ennsylvania)|([Rr]hode\s+[Ii]sland)|([Ss]outh\s+[Cc]arolina)|
                ([Ss]outh\s+[Dd]akota)|([Tt]ennessee)|([Tt]exas)|([Uu]tah)|([Vv]ermont)|
                ([Vv]irginia)|([Ww]ashington)|([Ww]est\s+[Vv]irginia)|([Ww]isconsin)|
                ([Ww]yoming)|([Dd]istrict\s+[Oo]f\s+[Cc]olumbia)|
                ((?:[Aa]merican\s+)?[Ss]amoa)|([Gg]uam)|([Nn]orthern\s+[Mm]ariana\s+[Ii]slands)|
                ([Pp]uerto\s+[Rr]ico)|([Uu]nited\s+[Ss]tates\s+[Mm]inor\s+[Oo]utlying\s+[Ii]slands)|
                ([Vv]irgin\s+[Ii]slands,\s+U[.]?S[.]?)|
                ([Aa]lberta)|([Bb]ritish\s+[Cc]olumbia)|([Mm]anitoba)|([Nn]ew\s+[Bb]runswick)|
                ([Nn]ewfoundland(?:\s+[Aa]nd\s+[Ll]abrador)?)|([Nn]ova\s+[Ss]cotia)|
                ([Nn]orthwest\s+[Tt]erritories)|([Nn]unavut)|([Oo]ntario)|
                ([Pp]rince\s+[Ee]dward\s+[Ii]sland)|([Qq]u[eé]bec)|([Ss]askatchewan)|([Yy]ukon)
            )
        [ \t\n\r]*$",
        )
        .unwrap()
    });

    // Codes corresponding to the capture groups above
    const STATE_PROV_CODES: &[&str] = &[
        "AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DE", "FL", "GA", "HI", "ID", "IL", "IN", "IA",
        "KS", "KY", "LA", "ME", "MD", "MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ",
        "NM", "NY", "NC", "ND", "OH", "OK", "OR", "PA", "RI", "SC", "SD", "TN", "TX", "UT", "VT",
        "VA", "WA", "WV", "WI", "WY", "DC", "AS", "GU", "MP", "PR", "UM", "VI", "AB", "BC", "MB",
        "NB", "NL", "NS", "NT", "NU", "ON", "PE", "QC", "SK", "YT",
    ];

    let input = value.trim();

    if let Some(caps) = STATE_PROV_PATTERN.captures(input) {
        // Find which group matched (starting from group 2, since 1 is the outer group)
        for (idx, code) in STATE_PROV_CODES.iter().enumerate() {
            if caps.get(idx + 2).is_some() {
                return Ok(code.to_string());
            }
        }
    }

    Err(TransformationError::InvalidInput(
        value.to_string(),
        "stateprovnameen: no matching state/province".to_string(),
    ))
}

/// Converts duration days to ISO 8601 duration format
///
/// Handles decimal values with fractional spillover into hours.
/// If the input is not an integer, the fractional part spills into hours.
///
/// ## Examples
/// - "30" → "P30D"
/// - "30.5" → "P30DT12H" (0.5 days = 12 hours)
/// - "365" → "P365D"
/// - "-10.25" → "-P10DT6H"
pub fn dur_day(value: &str) -> Result<String, TransformationError> {
    let (n, sign) = parse_duration_value(value)?;
    let days = n.floor() as i64;
    let hours = ((n - days as f64) * 24.0).floor() as i64;
    format_duration(None, None, Some(days), Some(hours), sign)
}

/// Converts duration months to ISO 8601 duration format
///
/// Handles decimal values with fractional spillover into days.
/// Uses 30.4375 days per month for conversions.
///
/// ## Examples
/// - "12" → "P12M"
/// - "12.5" → "P12M15D" (0.5 months ≈ 15 days)
/// - "6" → "P6M"
/// - "-3.25" → "-P3M7D"
pub fn dur_month(value: &str) -> Result<String, TransformationError> {
    let (n, sign) = parse_duration_value(value)?;
    let months = n.floor() as i64;
    let days = ((n - months as f64) * 30.4375).floor() as i64;
    format_duration(None, Some(months), Some(days), None, sign)
}

/// Converts duration years to ISO 8601 duration format
///
/// Handles decimal values with fractional spillover into months and days.
///
/// ## Examples
/// - "1" → "P1Y"
/// - "1.5" → "P1Y6M" (0.5 years = 6 months)
/// - "2.1" → "P2Y1M9D"
pub fn dur_year(value: &str) -> Result<String, TransformationError> {
    let (n, sign) = parse_duration_value(value)?;
    let years = n.floor() as i64;
    let months_decimal = (n - years as f64) * 12.0;
    let months = months_decimal.floor() as i64;
    let days = ((months_decimal - months as f64) * 30.4375).floor() as i64;
    format_duration(Some(years), Some(months), Some(days), None, sign)
}

/// Converts duration weeks to ISO 8601 duration format
///
/// Converts weeks to days (xs:duration doesn't have weeks).
///
/// ## Examples
/// - "1" → "P7D"
/// - "2.5" → "P17D" (2.5 weeks = 17.5 days, truncated)
pub fn dur_week(value: &str) -> Result<String, TransformationError> {
    let (n, sign) = parse_duration_value(value)?;
    let days = (n * 7.0).floor() as i64;
    format_duration(None, None, Some(days), None, sign)
}

/// Converts duration hours to ISO 8601 duration format
///
/// ## Examples
/// - "24" → "PT24H"
/// - "1.5" → "PT1H" (fractional hours truncated)
pub fn dur_hour(value: &str) -> Result<String, TransformationError> {
    let (n, sign) = parse_duration_value(value)?;
    let hours = n.floor() as i64;
    format_duration(None, None, None, Some(hours), sign)
}

/// Helper to parse a duration value and extract sign
fn parse_duration_value(value: &str) -> Result<(f64, &'static str), TransformationError> {
    static DECIMAL_PATTERN: Lazy<Regex> = Lazy::new(|| {
        Regex::new(r"^[ \t\n\r]*([+-])?([0-9]+(\.[0-9]*)?|\.[0-9]+)[ \t\n\r]*$").unwrap()
    });

    let input = value.trim();
    if let Some(caps) = DECIMAL_PATTERN.captures(input) {
        let sign_str = caps.get(1).map(|m| m.as_str()).unwrap_or("");
        let num_str = caps.get(2).unwrap().as_str();

        let n: f64 = num_str.parse().map_err(|_| {
            TransformationError::InvalidInput(value.to_string(), "duration value".to_string())
        })?;

        let sign = if sign_str == "-" { "-" } else { "" };
        let abs_n = n.abs();

        Ok((abs_n, sign))
    } else {
        Err(TransformationError::InvalidInput(
            value.to_string(),
            "duration value (expected decimal number)".to_string(),
        ))
    }
}

/// Helper to format ISO 8601 duration
fn format_duration(
    years: Option<i64>,
    months: Option<i64>,
    days: Option<i64>,
    hours: Option<i64>,
    sign: &str,
) -> Result<String, TransformationError> {
    // Handle special case: all zeros
    let all_zero = years.unwrap_or(0) == 0
        && months.unwrap_or(0) == 0
        && days.unwrap_or(0) == 0
        && hours.unwrap_or(0) == 0;

    if all_zero {
        // Return P0Y, P0M, P0D, or PT0H depending on which components are present
        if years.is_some() {
            return Ok("P0Y".to_string());
        } else if months.is_some() {
            return Ok("P0M".to_string());
        } else if days.is_some() {
            return Ok("P0D".to_string());
        } else if hours.is_some() {
            return Ok("PT0H".to_string());
        }
        return Ok("P0D".to_string());
    }

    let mut result = format!("{}P", sign);

    // The unit the value was given in is always written, even when the
    // value is under one of them: 0.9 years is `P0Y10M24D`, as EDGAR has it.
    if let Some(y) = years {
        result.push_str(&format!("{}Y", y));
    }

    if let Some(m) = months {
        if m != 0 || years.is_none() {
            result.push_str(&format!("{}M", m));
        }
    }

    if let Some(d) = days {
        if d != 0 || (years.is_none() && months.is_none()) {
            result.push_str(&format!("{}D", d));
        }
    }

    // Add time component if hours present
    if let Some(h) = hours {
        if h != 0 || (years.is_none() && months.is_none() && days.is_none()) {
            result.push_str(&format!("T{}H", h));
        }
    }

    Ok(result)
}

/// Converts entity filer category to standardized format using SEC regex pattern
///
/// Normalizes variations of filer categories to standard strings.
///
/// ## Examples
/// - "Large Accelerated Filer" → "Large Accelerated Filer"
/// - "Non-accelerated Filer" → "Non-accelerated Filer"  
/// - "Non accelerated Filer" → "Non-accelerated Filer"
pub fn entityfilercategoryen(value: &str) -> Result<String, TransformationError> {
    static ENTITY_FILER_PATTERN: Lazy<Regex> = Lazy::new(|| {
        Regex::new(
            r"(?ix)^[ \t\n\r]*
            (
                ([Ll]arge\s+[Aa]ccelerated\s+[Ff]iler)|
                ([Aa]ccelerated\s+[Ff]iler)|
                ([Nn]on[^\w]+[Aa]ccelerated\s+[Ff]iler)
            )
        [ \t\n\r]*$",
        )
        .unwrap()
    });

    const ENTITY_FILER_CODES: &[&str] = &[
        "Large Accelerated Filer",
        "Accelerated Filer",
        "Non-accelerated Filer",
    ];

    let input = value.trim();

    if let Some(caps) = ENTITY_FILER_PATTERN.captures(input) {
        for (idx, code) in ENTITY_FILER_CODES.iter().enumerate() {
            if caps.get(idx + 2).is_some() {
                return Ok(code.to_string());
            }
        }
    }

    Err(TransformationError::InvalidInput(
        value.to_string(),
        "entityfilercategoryen: no matching filer category".to_string(),
    ))
}

/// Converts EDGAR province/country codes to standard format
///
/// ## Examples
/// - "CAYMAN ISLANDS" → "Cayman Islands"
/// - "DELAWARE" → "Delaware"
pub fn edgarprovcountryen(value: &str) -> Result<String, TransformationError> {
    // Title case the input
    let words: Vec<String> = value
        .trim()
        .to_lowercase()
        .split_whitespace()
        .map(|word| {
            let mut chars = word.chars();
            match chars.next() {
                None => String::new(),
                Some(first) => first.to_uppercase().chain(chars).collect(),
            }
        })
        .collect();
    Ok(words.join(" "))
}

/// Converts country names to 2-letter ISO country codes
///
/// Supports 246 countries with many name variations.
/// Based on SEC EDGAR specification using regex capture group indexing.
///
/// ## Examples
/// - "United States" → "US"
/// - "United Kingdom" → "GB"
/// - "People's Republic of China" → "CN"
pub fn countrynameen(value: &str) -> Result<String, TransformationError> {
    // Helper function to find which capture group matched
    fn find_code_index(caps: &regex::Captures) -> Option<usize> {
        // Skip group 0 (full match) and group 1 (outer group)
        for idx in 2..caps.len() {
            if caps.get(idx).is_some() {
                return Some(idx - 2); // Convert to 0-based index
            }
        }
        None
    }

    static COUNTRY_PATTERN: Lazy<Regex> = Lazy::new(|| {
        // This is a simplified version - the full SEC pattern has 246 country patterns
        // Using non-capturing groups (?:...) for optional parts to avoid indexing issues
        Regex::new(r"(?ix)^[ \t\n\r]*(
            ([Aa]fghanistan)|([ÅåAa]land\s+[Ii]slands)|([Aa]lbania)|([Aa]lgeria)|([Aa]merican\s+[Ss]amoa)|
            ([Aa]ndorra)|([Aa]ngola)|([Aa]nguilla)|([Aa]ntarctica)|([Aa]ntigua\s+[Aa]nd\s+[Bb]arbuda)|
            ((?:(?:[Tt]he\s+)?[Rr]epublic\s+[Oo]f\s+)?[Aa]rgentina)|([Aa]rmenia)|([Aa]ruba)|([Aa]ustralia)|
            ([Aa]ustria)|([Aa]zerbaijan)|([Bb]ahamas)|([Bb]ahrain)|([Bb]angladesh)|([Bb]arbados)|
            ([Bb]elarus)|([Bb]elgium)|([Bb]elize)|([Bb]enin)|([Bb]ermuda)|([Bb]hutan)|([Bb]olivia)|
            ([Bb]onaire,\s+[Ss]int\s+[Ee]ustatius\s+[Aa]nd\s+[Ss]aba)|([Bb]osnia\s+[Aa]nd\s+[Hh]erzegovina)|
            ([Bb]otswana)|([Bb]ouvet\s+[Ii]sland)|((?:(?:[Tt]he\s+)?[Ff]ederative\s+[Rr]epublic\s+[Oo]f\s+)?[Bb]ra[sz]il)|
            ([Bb]ritish\s+[Ii]ndian\s+[Oo]cean\s+[Tt]erritory)|([Bb]runei\s+[Dd]arussalam)|([Bb]ulgaria)|
            ([Bb]urkina\s+[Ff]aso)|([Bb]urundi)|([Cc]abo\s+[Vv]erde)|([Cc]ambodia)|([Cc]ameroon)|([Cc]anada)|
            ([Cc]ayman\s+[Ii]slands)|([Cc]entral\s+[Aa]frican\s+[Rr]epublic)|([Cc]had)|([Cc]hile)|
            ((?:(?:[Tt]he\s+)?[Pp]eople['']?s\s+[Rr]epublic\s+[Oo]f\s+)?[Cc]hina)|([Cc]hristmas\s+[Ii]sland)|
            ([Cc]ocos\s+(?:.[Kk]eeling.\s+)?[Ii]slands)|((?:(?:[Tt]he\s+)?[Rr]epublic\s+[Oo]f\s+)?[Cc]olombia)|
            ([Cc]omoros)|([Dd]emocratic\s+[Rr]epublic\s+[Oo]f\s+(?:[Tt]he\s+)?[Cc]ongo)|([Cc]ongo)|
            ([Cc]ook\s+[Ii]slands)|([Cc]osta\s+[Rr]ica)|([Cc][ôo]te\s+d[''][Ii]voire)|([Cc]roatia)|([Cc]uba)|
            ([Cc]ura[çc]ao)|([Cc]yprus)|([Cc]zechia|[Cc]zech\s+[Rr]epublic)|((?:(?:[Tt]he\s+)?[Kk]ingdom\s+[Oo]f\s+)?[Dd]enmark)|
            ([Dd]jibouti)|([Dd]ominica)|([Dd]ominican\s+[Rr]epublic)|([Ee]cuador)|([Ee]gypt)|([Ee]l\s+[Ss]alvador)|
            ([Ee]quatorial\s+[Gg]uinea)|([Ee]ritrea)|([Ee]stonia)|([Ee]swatini)|([Ee]thiopia)|
            ((?:[Tt]he\s+)?[Ff]alkland\s+[Ii]slands(?:\s+.[Mm]alvinas.)?|(?:[Ii]slas\s+)?[Mm]alvinas(?:\s+[Ii]slands)?)|
            ([Ff]aroe\s+[Ii]slands)|([Ff]iji)|([Ff]inland)|([Ff]rance)|([Ff]rench\s+[Gg]uiana)|
            ([Ff]rench\s+[Pp]olynesia)|([Ff]rench\s+[Ss]outhern\s+[Tt]erritories)|([Gg]abon)|([Gg]ambia)|
            ([Gg]eorgia)|([Gg]ermany)|([Gg]hana)|([Gg]ibraltar)|([Gg]reece)|([Gg]reenland)|([Gg]renada)|
            ([Gg]uadeloupe)|([Gg]uam)|([Gg]uatemala)|([Gg]uernsey)|([Gg]uinea)|([Gg]uinea-[Bb]issau)|
            ([Gg]uyana)|([Hh]aiti)|([Hh]eard\s+[Ii]sland\s+[Aa]nd\s+[Mm]cDonald\s+[Ii]slands)|
            ((?:[Tt]he\s+)?[Hh]oly\s+[Ss]ee|[Vv]atican\s+[Cc]ity)|([Hh]onduras)|([Hh]ong\s+[Kk]ong)|
            ([Hh]ungary)|([Ii]celand)|([Ii]ndia)|([Ii]ndonesia)|((?:(?:[Tt]he\s+)?[Ii]slamic\s+[Rr]epublic\s+of\s+)?[Ii]ran)|
            ([Ii]raq)|([Ii]reland)|([Ii]sle\s+[Oo]f\s+[Mm]an)|([Ii]srael)|([Ii]taly)|([Jj]amaica)|([Jj]apan)|
            ([Jj]ersey)|([Jj]ordan)|([Kk]azakhstan)|([Kk]enya)|([Kk]iribati)|
            ((?:[Nn]orth|[Dd]emocratic\s+[Pp]eople['']?s\s+[Rr]epublic\s+[Oo]f)\s+[Kk]orea)|
            ((?:[Ss]outh|[Rr]epublic\s+[Oo]f)\s+[Kk]orea)|([Kk]uwait)|([Kk]yrgyzstan)|
            ([Ll]ao\s+[Pp]eople['']?s\s+[Dd]emocratic\s+[Rr]epublic)|([Ll]atvia)|([Ll]ebanon)|([Ll]esotho)|
            ([Ll]iberia)|((?:(?:[Tt]he\s+)?[Ss]tate\s+[Oo]f\s+)?[Ll]ibya)|([Ll]iechtenstein)|([Ll]ithuania)|
            ((?:(?:[Tt]he\s+)?(?:[Gg]rand\s+)?[Dd]uchy\s+[Oo]f\s+)?[Ll]uxembourg)|([Mm]aca[ou])|([Mm]adagascar)|
            ([Mm]alawi)|([Mm]alaysia)|([Mm]aldives)|([Mm]ali)|([Mm]alta)|
            ((?:(?:[Tt]he\s+)?[Rr]epublic\s+[Oo]f\s+(?:[Tt]he\s+)?)?[Mm]arshall\s+[Ii]slands)|([Mm]artinique)|
            ([Mm]auritania)|([Mm]auritius)|([Mm]ayotte)|([Mm]exico|[Uu]nited\s+[Mm]exican\s+[Ss]tates)|
            ((?:(?:[Tt]he\s+)?[Ff]ederated\s+[Ss]tates\s+[Oo]f\s+)?[Mm]icronesia)|((?:(?:[Tt]he\s+)?[Rr]epublic\s+[Oo]f\s+)?[Mm]oldova)|
            ([Mm]onaco)|([Mm]ongolia)|([Mm]ontenegro)|([Mm]ontserrat)|([Mm]orocco)|([Mm]ozambique)|
            ([Mm]yanmar)|([Nn]amibia)|([Nn]auru)|([Nn]epal)|([Nn]etherlands)|([Nn]ew\s+[Cc]aledonia)|
            ([Nn]ew\s+[Zz]ealand)|([Nn]icaragua)|([Nn]iger)|([Nn]igeria)|([Nn]iue)|([Nn]orfolk\s+[Ii]sland)|
            ((?:(?:[Tt]he\s+)?[Rr]epublic\s+[Oo]f\s+)?[Nn]orth\s+[Mm]acedonia)|([Nn]orthern\s+[Mm]ariana\s+[Ii]slands)|
            ([Nn]orway)|([Oo]man)|([Pp]akistan)|([Pp]alau)|((?:(?:[Tt]he\s+)?[Ss]tate\s+[Oo]f\s+)?[Pp]alestine)|
            ([Pp]anama)|([Pp]apua\s+[Nn]ew\s+[Gg]uinea)|([Pp]araguay)|([Pp]eru)|([Pp]hilippines)|([Pp]itcairn)|
            ([Pp]oland)|([Pp]ortugal)|([Pp]uerto\s+[Rr]ico)|([Qq]atar)|([Rr][ée]union)|([Rr]omania)|
            ([Rr]ussian\s+[Ff]ederation)|([Rr]wanda)|([Ss]aint\s+[Bb]arth[ée]lemy)|
            ([Ss]aint\s+[Hh]elena(?:,\s+[Aa]scension,?\s+[Aa]nd\s+[Tt]ristan(?:\s+[Dd]a\s+[Cc]unha)?)?)|
            ([Ss]aint\s+[Kk]itts\s+[Aa]nd\s+[Nn]evis)|([Ss]aint\s+[Ll]ucia)|([Ss]aint\s+[Mm]artin)|
            ([Ss]aint\s+[Pp]ierre\s+[Aa]nd\s+[Mm]iquelon)|([Ss]aint\s+[Vv]incent(?:\s+[Aa]nd\s+(?:[Tt]he\s+)?[Gg]renadines)?)|
            ([Ss]amoa)|([Ss]an\s+[Mm]arino)|([Ss]ao\s+[Tt]ome\s+[Aa]nd\s+[Pp]rincipe)|([Ss]audi\s+[Aa]rabia)|
            ([Ss]enegal)|([Ss]erbia)|([Ss]eychelles)|([Ss]ierra\s+[Ll]eone)|([Ss]ingapore)|([Ss]int\s+[Mm]aarten)|
            ([Ss]lovakia)|([Ss]lovenia)|([Ss]olomon\s+[Ii]slands)|([Ss]omalia)|
            ((?:(?:[Tt]he\s+)?[Rr]epublic\s+[Oo]f\s+)?[Ss]outh\s+[Aa]frica)|
            ([Ss]outh\s+[Gg]eorgia\s+[Aa]nd\s+(?:[Tt]he\s+)?[Ss]outh\s+[Ss]andwich\s+[Ii]slands)|
            ([Ss]outh\s+[Ss]udan)|((?:(?:[Tt]he\s+)?[Kk]ingdom\s+[Oo]f\s+)?[Ss]pain|[Ee]spa[ñn]a)|
            ([Ss]ri\s+[Ll]anka)|([Ss]udan)|([Ss]uriname)|([Ss]valbard\s+[Aa]nd\s+[Jj]an\s+[Mm]ayen)|
            ([Ss]weden)|([Ss]witzerland)|([Ss]yria(?:n\s+[Aa]rab\s+[Rr]epublic)?)|([Tt]aiwan(?:,?\s+[Pp]rovince\s+[Oo]f\s+[Cc]hina)?)|
            ([Tt]ajikistan)|((?:(?:[Tt]he\s+)?[Uu]nited\s+[Rr]epublic\s+[Oo]f\s+)?[Tt]anzania)|([Tt]hailand)|
            ([Tt]imor-[Ll]este)|([Tt]ogo)|([Tt]okelau)|([Tt]onga)|([Tt]rinidad\s+[Aa]nd\s+[Tt]obago)|
            ([Tt]unisia)|([Tt]urkey)|([Tt]urkmenistan)|([Tt]urks\s+[Aa]nd\s+[Cc]aicos\s+[Ii]slands)|
            ([Tt]uvalu)|([Uu]ganda)|([Uu]kraine)|
            (UAE|[Uu]nited\s+[Aa]rab\s+[Ee]mirates)|
            (U[.]?K[.]?|[Bb]ritain|[Gg]reat\s+[BBb]ritain|[Uu]nited\s+[Kk]ingdom(?:\s+[Oo]f\s+[Gg]reat\s+[Bb]ritain\s+[Aa]nd\s+[Nn]orthern\s+[Ii]reland)?|[Ee]ngland(?:\s+[Aa]nd\s+[Ww]ales)?)|
            ([Uu]nited\s+[Ss]tates\s+[Mm]inor\s+[Oo]utlying\s+[Ii]slands)|
            (U[.]?S[.]?A[.]?|[Uu]nited\s+[Ss]tates(?:\s+[Oo]f\s+[Aa]merica)?)|
            ([Uu]ruguay)|([Uu]zbekistan)|([Vv]anuatu)|([Vv]enezuela)|([Vv]iet\s+[Nn]am)|
            ([Bb]ritish\s+[Vv]irgin\s+[Ii]slands)|([Uu][.]?[Ss][.]?\s+[Vv]irgin\s+[Ii]slands)|
            ([Ww]allis\s+[Aa]nd\s+[Ff]utuna)|([Ww]estern\s+[Ss]ahara)|([Yy]emen)|([Zz]ambia)|([Zz]imbabwe)
        )[ \t\n\r]*$").unwrap()
    });

    // ISO country codes in order matching the regex patterns
    const COUNTRY_CODES: &[&str] = &[
        "AF", "AX", "AL", "DZ", "AS", "AD", "AO", "AI", "AQ", "AG", "AR", "AM", "AW", "AU", "AT",
        "AZ", "BS", "BH", "BD", "BB", "BY", "BE", "BZ", "BJ", "BM", "BT", "BO", "BQ", "BA", "BW",
        "BV", "BR", "IO", "BN", "BG", "BF", "BI", "CV", "KH", "CM", "CA", "KY", "CF", "TD", "CL",
        "CN", "CX", "CC", "CO", "KM", "CD", "CG", "CK", "CR", "CI", "HR", "CU", "CW", "CY", "CZ",
        "DK", "DJ", "DM", "DO", "EC", "EG", "SV", "GQ", "ER", "EE", "SZ", "ET", "FK", "FO", "FJ",
        "FI", "FR", "GF", "PF", "TF", "GA", "GM", "GE", "DE", "GH", "GI", "GR", "GL", "GD", "GP",
        "GU", "GT", "GG", "GN", "GW", "GY", "HT", "HM", "VA", "HN", "HK", "HU", "IS", "IN", "ID",
        "IR", "IQ", "IE", "IM", "IL", "IT", "JM", "JP", "JE", "JO", "KZ", "KE", "KI", "KP", "KR",
        "KW", "KG", "LA", "LV", "LB", "LS", "LR", "LY", "LI", "LT", "LU", "MO", "MG", "MW", "MY",
        "MV", "ML", "MT", "MH", "MQ", "MR", "MU", "YT", "MX", "FM", "MD", "MC", "MN", "ME", "MS",
        "MA", "MZ", "MM", "NA", "NR", "NP", "NL", "NC", "NZ", "NI", "NE", "NG", "NU", "NF", "MK",
        "MP", "NO", "OM", "PK", "PW", "PS", "PA", "PG", "PY", "PE", "PH", "PN", "PL", "PT", "PR",
        "QA", "RE", "RO", "RU", "RW", "BL", "SH", "KN", "LC", "MF", "PM", "VC", "WS", "SM", "ST",
        "SA", "SN", "RS", "SC", "SL", "SG", "SX", "SK", "SI", "SB", "SO", "ZA", "GS", "SS", "ES",
        "LK", "SD", "SR", "SJ", "SE", "CH", "SY", "TW", "TJ", "TZ", "TH", "TL", "TG", "TK", "TO",
        "TT", "TN", "TR", "TM", "TC", "TV", "UG", "UA", "AE", "GB", "UM", "US", "UY", "UZ", "VU",
        "VE", "VN", "VG", "VI", "WF", "EH", "YE", "ZM", "ZW",
    ];

    let input = value.trim();

    if let Some(caps) = COUNTRY_PATTERN.captures(input) {
        if let Some(idx) = find_code_index(&caps) {
            if idx < COUNTRY_CODES.len() {
                return Ok(COUNTRY_CODES[idx].to_string());
            }
        }
    }

    Err(TransformationError::InvalidInput(
        value.to_string(),
        "countrynameen: no matching country".to_string(),
    ))
}

// --- Registries ---

// SEC-specific transformations (ixt-sec)
static IXT_SEC_REGISTRY: Lazy<TransformationRegistry> = Lazy::new(|| {
    let mut m = HashMap::new();
    m.insert("boolballotbox", bool_ballot_box as Transformation);
    m.insert("yesnoballotbox", yesno_ballot_box as Transformation);
    m.insert("numwordsen", num_words_en as Transformation);
    m.insert("durwordsen", dur_words_en as Transformation);
    m.insert("duryear", dur_year as Transformation);
    m.insert("durmonth", dur_month as Transformation);
    m.insert("durweek", dur_week as Transformation);
    m.insert("durday", dur_day as Transformation);
    m.insert("durhour", dur_hour as Transformation);
    m.insert("datequarterend", date_quarter_end as Transformation);
    m.insert("numinf", num_inf as Transformation);
    m.insert("numneginf", num_neg_inf as Transformation);
    m.insert("numnan", num_nan as Transformation);
    m.insert("exchnameen", exchnameen as Transformation);
    m.insert("stateprovnameen", stateprovnameen as Transformation);
    m.insert("countrynameen", countrynameen as Transformation);
    m.insert(
        "entityfilercategoryen",
        entityfilercategoryen as Transformation,
    );
    m.insert("edgarprovcountryen", edgarprovcountryen as Transformation);
    m
});

/// The Transformation Rules Registry (`ixt:`), under the hyphenated names of
/// versions 4 and 5 and the run-together names of versions 1 to 3.
static IXT_REGISTRY: Lazy<TransformationRegistry> = Lazy::new(|| {
    use DatePart::*;

    /// Registers a date rule under each of its names.
    macro_rules! date {
        ($m:ident, $parts:tt, $($name:literal),+) => {
            $($m.insert($name, (|value| read_date(value, $name, &$parts)) as Transformation);)+
        };
    }

    let mut m: TransformationRegistry = HashMap::new();
    for (name, rule) in [
        ("fixed-false", fixed_false as Transformation),
        ("booleanfalse", boolean_false),
        ("fixed-true", fixed_true),
        ("booleantrue", boolean_true),
        ("fixed-zero", fixed_zero),
        ("zero-dash", zero_dash),
        ("zerodash", zero_dash),
        ("fixed-empty", fixed_empty),
        ("nocontent", fixed_empty),
        ("num-dot-decimal", num_dot_decimal),
        ("numdotdecimal", num_dot_decimal),
        ("num-dot-decimal-in", num_dot_decimal),
        ("numdotdecimalin", num_dot_decimal),
        ("num-dot-decimal-apos", num_dot_decimal),
        ("num-comma-decimal", num_comma_decimal),
        ("numcommadecimal", num_comma_decimal),
        ("num-comma-decimal-apos", num_comma_decimal),
        ("num-unit-decimal", num_unit_decimal),
        ("numunitdecimal", num_unit_decimal),
        ("num-unit-decimal-apos", num_unit_decimal),
        ("numunitdecimalin", num_unit_decimal),
        ("date-monthname-day-year-en", date_month_day_year_en),
        ("datemonthdayyearen", date_month_day_year_en),
    ] {
        m.insert(name, rule);
    }

    date!(
        m,
        [Day, MonthName, Year],
        "date-day-monthname-year-en",
        "datedaymonthyearen"
    );
    date!(
        m,
        [Year, MonthName, Day],
        "date-year-monthname-day-en",
        "dateyearmonthdayen"
    );
    date!(
        m,
        [Month, Day, Year],
        "date-month-day-year",
        "datemonthdayyear"
    );
    date!(
        m,
        [Day, Month, Year],
        "date-day-month-year",
        "datedaymonthyear"
    );
    date!(
        m,
        [Year, Month, Day],
        "date-year-month-day",
        "dateyearmonthday"
    );
    date!(
        m,
        [MonthName, Day],
        "date-monthname-day-en",
        "datemonthdayen"
    );
    date!(
        m,
        [Day, MonthName],
        "date-day-monthname-en",
        "datedaymonthen"
    );
    date!(m, [Month, Day], "date-month-day", "datemonthday");
    date!(m, [Day, Month], "date-day-month", "datedaymonth");
    date!(
        m,
        [MonthName, Year],
        "date-monthname-year-en",
        "datemonthyearen"
    );
    date!(
        m,
        [Year, MonthName],
        "date-year-monthname-en",
        "dateyearmonthen"
    );
    date!(m, [Month, Year], "date-month-year", "datemonthyear");
    date!(m, [Year, Month], "date-year-month");
    m
});

/// Applies the transformation a `format` attribute names to the text of an
/// inline fact.
///
/// `format` is `prefix:name`. The prefix chooses the registry — `ixt-sec` for
/// the SEC's, `ixt` for the Transformation Rules Registry, with or without
/// the version suffix some filings add (`ixt4:`).
///
/// A format this module does not know returns the text unchanged. A rule
/// that cannot read the text returns [`TransformationError::InvalidInput`];
/// the parser then keeps the text as the filing shows it.
///
/// ```
/// use xbrlkit::transformations::apply_transformation;
///
/// assert_eq!(apply_transformation("1,000", "ixt:num-dot-decimal").unwrap(), "1000");
/// assert_eq!(apply_transformation("one", "ixt-sec:numwordsen").unwrap(), "1");
/// assert_eq!(apply_transformation("Sept. 30, 2025", "ixt:date-monthname-day-year-en").unwrap(), "2025-09-30");
/// assert_eq!(apply_transformation("December 31", "ixt:date-monthname-day-en").unwrap(), "--12-31");
///
/// // Unknown formats pass through.
/// assert_eq!(apply_transformation("as is", "ixt:not-a-format").unwrap(), "as is");
/// ```
pub fn apply_transformation(value: &str, format: &str) -> Result<String, TransformationError> {
    let Some((prefix, name)) = format.split_once(':') else {
        return Ok(value.to_string());
    };

    let registry = if prefix.starts_with("ixt-sec") {
        &*IXT_SEC_REGISTRY
    } else if prefix.starts_with("ixt") {
        &*IXT_REGISTRY
    } else {
        return Ok(value.to_string());
    };

    match registry.get(name) {
        Some(rule) => rule(value),
        None => Ok(value.to_string()),
    }
}

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

    #[test]
    fn dates_are_read_whatever_separates_their_parts() {
        let date = |value, format| apply_transformation(value, format).unwrap();

        assert_eq!(
            date("December 31, 2025", "ixt:date-monthname-day-year-en"),
            "2025-12-31"
        );
        assert_eq!(
            date("Sept. 30, 2025", "ixt:date-monthname-day-year-en"),
            "2025-09-30"
        );
        assert_eq!(date("DEC 1 2025", "ixt:datemonthdayyearen"), "2025-12-01");
        assert_eq!(
            date("31 December 2025", "ixt:date-day-monthname-year-en"),
            "2025-12-31"
        );
        assert_eq!(
            date("30th of June, 2026", "ixt:date-day-monthname-year-en"),
            "2026-06-30"
        );
        assert_eq!(date("9/21/2018", "ixt:date-month-day-year"), "2018-09-21");
        assert_eq!(date("12/1/23", "ixt:date-month-day-year"), "2023-12-01");
        assert_eq!(date("21.09.2018", "ixt:date-day-month-year"), "2018-09-21");
        assert_eq!(date("2018/09/21", "ixt:date-year-month-day"), "2018-09-21");
    }

    #[test]
    fn a_date_without_a_year_or_a_day_is_a_partial_date() {
        let date = |value, format| apply_transformation(value, format).unwrap();

        assert_eq!(date("December 31", "ixt:date-monthname-day-en"), "--12-31");
        assert_eq!(date("31 Dec", "ixt:date-day-monthname-en"), "--12-31");
        assert_eq!(date("12-31", "ixt:date-month-day"), "--12-31");
        assert_eq!(date("1/31", "ixt:date-month-day"), "--01-31");
        assert_eq!(date("31/1", "ixt:date-day-month"), "--01-31");
        assert_eq!(date("February 29", "ixt:date-monthname-day-en"), "--02-29");
        assert_eq!(
            date("January 2028", "ixt:date-monthname-year-en"),
            "2028-01"
        );
        assert_eq!(
            date("2028 January", "ixt:date-year-monthname-en"),
            "2028-01"
        );
        assert_eq!(date("06/2027", "ixt:date-month-year"), "2027-06");
    }

    #[test]
    fn text_that_is_not_the_date_a_format_expects_is_refused() {
        for (value, format) in [
            ("as of December 31, 2025", "ixt:date-monthname-day-year-en"),
            ("December 2025", "ixt:date-monthname-day-year-en"),
            ("Smarch 31, 2025", "ixt:date-monthname-day-year-en"),
            ("February 30, 2025", "ixt:date-monthname-day-year-en"),
            ("February 29, 2025", "ixt:date-monthname-day-year-en"),
            ("13/31/2025", "ixt:date-month-day-year"),
            ("12/31/202", "ixt:date-month-day-year"),
            ("", "ixt:date-month-day"),
        ] {
            assert!(
                apply_transformation(value, format).is_err(),
                "{value:?} should not read as {format}"
            );
        }
        // A leap day is a day in a leap year.
        assert_eq!(
            apply_transformation("February 29, 2024", "ixt:date-monthname-day-year-en").unwrap(),
            "2024-02-29"
        );
    }

    #[test]
    fn numbers_lose_their_separators_under_either_convention() {
        let number = |value, format| apply_transformation(value, format).unwrap();

        assert_eq!(number("1,234,567.89", "ixt:num-dot-decimal"), "1234567.89");
        assert_eq!(number("1 234 567.89", "ixt:numdotdecimal"), "1234567.89");
        assert_eq!(number("1,00,000.5", "ixt:num-dot-decimal-in"), "100000.5");
        assert_eq!(number("1'234.5", "ixt:num-dot-decimal-apos"), "1234.5");
        assert_eq!(
            number("1.234.567,89", "ixt:num-comma-decimal"),
            "1234567.89"
        );
        assert_eq!(number("1 234,5", "ixt:numcommadecimal"), "1234.5");
        assert_eq!(number("3 dollars 50 cents", "ixt:num-unit-decimal"), "3.50");
        assert_eq!(
            number("1,234 dollars and 5 cents", "ixt:num-unit-decimal"),
            "1234.05"
        );
        assert_eq!(number("anything", "ixt:fixed-empty"), "");
    }

    #[test]
    fn a_registry_prefix_may_carry_its_version() {
        assert_eq!(
            apply_transformation("1,000", "ixt4:num-dot-decimal").unwrap(),
            "1000"
        );
        assert_eq!(
            apply_transformation("one", "ixt-sec1:numwordsen").unwrap(),
            "1"
        );
        assert_eq!(
            apply_transformation("1,000", "other:num-dot-decimal").unwrap(),
            "1,000"
        );
        assert_eq!(
            apply_transformation("1,000", "num-dot-decimal").unwrap(),
            "1,000"
        );
    }

    #[test]
    fn a_duration_under_one_year_still_states_its_years() {
        assert_eq!(dur_year("0.9").unwrap(), "P0Y10M24D");
        assert_eq!(dur_year("0.1").unwrap(), "P0Y1M6D");
        assert_eq!(dur_year("2.25").unwrap(), "P2Y3M");
        assert_eq!(dur_year("10").unwrap(), "P10Y");
        assert_eq!(dur_year("0").unwrap(), "P0Y");
    }

    #[test]
    fn test_bool_ballot_box() {
        assert_eq!(bool_ballot_box("☐").unwrap(), "false");
        assert_eq!(bool_ballot_box("☑").unwrap(), "true");
        assert_eq!(bool_ballot_box("☒").unwrap(), "true");
        assert!(bool_ballot_box("invalid").is_err());
    }

    #[test]
    fn test_num_words_en_simple() {
        assert_eq!(num_words_en("one").unwrap(), "1");
        assert_eq!(num_words_en("zero").unwrap(), "0");
        assert_eq!(num_words_en("twelve").unwrap(), "12");
        assert_eq!(num_words_en("ninety nine").unwrap(), "99");

        // Test special cases that map to zero (matching Python's numwordsNoPattern)
        assert_eq!(num_words_en("no").unwrap(), "0");
        assert_eq!(num_words_en("none").unwrap(), "0");
        assert_eq!(num_words_en("nil").unwrap(), "0");
        assert_eq!(num_words_en("No").unwrap(), "0");
        assert_eq!(num_words_en("NONE").unwrap(), "0");
        assert_eq!(num_words_en("Nil").unwrap(), "0");
    }

    #[test]
    fn test_num_words_en_complex() {
        assert_eq!(num_words_en("seventy thousand and one").unwrap(), "70001");
        assert_eq!(num_words_en("nineteen hundred forty-four").unwrap(), "1944");
        assert_eq!(
            num_words_en("six million four hundred thousand five").unwrap(),
            "6400005"
        );
    }

    #[test]
    fn test_dur_words_en() {
        // Basic tests
        assert_eq!(dur_words_en("9 years, 2 months").unwrap(), "P9Y2M");
        assert_eq!(dur_words_en("Five years, two months").unwrap(), "P5Y2M");
        assert_eq!(
            dur_words_en("three years four months no days").unwrap(),
            "P3Y4M"
        );

        // Test with "and"
        assert_eq!(dur_words_en("5 years and 3 months").unwrap(), "P5Y3M");
        assert_eq!(
            dur_words_en("10 years, 6 months and 15 days").unwrap(),
            "P10Y6M15D"
        );

        // Test "no", "zero", "none", "nil" as zero values
        assert_eq!(dur_words_en("no years, 5 months").unwrap(), "P5M");
        assert_eq!(
            dur_words_en("zero years, zero months, 10 days").unwrap(),
            "P10D"
        );
        assert_eq!(dur_words_en("none years, 3 months").unwrap(), "P3M");
        assert_eq!(
            dur_words_en("nil years, nil months, 7 days").unwrap(),
            "P7D"
        );

        // Test Unicode dashes (Armenian hyphen U+058A)
        assert_eq!(dur_words_en("3֊years").unwrap(), "P3Y");
        // Hebrew maqaf (U+05BE)
        assert_eq!(dur_words_en("2־months").unwrap(), "P2M");
        // En dash (U+2013)
        assert_eq!(dur_words_en("5–years").unwrap(), "P5Y");
        // Em dash (U+2014)
        assert_eq!(dur_words_en("7—months").unwrap(), "P7M");
        // Small em dash (U+FE58)
        assert_eq!(dur_words_en("4﹘days").unwrap(), "P4D");
        // Fullwidth hyphen-minus (U+FF0D)
        assert_eq!(dur_words_en("9-years").unwrap(), "P9Y");

        // Test all zeros returns P0D
        assert_eq!(dur_words_en("no years, no months, no days").unwrap(), "P0D");
        assert_eq!(dur_words_en("zero years").unwrap(), "P0D");
    }

    #[test]
    fn test_num_dot_decimal() {
        assert_eq!(num_dot_decimal("1,000,000").unwrap(), "1000000");
        assert_eq!(num_dot_decimal("123,456.789").unwrap(), "123456.789");
        assert_eq!(num_dot_decimal("42").unwrap(), "42");
    }

    #[test]
    fn test_zero_dash() {
        // Standard hyphen-minus
        assert_eq!(zero_dash("-").unwrap(), "0");

        // Em dash
        assert_eq!(zero_dash("—").unwrap(), "0");

        // En dash
        assert_eq!(zero_dash("–").unwrap(), "0");

        // With whitespace
        assert_eq!(zero_dash("  -  ").unwrap(), "0");
        assert_eq!(zero_dash("\t-\t").unwrap(), "0");

        // Non-dash values should pass through
        assert_eq!(zero_dash("123").unwrap(), "123");
        assert_eq!(zero_dash("0").unwrap(), "0");
        assert_eq!(zero_dash("  456  ").unwrap(), "456"); // trimmed
    }

    #[test]
    fn test_apply_transformation() {
        assert_eq!(
            apply_transformation("one", "ixt-sec:numwordsen").unwrap(),
            "1"
        );
        assert_eq!(
            apply_transformation("☐", "ixt-sec:boolballotbox").unwrap(),
            "false"
        );
        assert_eq!(
            apply_transformation("1,000", "ixt:num-dot-decimal").unwrap(),
            "1000"
        );
        // Unknown transformation should pass through
        assert_eq!(
            apply_transformation("value", "unknown:transform").unwrap(),
            "value"
        );
    }

    #[test]
    fn test_boolean_transformations() {
        assert_eq!(boolean_false("anything").unwrap(), "false");
        assert_eq!(boolean_true("anything").unwrap(), "true");
        assert_eq!(
            apply_transformation("x", "ixt:booleanfalse").unwrap(),
            "false"
        );
        assert_eq!(
            apply_transformation("x", "ixt:booleantrue").unwrap(),
            "true"
        );
    }

    #[test]
    fn test_exchnameen() {
        assert_eq!(exchnameen("New York Stock Exchange").unwrap(), "NYSE");
        assert_eq!(exchnameen("The New York Stock Exchange").unwrap(), "NYSE");
        assert_eq!(exchnameen("The NYSE").unwrap(), "NYSE");
        assert_eq!(
            exchnameen("The NASDAQ Stock Market, LLC").unwrap(),
            "NASDAQ"
        );
        assert_eq!(exchnameen("NASDAQ Stock Market").unwrap(), "NASDAQ");
        assert_eq!(exchnameen("Cboe BZX Exchange, Inc.").unwrap(), "CboeBZX");
        // Test that invalid exchanges fail
        assert!(exchnameen("Other Exchange").is_err());
    }

    #[test]
    fn test_date_month_day_year_en() {
        assert_eq!(
            date_month_day_year_en("August 22, 2025").unwrap(),
            "2025-08-22"
        );
        assert_eq!(
            date_month_day_year_en("November 29, 2021").unwrap(),
            "2021-11-29"
        );
        assert_eq!(
            date_month_day_year_en("January 1, 2020").unwrap(),
            "2020-01-01"
        );
        assert_eq!(
            date_month_day_year_en("December 31, 2023").unwrap(),
            "2023-12-31"
        );
        // Test both registry names
        assert_eq!(
            apply_transformation("August 22, 2025", "ixt:date-monthname-day-year-en").unwrap(),
            "2025-08-22"
        );
        assert_eq!(
            apply_transformation("August 22, 2025", "ixt:datemonthdayyearen").unwrap(),
            "2025-08-22"
        );
    }

    #[test]
    fn test_stateprovnameen() {
        assert_eq!(stateprovnameen("Utah").unwrap(), "UT");
        assert_eq!(stateprovnameen("Delaware").unwrap(), "DE");
        assert_eq!(stateprovnameen("California").unwrap(), "CA");
        assert_eq!(stateprovnameen("New York").unwrap(), "NY");
        // Canadian provinces
        assert_eq!(stateprovnameen("Ontario").unwrap(), "ON");
        assert_eq!(stateprovnameen("British Columbia").unwrap(), "BC");
        assert_eq!(stateprovnameen("Quebec").unwrap(), "QC");
        assert_eq!(stateprovnameen("Québec").unwrap(), "QC");
        // Territories
        assert_eq!(stateprovnameen("Puerto Rico").unwrap(), "PR");
        // Test that invalid state names fail
        assert!(stateprovnameen("Cayman Islands").is_err());
    }

    #[test]
    fn test_dur_day() {
        assert_eq!(dur_day("30").unwrap(), "P30D");
        assert_eq!(dur_day("365").unwrap(), "P365D");
        assert_eq!(dur_day("1").unwrap(), "P1D");
        assert_eq!(dur_day("30.5").unwrap(), "P30DT12H");
    }

    #[test]
    fn test_dur_month() {
        assert_eq!(dur_month("12").unwrap(), "P12M");
        assert_eq!(dur_month("6").unwrap(), "P6M");
        assert_eq!(dur_month("1").unwrap(), "P1M");
        assert_eq!(dur_month("12.5").unwrap(), "P12M15D");
    }

    #[test]
    fn test_entityfilercategoryen() {
        assert_eq!(
            entityfilercategoryen("Large Accelerated Filer").unwrap(),
            "Large Accelerated Filer"
        );
        assert_eq!(
            entityfilercategoryen("  Non-accelerated Filer  ").unwrap(),
            "Non-accelerated Filer"
        );
    }

    #[test]
    fn test_edgarprovcountryen() {
        assert_eq!(
            edgarprovcountryen("CAYMAN ISLANDS").unwrap(),
            "Cayman Islands"
        );
        assert_eq!(edgarprovcountryen("DELAWARE").unwrap(), "Delaware");
        assert_eq!(edgarprovcountryen("NEW YORK").unwrap(), "New York");
    }

    #[test]
    fn test_numdotdecimal_alias() {
        // Test that both spellings work
        assert_eq!(
            apply_transformation("1,234.56", "ixt:num-dot-decimal").unwrap(),
            "1234.56"
        );
        assert_eq!(
            apply_transformation("1,234.56", "ixt:numdotdecimal").unwrap(),
            "1234.56"
        );
    }

    #[test]
    fn test_date_quarter_end() {
        // Q notation
        assert_eq!(date_quarter_end("Q1 2023").unwrap(), "2023-03-31");
        assert_eq!(date_quarter_end("Q2 2023").unwrap(), "2023-06-30");
        assert_eq!(date_quarter_end("Q3 2023").unwrap(), "2023-09-30");
        assert_eq!(date_quarter_end("Q4 2023").unwrap(), "2023-12-31");

        // Number notation
        assert_eq!(date_quarter_end("1 2023").unwrap(), "2023-03-31");
        assert_eq!(date_quarter_end("2 2023").unwrap(), "2023-06-30");
        assert_eq!(date_quarter_end("3 2023").unwrap(), "2023-09-30");
        assert_eq!(date_quarter_end("4 2023").unwrap(), "2023-12-31");

        // Word notation
        assert_eq!(date_quarter_end("first 2023").unwrap(), "2023-03-31");
        assert_eq!(date_quarter_end("second 2023").unwrap(), "2023-06-30");
        assert_eq!(date_quarter_end("third 2023").unwrap(), "2023-09-30");
        assert_eq!(date_quarter_end("fourth 2023").unwrap(), "2023-12-31");
        assert_eq!(date_quarter_end("last 2023").unwrap(), "2023-12-31");

        // Reverse order (year first)
        assert_eq!(date_quarter_end("2023 Q2").unwrap(), "2023-06-30");
        assert_eq!(date_quarter_end("2023 second").unwrap(), "2023-06-30");
        assert_eq!(date_quarter_end("2023 3").unwrap(), "2023-09-30");
    }

    #[test]
    fn test_yesno_ballot_box() {
        assert_eq!(yesno_ballot_box("☐").unwrap(), "No");
        assert_eq!(yesno_ballot_box("☑").unwrap(), "Yes");
        assert_eq!(yesno_ballot_box("☒").unwrap(), "Yes");
        assert!(yesno_ballot_box("invalid").is_err());
        assert!(yesno_ballot_box("").is_err());
    }

    #[test]
    fn test_special_floats() {
        assert_eq!(num_inf("anything").unwrap(), "INF");
        assert_eq!(num_neg_inf("anything").unwrap(), "-INF");
        assert_eq!(num_nan("anything").unwrap(), "NaN");

        // Test via registry
        assert_eq!(apply_transformation("x", "ixt-sec:numinf").unwrap(), "INF");
        assert_eq!(
            apply_transformation("x", "ixt-sec:numneginf").unwrap(),
            "-INF"
        );
        assert_eq!(apply_transformation("x", "ixt-sec:numnan").unwrap(), "NaN");
    }

    #[test]
    fn test_countrynameen() {
        // Major countries
        assert_eq!(countrynameen("United States").unwrap(), "US");
        assert_eq!(countrynameen("United States of America").unwrap(), "US");
        assert_eq!(countrynameen("U.S.A.").unwrap(), "US");
        assert_eq!(countrynameen("USA").unwrap(), "US");

        assert_eq!(countrynameen("United Kingdom").unwrap(), "GB");
        assert_eq!(countrynameen("U.K.").unwrap(), "GB");
        assert_eq!(countrynameen("Britain").unwrap(), "GB");
        assert_eq!(countrynameen("Great Britain").unwrap(), "GB");
        assert_eq!(countrynameen("England").unwrap(), "GB");

        assert_eq!(countrynameen("China").unwrap(), "CN");
        assert_eq!(countrynameen("People's Republic of China").unwrap(), "CN");

        assert_eq!(countrynameen("Canada").unwrap(), "CA");
        assert_eq!(countrynameen("Germany").unwrap(), "DE");
        assert_eq!(countrynameen("France").unwrap(), "FR");
        assert_eq!(countrynameen("Japan").unwrap(), "JP");
        assert_eq!(countrynameen("Australia").unwrap(), "AU");
        assert_eq!(countrynameen("Brazil").unwrap(), "BR");
        assert_eq!(countrynameen("India").unwrap(), "IN");

        // Countries with special characters
        assert_eq!(countrynameen("Côte d'Ivoire").unwrap(), "CI");
        assert_eq!(countrynameen("Curaçao").unwrap(), "CW");
        assert_eq!(countrynameen("Réunion").unwrap(), "RE");

        // Countries with long official names
        assert_eq!(countrynameen("The Republic of Argentina").unwrap(), "AR");
        assert_eq!(countrynameen("Argentina").unwrap(), "AR");
        assert_eq!(
            countrynameen("The Federative Republic of Brazil").unwrap(),
            "BR"
        );

        // Test via registry
        assert_eq!(
            apply_transformation("United States", "ixt-sec:countrynameen").unwrap(),
            "US"
        );

        // Test invalid country
        assert!(countrynameen("Atlantis").is_err());
    }
}