num2words2-core 0.1.3

Number-to-words conversion for 120+ languages (Rust port of num2words). 42 -> forty-two.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
//! Port of `lang_DV.py` (Dhivehi / Maldivian).
//!
//! Shape: **self-contained**. `Num2Word_DV` inherits from nothing — it is a
//! bare `class Num2Word_DV:` with no base class at all, so `base.py`'s engine
//! (`splitnum`/`clean`/`merge`/`set_high_numwords` on `Num2Word_Base`) is
//! never involved. Every trait method here is an override; `cards()`,
//! `maxval()` and `merge()` stay at their `Lang` defaults and are unused.
//!
//! Note that `Num2Word_DV` defines its *own* `cards`, `MAXVAL` and
//! `set_high_numwords` that merely share names with `base.py`'s — they are
//! unrelated tables driving the module's own `convert_int`. They are modelled
//! as private fields/consts below rather than through the `Lang` trait, to
//! avoid the engine accidentally picking them up.
//!
//! # The numbering system
//!
//! Dhivehi groups digits Indian-style: units take 3 digits, then thousands
//! take 2 (`ހާސް`), then lakh takes 1 (`ލައްކަ`), and everything above that
//! reverts to Western 3-digit groups (million, billion, ... nonillion). That
//! is exactly what `self.grouping` encodes:
//!
//! ```text
//! [-3, -5, -6, -9, -12, -15, -18, -21, -24, -27, -30, -33, -36]
//! ```
//!
//! `convert_int` pairs `[len(digits)] + grouping` pairwise into `(end, start)`
//! and slices `digits_str[start:end]`, yielding
//! `parts[0] = last 3 digits`, `parts[1] = digits[-5:-3]` (thousands),
//! `parts[2] = digits[-6:-5]` (lakh), `parts[3] = digits[-9:-6]` (million), …
//! `parts[1..]` is then `zip`ped against `reversed(self.cards.items())`, i.e.
//! the multiplier words in ascending order. `zip` stops at the shorter side,
//! so `parts[12]` (`digits[-36:-33]`) is never consumed — unreachable anyway,
//! since MAXVAL caps input at 33 digits.
//!
//! # Stem vs nominal
//!
//! Every numeral has two forms: a *stem* (bound/attributive, `base_stem`) and
//! a *nominal* (free-standing, `base_nominal`). Cardinals end in the nominal
//! form, ordinals in the stem form — that is the whole of the `nominal` flag
//! threaded through `convert_int`. So `to_cardinal(3)` is `ތިނެއް` while
//! `to_ordinal(3)` is `ތިން ވަނަ`.
//!
//! # Faithfully reproduced Python quirks
//!
//! This is a port, not a rewrite. All of the following are verified against
//! the interpreter and against `bench/corpus.jsonl`:
//!
//! 1. **Negative cardinals emit a double space.** When `part_words` is empty
//!    (any |value| < 1000 with a non-zero last group) `convert_int` returns
//!    `"".join([]) + " " + word`, i.e. a string with a *leading* space. The
//!    non-negative path launders this via `result.strip()`, but the `sign == 1`
//!    path does `" ".join([negword, result])` with **no strip**, so
//!    `to_cardinal(-1)` == `"މައިނަސް  އެކެއް"` — two spaces. `to_cardinal(-1000)`
//!    has only one, because `parts[0] == "000"` takes the early `int(parts[0])
//!    == 0` return, which has no leading space. Reproduced in
//!    [`LangDv::to_cardinal_float`].
//!
//! 2. **`convert_three2nominal` mixes stem and nominal for hundreds.** The
//!    `x00` branch uses `convert_two2nominal(digits_str[0])` while the `xyz`
//!    branch uses `convert_two2stem(digits_str[0])`. So cardinal 300 is
//!    `ތިނެއްސަތޭކަ` (*nominal* three + hundred) but cardinal 555 is
//!    `ފަސްސަތޭކަ ފަންސާސްފަހެއް` (*stem* five + hundred). Almost certainly a
//!    typo for `convert_two2stem`, but it is what Python emits.
//!
//! 3. **Hundreds spacing is asymmetric.** 100s and 200s concatenate with no
//!    separator (`ސަތޭކަ` + tail), while 300–900 insert a space before the tail
//!    (`convert_two2stem(d0) + base_stem[100] + " " + tail`). Hence 101 →
//!    `ސަތޭކައެކެއް` (no space) but 555 → `ފަސްސަތޭކަ ފަންސާސްފަހެއް` (space).
//!
//! 4. **The overflow bound is not `MAXVAL`.** `MAXVAL` is 10^33, but the guard
//!    reads
//!
//!    ```python
//!    if Decimal(self.MAXVAL).compare(abs(decimal_value).to_integral(ROUND_FLOOR)) < 1:
//!    ```
//!
//!    and `Decimal.__abs__` is a **context operation**: it rounds to the
//!    default context precision of 28 significant digits with ROUND_HALF_EVEN.
//!    (`__init__` has `getcontext().prec = 34` sitting commented out, so this
//!    is a latent bug the author half-noticed.) A 33-digit input is therefore
//!    rounded *up* to 10^33 before the comparison, and `compare(...) < 1` means
//!    `MAXVAL <= rounded`, so it raises. The true threshold is
//!    `abs(value) >= 10^33 - 50000`: `to_cardinal(10**33 - 50001)` succeeds but
//!    `to_cardinal(10**33 - 50000)` raises `OverflowError` (the tie rounds to
//!    even, i.e. up). `ROUND_FLOOR` on `to_integral` is a red herring — `abs`
//!    has already made the value integral, so `to_integral` is a no-op.
//!    Modelled by [`round_half_even_28`]. Crucially the *conversion* still uses
//!    the exact digits — only the guard sees the rounded value.
//!
//! 5. `to_ordinal`/`to_ordinal_num` raise `TypeError` (not ValueError) for any
//!    negative input, via `verify_ordinal`. `to_cardinal` is unaffected.
//!
//! # Hazard: the overflow bound depends on *global* interpreter state
//!
//! [`CTX_PREC`] is pinned to 28 — the pristine `decimal` default, and the
//! value the frozen corpus was generated under. But `getcontext()` is global
//! (thread-local) mutable state, and `lang_AR.py:408` mutates it and never
//! restores it:
//!
//! ```python
//! except decimal.InvalidOperation:
//!     decimal.getcontext().prec = len(temp_number_dec.as_tuple().digits)
//! ```
//!
//! That handler fires for any input with more digits than the current
//! precision, so a single `Num2Word_AR().to_cardinal(10**33 - 1)` earlier in
//! the *same process* raises the global precision to 33 — after which
//! `Num2Word_DV().to_cardinal(10**33 - 1)` stops raising `OverflowError` and
//! happily returns a string. Same object, same input, different answer,
//! depending on whether an unrelated language ran first.
//!
//! This port is deliberately order-independent and reproduces the pristine
//! (prec == 28) behaviour. If a differential harness ever runs AR-then-DV in
//! one interpreter, Python — not this file — is what changed.
//!
//! # Currency
//!
//! `to_currency` shares nothing with `base.py`'s. The signature is
//!
//! ```python
//! def to_currency(self, value, currency="ރުފިޔާ", cents="ލާރި"):
//! ```
//!
//! — `currency` and `cents` are **words**, not an ISO code and a verbosity
//! flag. `Num2Word_DV` has no `CURRENCY_FORMS`, no `CURRENCY_PRECISION`, no
//! `pluralize`, and no `separator`/`adjective` kwargs, so those trait hooks all
//! stay at their defaults and are never consulted.
//!
//! The dispatcher passes `currency=<ISO code>` straight through, and DV
//! interpolates whatever it is given **verbatim** as the unit word: there is no
//! lookup, so `to_currency(1, currency="EUR")` is `"އެއް EUR"` and no code can
//! ever raise `NotImplementedError`. Every code is "supported", which is
//! exactly what the corpus records for all nine it tries. Omitting `currency=`
//! instead yields the class's own default word — `to_currency(1)` is
//! `"އެއް ރުފިޔާ"` (rufiyaa), the real Maldivian unit — which is what the
//! generated [`Lang::default_currency`] override carries; the binding resolves
//! it before `to_currency` runs, so the `&str` arriving here is already right.
//!
//! Continuing the quirk list above, all verified against the interpreter:
//!
//! 6. **Cents use ROUND_HALF_EVEN and go negative.** `int_part` is
//!    `value.to_integral_value()` — round to *nearest*, ties to even — not
//!    floor, and `frac_part` is `(value - int_part) * 100` after the same
//!    rounding. So 99.99 rounds **up** to 100 and leaves `frac_part == -1`,
//!    printing `"ސަތޭކަ EUR މައިނަސް  އެއް ލާރި"`: "one hundred EUR **minus** one
//!    laari", carrying quirk 1's double space along with it (`to_cardinal_float`
//!    is what renders that -1). 1234.56 likewise becomes 1235 EUR minus 44
//!    laari. And 0.5 ties to even, so `int_part` is 0 and it prints "fifty
//!    laari" with no unit word at all.
//!
//! 7. **Either segment vanishes when its part is zero.** Both are guarded by a
//!    bare truthiness test on a `Decimal`, so 0.01 is `"އެއް ލާރި"` (no unit
//!    word) and 1.0 is `"އެއް EUR"` (no cents). When both parts round to zero
//!    but the value itself is non-zero — 0.001, say — `" ".join([])` yields the
//!    **empty string**.
//!
//! 8. **A positive Decimal exponent survives `to_integral_value`, so large
//!    floats collapse to their coefficient.** `to_integral_value` returns a
//!    value whose exponent is `>= 0` *unchanged*, and `to_cardinal_float` then
//!    reads `as_tuple().digits` — the coefficient alone. `str(1e21)` is
//!    `'1e+21'`, i.e. `Decimal('1E+21')` with digits `(1,)` and exponent 21, so
//!    `to_currency(1e21)` renders **`"އެއް EUR"`** — "one EUR". The exponent is
//!    silently dropped. Only the float path can reach this: `Decimal(int)`
//!    always has exponent 0, which is why the verified integer modes are
//!    immune. Modelled by keeping the currency path on `BigDecimal` and reading
//!    its `(coefficient, exponent)` rather than flattening to a `BigInt` — see
//!    [`LangDv::to_cardinal_float_dec`].
//!
//! `to_cheque` does not exist on the class at all, so it surfaces as
//! `AttributeError` from the dispatcher's `getattr`, not as the
//! `NotImplementedError` that `default_to_cheque` would produce.
//!
//! # Float/Decimal routing
//!
//! DV has no whole-value fast path: `to_cardinal(5.0)` goes through
//! `Decimal(str(5.0))` == `Decimal('5.0')`, whose `as_tuple()` has exponent
//! -1, so the pointword branch runs and the result is "five point zero"
//! (`ފަހެއް ޕޮއިންޓް ސުމެއް`). [`Lang::cardinal_float_entry`] is therefore
//! overridden to bypass the base's whole -> int routing entirely, and the
//! ordinal/year entries follow the class's own methods. More reproduced
//! quirks, all corpus-verified:
//!
//! 9.  **`str(float)`'s scientific regime collapses to the coefficient.**
//!     `str(1e16)` is `'1e+16'`, so `Decimal(str(1e16))` has digits `(1,)`
//!     and exponent 16 — and `convert_int` only ever sees the digit tuple, so
//!     `to_cardinal(1e16)` is `އެކެއް` ("one"). Same for `Decimal('1E+2')` ->
//!     "one". Reconstructed in [`py_float_dec_tuple`] from Rust's
//!     shortest-round-trip digits (`{:e}`), which match `repr(float)`'s
//!     digits by uniqueness of the shortest representation; the regime
//!     boundary (scientific iff adjusted exponent >= 16 or < -4) is
//!     CPython's `float_repr_style` cutoff.
//! 10. **Whole floats keep their `.0`.** A fixed-point repr of an integral
//!     float appends ".0", giving the Decimal a trailing zero digit and
//!     exponent -1 — hence the trailing `ސުމެއް`/`ސުން` after the pointword
//!     in every `N.0` row.
//! 11. **`cardinal(0.0)`, `cardinal(-0.0)` and `cardinal(".5")` raise
//!     IndexError**: `digits[:exponent]` is empty and `convert_int` dies on
//!     `parts[0]` — before the sign is even looked at, which is why `-0.0`
//!     raises rather than printing a negword.
//! 12. **`verify_ordinal` raises TypeError for non-integral floats first**,
//!     then for negatives (also TypeError); `-0.0` passes both checks
//!     (`-0.0 == int(-0.0)`, `abs(-0.0) == -0.0`) and dies later with
//!     cardinal's IndexError — except in `to_ordinal_num`, which happily
//!     formats it as `-0.0 ވަނަ`.
//! 13. **Ordinal floats mix nominal and stem.** `to_cardinal_float(value,
//!     nominal=False)` hardcodes the *integer* part nominal — Python calls
//!     `convert_int(digits[:exponent])` with the default — while the
//!     fractional digits follow the flag as stems: `to_ordinal(1.0)` is
//!     `އެކެއް ޕޮއިންޓް ސުން ވަނަ` (nominal one, stem zero).
//! 14. **`to_year` in [1100, 2000) splits float years absurdly**:
//!     `to_year(1234.0)` computes `high, low = value // 100, value % 100` ==
//!     `12.0, 34.0` (both still floats!) and renders "twelve point zero
//!     hundred thirty-four point zero". Negative years go through `abs()`
//!     *before* the cardinal, so no negword and no double space:
//!     `to_year(-1.5)` == `އެކެއް ޕޮއިންޓް ފަހެއް ބީ.ސީ`.
//!
//! # Strings
//!
//! `str_to_number` is `to_decimal`, which turns `InvalidOperation` into
//! `TypeError("{} is not a valid value.")` — that is the whole override.
//! One deliberate shortcut: Python parses `"NaN"` into `Decimal('NaN')`
//! successfully and only raises later, when `to_cardinal_float`'s overflow
//! guard evaluates `Decimal(MAXVAL).compare(NaN) < 1` (ordered comparison
//! with a NaN Decimal -> `decimal.InvalidOperation`). The pyo3 shim
//! hardcodes `ParsedNumber::NaN -> ValueError` before any DV hook could
//! run, so this port raises the InvalidOperation from `str_to_number`
//! itself — the same observable exception for every corpus row ("NaN" only
//! appears under `to='cardinal'`). The one place the shortcut is visibly
//! unfaithful is `to_ordinal("NaN")`, where genuine Python raises
//! ValueError from `int(Decimal('NaN'))` — a row no corpus exercises.
//!
//! # Fraction
//!
//! `Num2Word_DV` has no `to_fraction` — like `to_cheque`, the dispatcher's
//! attribute lookup fails, so every fraction-corpus row and every "n/d"
//! string (whatever `to=` says) is `AttributeError`, including `"1/0"`,
//! which dies on lookup before any division could raise ZeroDivisionError.
//! Known gap: `to='fraction'` with a *plain* numeric string ("5", "1.5")
//! cannot be reproduced from this file — the pyo3 shim's `dec_mode`
//! hardcodes the base-class TypeError (`to_fraction() missing 1 required
//! positional argument`) for that combination and never consults the
//! language, while Python raises AttributeError on the `getattr`.
//!
//! # Grammatical kwargs
//!
//! `to_cardinal(value, nominal=True)` is the only extra cardinal kwarg;
//! Python tests it with bare truthiness (`if not nominal`), so False, 0,
//! None and "" all select the stem form. `to_year`'s `suffix=""` rides
//! `to_year_kw`; a truthy suffix overrides the implicit `bcword` on
//! negative years. Everything else falls back to Python via the
//! `kw.only` guard.
//!
//! `cardinal_from_decimal` stays at its default: DV's `to_currency` never
//! produces fractional cents, since `frac_part` is always run through
//! `to_integral_value`.

use crate::base::{Kwargs, KwVal, Lang, N2WError, Result};
use crate::currency::CurrencyValue;
use crate::floatpath::FloatValue;
use crate::strnum::{python_decimal_parse, ParsedNumber};
use bigdecimal::BigDecimal;
use num_bigint::BigInt;
use num_integer::Integer;
use num_traits::{Signed, Zero};

const NEGWORD: &str = "މައިނަސް";
const ORDWORD: &str = "ވަނަ";
const BCWORD: &str = "ބީ.ސީ";

/// `to_currency`'s `cents=` default: the *word* ލާރި (laari, 1/100 rufiyaa),
/// not a verbosity flag. See the `to_currency` impl for why the trait's bool
/// cannot carry it.
const CENTSWORD: &str = "ލާރި";

/// `self.high_numwords`, in source order. `set_high_numwords` zips this with
/// `range(3 + 3*len(high), 3, -3)` == `30, 27, …, 6`, so index 0 is 10^30.
const HIGH_NUMWORDS: [&str; 9] = [
    "ނޮނިލި",
    "އޮކްޓިލި",
    "ސެޕްޓިލި",
    "ސެކްސްޓިލި",
    "ކުއިންޓިލި",
    "ކުއަޑްރި",
    "ޓްރި",
    "ބިލި",
    "މިލި",
];

/// The suffix `set_high_numwords` appends to every high numword.
const HIGH_SUFFIX: &str = "ޔަން";

/// `self.grouping`, i.e. `[-3, -5] + [(x * 3 + 6) * -1 for x in range(len(self.cards))]`
/// with `len(self.cards) == 11`.
const GROUPING: [isize; 13] = [
    -3, -5, -6, -9, -12, -15, -18, -21, -24, -27, -30, -33, -36,
];

/// Number of significant digits `Decimal.__abs__` rounds to (the default
/// context precision, which `__init__` leaves untouched).
const CTX_PREC: usize = 28;

/// `self.MAXVAL` == `list(self.cards.keys())[0] * 1000` == 10^30 * 1000.
const MAXVAL_EXP: usize = 33;

pub struct LangDv {
    /// `reversed(self.cards.items())` — multiplier words in ascending order of
    /// their key, which is the order `convert_int` zips `parts[1:]` against.
    /// Only the word is ever read (the comprehension binds `base` and drops
    /// it), so the keys are not carried.
    mult_words_asc: Vec<String>,
    maxval: BigInt,
}

pub fn new() -> LangDv {
    LangDv::new()
}

impl Default for LangDv {
    fn default() -> Self {
        LangDv::new()
    }
}

impl LangDv {
    pub fn new() -> LangDv {
        // Mirror of `set_high_numwords` + the two explicit inserts. Python
        // builds `cards` descending (10^30 … 10^6, then 100000, then 1000);
        // `convert_int` only ever consumes it reversed, so store it ascending.
        let mut cards_desc: Vec<String> = HIGH_NUMWORDS
            .iter()
            .map(|w| format!("{}{}", w, HIGH_SUFFIX))
            .collect();
        cards_desc.push("ލައްކަ".to_string()); // self.cards[100000]
        cards_desc.push("ހާސް".to_string()); // self.cards[1000]

        let mut mult_words_asc = cards_desc;
        mult_words_asc.reverse();

        LangDv {
            mult_words_asc,
            maxval: pow10(MAXVAL_EXP),
        }
    }

    /// `self.base_stem` — bound/attributive forms. Missing key => `KeyError`.
    fn base_stem(&self, k: i64) -> Result<&'static str> {
        Ok(match k {
            0 => "ސުން",
            1 => "އެއް",
            2 => "ދެ",
            3 => "ތިން",
            4 => "ހަތަރު",
            5 => "ފަސް",
            6 => "ހަ",
            7 => "ހަތް",
            8 => "އައް",
            9 => "ނުވަ",
            10 => "ދިހަ",
            100 => "ސަތޭކަ",
            200 => "ދުއިސައްތަ",
            _ => return Err(N2WError::Key(k.to_string())),
        })
    }

    /// `self.base_nominal` — free-standing forms. Missing key => `KeyError`.
    fn base_nominal(&self, k: i64) -> Result<&'static str> {
        Ok(match k {
            0 => "ސުމެއް",
            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 => "ތިރީސް",
            40 => "ސާޅީސް",
            50 => "ފަންސާސް",
            60 => "ފަސްދޮޅަސް",
            70 => "ހަތްދިހަ",
            80 => "އައްޑިހަ",
            90 => "ނުވަދިހަ",
            _ => return Err(N2WError::Key(k.to_string())),
        })
    }

    /// `convert_decade2nominal`: `self.base_nominal[int(decade) * 10]`.
    fn convert_decade2nominal(&self, decade: &str) -> Result<&'static str> {
        self.base_nominal(py_int(decade)? * 10)
    }

    /// `convert_decade2stem`: 1 => `base_stem[10]`, else the nominal decade.
    fn convert_decade2stem(&self, decade: &str) -> Result<&'static str> {
        if py_int(decade)? == 1 {
            return self.base_stem(10);
        }
        self.convert_decade2nominal(decade)
    }

    /// `convert_two2nominal`.
    ///
    /// Unlike its `2stem` sibling this does **not** do `str(int(...))` first,
    /// so it indexes the caller's string as-is. Callers only ever pass an
    /// already-trimmed 1-char string or an exactly-2-char `digits_str[1:3]`
    /// slice, so the `< 30` guard always covers the 1-char case and the
    /// `digits_str[1]` access below is never out of range.
    fn convert_two2nominal(&self, digits_str: &str) -> Result<String> {
        let n = py_int(digits_str)?;
        if n < 30 {
            return Ok(self.base_nominal(n)?.to_string());
        }

        let d1 = char_at(digits_str, 1)?;
        let d0 = char_at(digits_str, 0)?;
        if py_int(&d1)? == 0 {
            return Ok(self.convert_decade2stem(&d0)?.to_string());
        }

        Ok(format!(
            "{}{}",
            self.convert_decade2stem(&d0)?,
            self.base_nominal(py_int(&d1)?)?
        ))
    }

    /// `convert_two2stem`.
    fn convert_two2stem(&self, digits_str: &str) -> Result<String> {
        let n = py_int(digits_str)?;
        let ds = n.to_string(); // `str(int(digits_str))` — trim leading zeros

        if n < 11 {
            return Ok(self.base_stem(n)?.to_string());
        }
        if n < 30 {
            return Ok(self.base_nominal(n)?.to_string());
        }

        let d1 = char_at(&ds, 1)?;
        let d0 = char_at(&ds, 0)?;
        if py_int(&d1)? == 0 {
            return Ok(self.convert_decade2stem(&d0)?.to_string());
        }

        Ok(format!(
            "{}{}",
            self.convert_decade2stem(&d0)?,
            self.base_stem(py_int(&d1)?)?
        ))
    }

    /// `convert_three2stem`.
    ///
    /// 100/200 have dedicated stems and glue straight onto the tail; 300–900
    /// are built as `<digit stem> + ސަތޭކަ + " " + <tail>` — note the space,
    /// which the 100/200 branches do not emit. Quirk 3 in the module docs.
    fn convert_three2stem(&self, digits_str: &str) -> Result<String> {
        let ds = py_int(digits_str)?.to_string(); // trim leading zeros

        if ds.len() < 3 {
            return self.convert_two2stem(&ds);
        }

        let d0 = char_at(&ds, 0)?;
        let tail = py_slice(&ds, 1, 3); // digits_str[1:3]
        let tail_n = py_int(&tail)?;

        if py_int(&d0)? == 1 {
            if tail_n == 0 {
                return Ok(self.base_stem(100)?.to_string());
            }
            return Ok(format!(
                "{}{}",
                self.base_stem(100)?,
                self.convert_two2stem(&tail)?
            ));
        }

        if py_int(&d0)? == 2 {
            if tail_n == 0 {
                return Ok(self.base_stem(200)?.to_string());
            }
            return Ok(format!(
                "{}{}",
                self.base_stem(200)?,
                self.convert_two2stem(&tail)?
            ));
        }

        if tail_n == 0 {
            return Ok(format!(
                "{}{}",
                self.convert_two2stem(&d0)?,
                self.base_stem(100)?
            ));
        }

        Ok(format!(
            "{}{} {}",
            self.convert_two2stem(&d0)?,
            self.base_stem(100)?,
            self.convert_two2stem(&tail)?
        ))
    }

    /// `convert_three2nominal`.
    ///
    /// Mirrors `convert_three2stem` except the tails are nominal — **and** the
    /// `x00` branch uses `convert_two2nominal(digits_str[0])` where the `xyz`
    /// branch uses `convert_two2stem(digits_str[0])`. That inconsistency is
    /// quirk 2 in the module docs: cardinal 300 == `ތިނެއްސަތޭކަ` (nominal three)
    /// but cardinal 555 == `ފަސްސަތޭކަ ފަންސާސްފަހެއް` (stem five). Preserved verbatim.
    fn convert_three2nominal(&self, digits_str: &str) -> Result<String> {
        let ds = py_int(digits_str)?.to_string(); // trim leading zeros

        if ds.len() < 3 {
            return self.convert_two2nominal(&ds);
        }

        let d0 = char_at(&ds, 0)?;
        let tail = py_slice(&ds, 1, 3);
        let tail_n = py_int(&tail)?;

        if py_int(&d0)? == 1 {
            if tail_n == 0 {
                return Ok(self.base_stem(100)?.to_string());
            }
            return Ok(format!(
                "{}{}",
                self.base_stem(100)?,
                self.convert_two2nominal(&tail)?
            ));
        }

        if py_int(&d0)? == 2 {
            if tail_n == 0 {
                return Ok(self.base_stem(200)?.to_string());
            }
            return Ok(format!(
                "{}{}",
                self.base_stem(200)?,
                self.convert_two2nominal(&tail)?
            ));
        }

        if tail_n == 0 {
            // NOTE: nominal here, stem in the branch below. Python bug, kept.
            return Ok(format!(
                "{}{}",
                self.convert_two2nominal(&d0)?,
                self.base_stem(100)?
            ));
        }

        Ok(format!(
            "{}{} {}",
            self.convert_two2stem(&d0)?,
            self.base_stem(100)?,
            self.convert_two2nominal(&tail)?
        ))
    }

    /// `convert_int`. `digits_str` is the decimal magnitude, i.e. Python's
    /// `"".join(str(d) for d in digits)` where `digits` came from
    /// `Decimal.as_tuple()` (sign-free, and exponent 0 for integer input).
    fn convert_int(&self, digits_str: &str, nominal: bool) -> Result<String> {
        if digits_str == "0" {
            return Ok(if nominal {
                self.base_nominal(0)?.to_string()
            } else {
                self.base_stem(0)?.to_string()
            });
        }

        // parts = filter(truthy, digits_str[start:end] for end, start in
        //                pairwise([len(digits_str)] + self.grouping))
        //
        // Emptiness is monotone here: `s[-a:-b]` is non-empty iff `len(s) > b`,
        // and the `b`s increase along `grouping`, so the filter only ever trims
        // a suffix of the sequence and never renumbers a surviving element.
        let mut bounds: Vec<isize> = Vec::with_capacity(1 + GROUPING.len());
        bounds.push(digits_str.chars().count() as isize);
        bounds.extend_from_slice(&GROUPING);

        let mut parts: Vec<String> = Vec::new();
        for w in bounds.windows(2) {
            let (end, start) = (w[0], w[1]);
            let p = py_slice(digits_str, start, end);
            if !p.is_empty() {
                parts.push(p);
            }
        }

        // `parts[0]` — IndexError if the filter left nothing. Unreachable for
        // integer input (the magnitude always has >= 1 digit), but this is the
        // site where float input dies, so it is modelled rather than assumed.
        let head = match parts.first() {
            Some(h) => h.clone(),
            None => return Err(N2WError::Index("list index out of range".into())),
        };

        // zip(parts[1:], reversed(self.cards.items())) — stops at the shorter.
        let mut part_words: Vec<String> = Vec::new();
        for (num, word) in parts.iter().skip(1).zip(self.mult_words_asc.iter()) {
            if py_int(num)? != 0 {
                part_words.push(format!("{}{}", self.convert_three2stem(num)?, word));
            }
        }
        part_words.reverse();

        if py_int(&head)? == 0 {
            return Ok(part_words.join(" "));
        }

        // NOTE: when `part_words` is empty this yields a leading space. The
        // caller strips it only on the non-negative path — see quirk 1.
        let tail = if nominal {
            self.convert_three2nominal(&head)?
        } else {
            self.convert_three2stem(&head)?
        };
        Ok(format!("{} {}", part_words.join(" "), tail))
    }

    /// `to_cardinal_float`, restricted to integer input.
    fn to_cardinal_float(&self, value: &BigInt, nominal: bool) -> Result<String> {
        // if Decimal(self.MAXVAL).compare(abs(v).to_integral(ROUND_FLOOR)) < 1
        //
        // `compare(x) < 1` means `MAXVAL <= x`. `abs()` rounds to 28
        // significant digits first (quirk 4), so this is *not* `v >= 10^33`.
        if round_half_even_28(&value.abs()) >= self.maxval {
            // Python formats the signed value, not its absolute value.
            return Err(N2WError::Overflow(format!(
                "abs({}) must be less than {}.",
                value, self.maxval
            )));
        }

        let result = self.convert_int(&value.abs().to_string(), nominal)?;

        if value.is_negative() {
            // " ".join([negword, result]) — no strip, hence the double space.
            return Ok(format!("{} {}", NEGWORD, result));
        }
        Ok(result.trim().to_string())
    }

    /// `to_cardinal_float`, for the currency path — where the argument is an
    /// already-integral `Decimal` rather than an `int`.
    ///
    /// Deliberately *not* folded into [`LangDv::to_cardinal_float`]. That one
    /// takes a `BigInt`, which flattens a `Decimal` to its full digit
    /// expansion; the whole point here is that Python does **not** expand —
    /// `as_tuple()` hands `convert_int` the bare coefficient and the exponent
    /// is dropped on the floor (quirk 8). `Decimal(int)` always has exponent 0,
    /// so the two agree on every value the verified integer modes can produce
    /// and diverge only where Python itself does.
    fn to_cardinal_float_dec(&self, value: &BigDecimal, nominal: bool) -> Result<String> {
        // sign, digits, exponent = decimal_value.as_tuple()
        let (coefficient, scale) = value.as_bigint_and_exponent();
        let exponent = -scale;
        let digits = coefficient.abs().to_string();

        if self.overflows(&coefficient, exponent) {
            // Python formats the *Decimal*, so a positive exponent prints in
            // scientific notation: "abs(1.5E+33) must be less than ...".
            return Err(N2WError::Overflow(format!(
                "abs({}) must be less than {}.",
                py_decimal_str(value),
                self.maxval
            )));
        }

        // The `exponent < 0` arm of `to_cardinal_float` (the pointword/
        // convert_discrete branch) is unreachable from here: every caller feeds
        // this a `to_integral_value()` result, which never has a negative
        // exponent. So only the `convert_int` arm can run.
        let result = self.convert_int(&digits, nominal)?;

        if coefficient.is_negative() {
            // " ".join([negword, result]) — no strip, hence the double space
            // that quirk 1 describes. This is the path 99.99's frac_part of -1
            // takes, which is why the corpus shows "މައިނަސް  އެއް ލާރި".
            return Ok(format!("{} {}", NEGWORD, result));
        }
        Ok(result.trim().to_string())
    }

    /// `to_cardinal_float`'s overflow guard for a `Decimal` argument:
    /// `Decimal(MAXVAL).compare(abs(v).to_integral(ROUND_FLOOR)) < 1`, i.e.
    /// `MAXVAL <= round_to_28_significant_digits(|v|)` — see quirk 4.
    ///
    /// `exponent` is Python's, so `>= 0` for every caller.
    fn overflows(&self, coefficient: &BigInt, exponent: i64) -> bool {
        if coefficient.is_zero() {
            return false;
        }
        // |v| >= 10^adjusted, where `adjusted` is the power of ten of the
        // leading digit. So adjusted >= 33 settles it as MAXVAL <= |v| without
        // materialising 10^exponent — which a Decimal("1E+999999999") would
        // otherwise demand, turning Python's instant OverflowError into an OOM.
        // Exact, not an approximation: rounding to nearest cannot pull a value
        // that is already >= 10^33 below 10^33, since 10^33 is itself
        // representable in 28 significant digits.
        let ndigits = coefficient.abs().to_string().len() as i64;
        if exponent + ndigits - 1 >= MAXVAL_EXP as i64 {
            return true;
        }
        // |v| < 10^33 now, so the exact integer is cheap. Rounding to 28
        // significant digits can still carry it up to exactly 10^33 — that is
        // the whole of quirk 4 — so the full check still has to run.
        let exact = coefficient.abs() * pow10(exponent.max(0) as usize);
        round_half_even_28(&exact) >= self.maxval
    }

    /// `verify_ordinal`. The `value == int(value)` float check cannot fail for
    /// integer input; only the negative check is reachable, and it raises
    /// `TypeError` rather than the `ValueError` one might expect.
    fn verify_ordinal(&self, value: &BigInt) -> Result<()> {
        if value.is_negative() {
            return Err(N2WError::Type(format!(
                "Cannot treat negative num {} as ordinal.",
                value
            )));
        }
        Ok(())
    }

    /// `convert_discrete`: render each individual digit as a *free* word. The
    /// fractional tail of the float path is spelled digit by digit, so this
    /// never sees anything but single 0-9 characters and neither table can
    /// miss. `nominal` picks `base_nominal` (cardinals) over `base_stem`; the
    /// non-nominal branch is only reachable via ordinal-float input, which
    /// `verify_ordinal` rejects before it can arrive here.
    fn convert_discrete(&self, digits_str: &str, nominal: bool) -> Result<String> {
        let mut out: Vec<String> = Vec::new();
        for ch in digits_str.chars() {
            let d = py_int(&ch.to_string())?;
            out.push(if nominal {
                self.base_nominal(d)?.to_string()
            } else {
                self.base_stem(d)?.to_string()
            });
        }
        Ok(out.join(" "))
    }

    /// The *real* `to_cardinal_float(value, nominal)` body — the one Python
    /// reaches with genuine float/Decimal input. Not to be confused with
    /// [`LangDv::to_cardinal_float`] above, which shares the Python name but is
    /// only ever fed an already-integral argument by the integer/currency
    /// modes. Both the Float and Decimal arms of the trait entry point reduce
    /// to `decimal_value.as_tuple()` — `(sign_negative, digit_str, exponent)` —
    /// and converge here.
    ///
    /// `digit_str` is the coefficient with no leading zeros (bar a lone `"0"`);
    /// `exponent` is Python's `as_tuple` exponent. The overflow guard has
    /// already fired in the caller.
    fn cardinal_float_body(
        &self,
        sign_negative: bool,
        digit_str: &str,
        exponent: i64,
        nominal: bool,
    ) -> Result<String> {
        let result = if exponent < 0 {
            let n = digit_str.chars().count() as i64;
            // Python slices the coefficient tuple: `digits[:exponent]` is the
            // integer part, `digits[exponent:len(digits)]` the fractional one.
            let cut = n + exponent; // == len(digits) - |exponent|

            // `digits[:exponent]` — empty when |exponent| >= len(digits), which
            // makes convert_int die with IndexError. That is evaluated first in
            // Python's join list, so 0.5 / 0.01 / 0.001 / 1.0-with-no-int-part
            // raise before the fractional digits are ever touched.
            let int_digits: String = if cut > 0 {
                digit_str.chars().take(cut as usize).collect()
            } else {
                String::new()
            };
            // Python hardcodes nominal=True for the integer part here (the
            // default arg), independent of the flag threaded to the fraction.
            let int_part = self.convert_int(&int_digits, true)?;

            // `digits[exponent:len(digits)]` — the fractional digits, clamped
            // to the whole coefficient when |exponent| exceeds its length
            // (unreachable in practice: int_part has already raised by then).
            let frac_digits: String = if cut > 0 {
                digit_str.chars().skip(cut as usize).collect()
            } else {
                digit_str.chars().collect()
            };
            let frac_part = self.convert_discrete(&frac_digits, nominal)?;

            // " ".join([convert_int(...), pointword, convert_discrete(...)]).
            // int_part still carries convert_int's leading space; the strip on
            // the non-negative path below launders it (quirk 1).
            format!("{} {} {}", int_part, self.pointword(), frac_part)
        } else {
            self.convert_int(digit_str, nominal)?
        };

        if sign_negative {
            // " ".join([negword, result]) — no strip, so convert_int's leading
            // space survives as the quirk-1 double space.
            Ok(format!("{} {}", NEGWORD, result))
        } else {
            Ok(result.trim().to_string())
        }
    }

    /// `to_cardinal_float`'s overflow guard for genuine float/Decimal input:
    /// `Decimal(MAXVAL).compare(abs(v).to_integral(ROUND_FLOOR)) < 1`, i.e.
    /// `MAXVAL <= floor(round_to_28_significant_digits(|v|))` (quirk 4). Unlike
    /// [`LangDv::overflows`], this floors the fractional part, matching
    /// `to_integral(ROUND_FLOOR)` — the value here can carry a real fraction.
    ///
    /// The 28-digit rounding is a no-op for any float (<= 17 significant digits)
    /// and for every corpus Decimal, but is reproduced for faithfulness.
    fn float_path_overflows(&self, digit_str: &str, exponent: i64) -> bool {
        let d = match BigInt::parse_bytes(digit_str.as_bytes(), 10) {
            Some(d) if !d.is_zero() => d,
            _ => return false,
        };
        // abs(v) context-rounds |coefficient| to 28 significant digits; scaling
        // by 10**exponent does not change which digits are significant, so
        // rounding the coefficient is rounding the value.
        let d = round_half_even_28(&d);
        // to_integral(ROUND_FLOOR): floor(d * 10**exponent), with d >= 0.
        let floored = if exponent >= 0 {
            d * pow10(exponent as usize)
        } else {
            d / pow10((-exponent) as usize) // truncation == floor for d >= 0
        };
        floored >= self.maxval
    }

    /// `to_cardinal_float(value, nominal)` for a value already reduced to its
    /// `as_tuple()` view: overflow guard, then [`LangDv::cardinal_float_body`].
    fn cardinal_tuple(
        &self,
        sign_negative: bool,
        digit_str: &str,
        exponent: i64,
        nominal: bool,
    ) -> Result<String> {
        if self.float_path_overflows(digit_str, exponent) {
            // Python formats the *Decimal* (`errmsg_toobig.format(decimal_value,
            // self.MAXVAL)`), so a positive exponent prints scientifically.
            return Err(N2WError::Overflow(format!(
                "abs({}) must be less than {}.",
                py_decimal_str_parts(sign_negative, digit_str, exponent),
                self.maxval
            )));
        }
        self.cardinal_float_body(sign_negative, digit_str, exponent, nominal)
    }

    /// The full `to_cardinal_float(value, nominal)` for genuine float/Decimal
    /// input — `to_decimal` (a no-op tuple reduction here), guard, body.
    fn cardinal_float_full(&self, value: &FloatValue, nominal: bool) -> Result<String> {
        let (sign_negative, digit_str, exponent) = float_value_tuple(value);
        self.cardinal_tuple(sign_negative, &digit_str, exponent, nominal)
    }

    /// `to_cardinal(f)` for an f64 the *port itself* produced (`to_year`'s
    /// `high`/`low`), routed through `Decimal(str(f))` like any float input.
    fn cardinal_from_f64(&self, f: f64, nominal: bool) -> Result<String> {
        let (sign_negative, digit_str, exponent) = py_float_dec_tuple(f);
        self.cardinal_tuple(sign_negative, &digit_str, exponent, nominal)
    }

    /// `verify_ordinal` for float/Decimal input.
    ///
    /// Order matters: the `value == int(value)` check runs first, so `-1.5`
    /// raises the *floatord* TypeError, not the negord one. `-0.0` passes
    /// both (`-0.0 == 0` and `abs(-0.0) == -0.0`) — quirk 12.
    fn verify_ordinal_float(&self, value: &FloatValue) -> Result<()> {
        let integral = match value {
            FloatValue::Float { value, .. } => *value == value.trunc(),
            FloatValue::Decimal { value, .. } => {
                let (coeff, scale) = value.as_bigint_and_exponent();
                scale <= 0 || (&coeff % pow10(scale as usize)).is_zero()
            }
        };
        if !integral {
            return Err(N2WError::Type(format!(
                "Cannot treat float {} as ordinal.",
                float_value_str(value)
            )));
        }
        let negative = match value {
            // Numeric `<`, not the sign bit: abs(-0.0) == -0.0 in Python.
            FloatValue::Float { value, .. } => *value < 0.0,
            // BigDecimal cannot carry a negative zero, so a negative
            // coefficient is a genuinely negative value.
            FloatValue::Decimal { value, .. } => {
                value.as_bigint_and_exponent().0.is_negative()
            }
        };
        if negative {
            return Err(N2WError::Type(format!(
                "Cannot treat negative num {} as ordinal.",
                float_value_str(value)
            )));
        }
        Ok(())
    }

    /// `to_year(value, suffix)` for integer input — the shared body behind
    /// the plain trait hook (`suffix=""`) and `to_year_kw`.
    fn year_int(&self, value: &BigInt, suffix: &str) -> Result<String> {
        let mut v = value.clone();
        let mut suffix = suffix.to_string();
        if v.is_negative() {
            v = v.abs();
            // suffix = self.bcword if not suffix else suffix
            if suffix.is_empty() {
                suffix = BCWORD.to_string();
            }
        }

        // `v` is non-negative by here, so Rust's truncating `/` and `%` agree
        // with Python's floor semantics.
        let hundred = BigInt::from(100);
        let high = &v / &hundred;
        let low = &v % &hundred;

        let mut result: Vec<String> = Vec::new();
        if v < BigInt::from(2000) && v >= BigInt::from(1100) {
            result.push(self.to_cardinal(&high)?);
            result.push("ސަތޭކަ".to_string()); // literal in Python, == base_stem[100]
            result.push(self.to_cardinal(&low)?);
        } else {
            result.push(self.to_cardinal(&v)?);
        }

        if !suffix.is_empty() {
            result.push(suffix);
        }

        Ok(result.join(" "))
    }
}

impl Lang for LangDv {

    fn python_maxval(&self) -> Option<num_bigint::BigInt> {
        // Python class attribute MAXVAL (self-contained converter).
        Some(num_bigint::BigInt::from(10u32).pow(33))
    }
    /// `self.pointword`, read from the live Python instance.
    /// Unused by the four integer modes, so phase 1 never needed it —
    /// the float path is the first caller.
    fn pointword(&self) -> &str {
        "ޕޮއިންޓް"
    }

    fn lang_name(&self) -> &str {
        "Num2Word_DV"
    }

    /// This language's own `to_currency(currency=...)` default,
    /// read from the live Python signature. Only 44 of 156 use EUR.
    fn default_currency(&self) -> &str {
        "ރުފިޔާ"
    }

    fn negword(&self) -> &str {
        NEGWORD
    }

    fn to_cardinal(&self, value: &BigInt) -> Result<String> {
        self.to_cardinal_float(value, true)
    }

    fn to_ordinal(&self, value: &BigInt) -> Result<String> {
        self.verify_ordinal(value)?;
        Ok(format!(
            "{} {}",
            self.to_cardinal_float(value, false)?,
            ORDWORD
        ))
    }

    fn to_ordinal_num(&self, value: &BigInt) -> Result<String> {
        self.verify_ordinal(value)?;
        Ok(format!("{} {}", value, ORDWORD))
    }

    /// `to_year(value, suffix="")`. This plain hook carries no `suffix`;
    /// callers passing one go through [`Lang::to_year_kw`]. The default empty
    /// string only matters for negative years, where Python substitutes
    /// `bcword`.
    fn to_year(&self, value: &BigInt) -> Result<String> {
        self.year_int(value, "")
    }

    /// `to_year(value, suffix=...)` — the only extra kwarg the Python
    /// signature accepts. `suffix=None` is falsy in `if not suffix`, so it
    /// behaves like the default; a non-str suffix would only crash later in
    /// `" ".join`, so it is punted back to Python instead of guessed at.
    fn to_year_kw(&self, value: &BigInt, kw: &Kwargs) -> Result<String> {
        if !kw.only(&["suffix"]) {
            return Err(N2WError::Fallback("kwargs".into()));
        }
        let suffix = match kw.get("suffix") {
            Option::None | Some(KwVal::None) => String::new(),
            Some(KwVal::Str(s)) => s.clone(),
            Some(_) => return Err(N2WError::Fallback("kwargs".into())),
        };
        self.year_int(value, &suffix)
    }

    /// `to_cardinal(value, nominal=True)` — the extra cardinal kwarg. Python
    /// only ever tests it with bare truthiness, so any falsy value selects
    /// the stem form.
    fn to_cardinal_kw(&self, value: &BigInt, kw: &Kwargs) -> Result<String> {
        if !kw.only(&["nominal"]) {
            return Err(N2WError::Fallback("kwargs".into()));
        }
        self.to_cardinal_float(value, kw_nominal(kw))
    }

    /// The genuine float/Decimal cardinal path. `Num2Word_DV.to_cardinal(value)`
    /// forwards to `to_cardinal_float(value, nominal=True)`, which converts the
    /// value to a `Decimal` (a float via `Decimal(str(value))`, so `2.675`
    /// yields the exact string digits `2,6,7,5` — DV never touches `float2tuple`
    /// and its binary-artefact heuristic) and renders it through
    /// `decimal_value.as_tuple()`.
    ///
    /// `precision_override` is ignored: DV's `to_cardinal_float` signature is
    /// `(value, nominal=True)` — no `precision` kwarg — and DV carries no
    /// `self.precision` attribute for the dispatcher's `precision=` path to
    /// latch onto, so Python could never thread one in here.
    fn to_cardinal_float(
        &self,
        value: &FloatValue,
        _precision_override: Option<u32>,
    ) -> Result<String> {
        self.cardinal_float_full(value, true)
    }

    /// `to_cardinal(float/Decimal)` — the full entry, whole values included.
    /// DV has no whole-value routing: `Decimal(str(5.0))` keeps its `.0`, so
    /// even integral floats run the pointword grammar (quirk 10), and a
    /// scientific repr collapses to its coefficient (quirk 9).
    fn cardinal_float_entry(
        &self,
        value: &FloatValue,
        _precision_override: Option<u32>,
    ) -> Result<String> {
        self.cardinal_float_full(value, true)
    }

    /// `to_ordinal(float/Decimal)`: `verify_ordinal(value)` (TypeError on
    /// non-integral, then on negative — quirk 12), then the float grammar
    /// with `nominal=False` (quirk 13) plus the ordword.
    fn ordinal_float_entry(&self, value: &FloatValue) -> Result<String> {
        self.verify_ordinal_float(value)?;
        Ok(format!(
            "{} {}",
            self.cardinal_float_full(value, false)?,
            ORDWORD
        ))
    }

    /// `to_ordinal_num(float/Decimal)`: `verify_ordinal`, then
    /// `"{} {}".format(value, ordword)` — `repr_str` is Python's
    /// `str(value)`, so `-0.0` (which passes verify) prints as `-0.0 ވަނަ`.
    fn ordinal_num_float_entry(&self, value: &FloatValue, repr_str: &str) -> Result<String> {
        self.verify_ordinal_float(value)?;
        Ok(format!("{} {}", repr_str, ORDWORD))
    }

    /// `to_year(float/Decimal)` — quirk 14. `value < 0` takes `abs()` first,
    /// so negative years carry no negword; [1100, 2000) splits into
    /// still-float `high`/`low` halves rendered independently.
    fn year_float_entry(&self, value: &FloatValue) -> Result<String> {
        match value {
            FloatValue::Float { value: f, .. } => {
                let mut v = *f;
                let mut suffix = "";
                // Numeric `<`: -0.0 is not negative and keeps its sign into
                // the cardinal, which raises IndexError there regardless.
                if v < 0.0 {
                    v = -v;
                    suffix = BCWORD;
                }

                let mut result: Vec<String> = Vec::new();
                if v < 2000.0 && v >= 1100.0 {
                    // Python float `%` is fmod (positive operands here), and
                    // `//` is the floor of the corrected quotient.
                    let low = v % 100.0;
                    let high = ((v - low) / 100.0).floor();
                    result.push(self.cardinal_from_f64(high, true)?);
                    result.push("ސަތޭކަ".to_string());
                    result.push(self.cardinal_from_f64(low, true)?);
                } else {
                    result.push(self.cardinal_from_f64(v, true)?);
                }

                if !suffix.is_empty() {
                    result.push(suffix.to_string());
                }
                Ok(result.join(" "))
            }
            FloatValue::Decimal { value: d, .. } => {
                let mut v = d.clone();
                let mut suffix = "";
                if v < BigDecimal::from(0) {
                    v = v.abs();
                    suffix = BCWORD;
                }

                let mut result: Vec<String> = Vec::new();
                if v < BigDecimal::from(2000) && v >= BigDecimal::from(1100) {
                    // Decimal divide-integer (`//`) yields exponent 0; the
                    // remainder keeps the ideal exponent min(exp(v), 0).
                    let (coeff, scale) = v.as_bigint_and_exponent();
                    let hundred = BigInt::from(100);
                    let (q, low_coeff, low_exp) = if scale >= 0 {
                        let div = &hundred * pow10(scale as usize);
                        let q = &coeff / &div; // v >= 1100 > 0: trunc == floor
                        let low = &coeff - &q * &div;
                        (q, low, -scale)
                    } else {
                        let full = &coeff * pow10((-scale) as usize);
                        let q = &full / &hundred;
                        let low = &full - &q * &hundred;
                        (q, low, 0)
                    };
                    result.push(self.cardinal_tuple(false, &q.to_string(), 0, true)?);
                    result.push("ސަތޭކަ".to_string());
                    result.push(self.cardinal_tuple(false, &low_coeff.to_string(), low_exp, true)?);
                } else {
                    let (coeff, scale) = v.as_bigint_and_exponent();
                    result.push(self.cardinal_tuple(
                        coeff.is_negative(),
                        &coeff.abs().to_string(),
                        -scale,
                        true,
                    )?);
                }

                if !suffix.is_empty() {
                    result.push(suffix.to_string());
                }
                Ok(result.join(" "))
            }
        }
    }

    /// `to_cardinal(float/Decimal, nominal=...)` — the kwarg rides the float
    /// entry too; the integer part stays hardcoded-nominal either way
    /// (quirk 13), only the fractional digits and the no-point branch follow
    /// the flag.
    fn to_cardinal_float_kw(
        &self,
        value: &FloatValue,
        _precision_override: Option<u32>,
        kw: &Kwargs,
    ) -> Result<String> {
        if !kw.only(&["nominal"]) {
            return Err(N2WError::Fallback("kwargs".into()));
        }
        self.cardinal_float_full(value, kw_nominal(kw))
    }

    /// `str_to_number` == `to_decimal`: `Decimal(value)` with
    /// `InvalidOperation` rewritten to `TypeError(errmsg_nonnum)`. The NaN
    /// arm short-circuits the InvalidOperation Python would raise a step
    /// later (`Decimal(MAXVAL).compare(NaN) < 1` in `to_cardinal_float`) —
    /// see the "Strings" section of the module docs for why it lives here.
    fn str_to_number(&self, s: &str) -> Result<ParsedNumber> {
        match python_decimal_parse(s) {
            Ok(ParsedNumber::NaN) => Err(N2WError::Custom {
                module: "decimal",
                class: "InvalidOperation",
                msg: "comparison involving NaN".into(),
            }),
            // A successful parse is served natively. The `to="fraction"`
            // AttributeError (Num2Word_DV has no to_fraction) is now handled
            // by the binding's fraction arm, which probes `to_fraction(1,1)`
            // and surfaces the language's AttributeError — so the earlier
            // blanket defer-to-Python is no longer needed.
            Ok(other) => Ok(other),
            Err(N2WError::Custom {
                module: "decimal",
                class: "InvalidOperation",
                ..
            }) => Err(N2WError::Type(format!("{} is not a valid value.", s))),
            Err(e) => Err(e),
        }
    }

    /// Like `to_cheque`, `Num2Word_DV` defines no `to_fraction` and inherits
    /// none, so the dispatcher's attribute lookup raises `AttributeError`
    /// before the arguments are even parsed — `to_fraction("1", "0")` never
    /// reaches a division, so no ZeroDivisionError either.
    fn to_fraction(&self, _numerator: &BigInt, _denominator: &BigInt) -> Result<String> {
        Err(N2WError::Attribute(
            "'Num2Word_DV' object has no attribute 'to_fraction'".into(),
        ))
    }

    /// `to_currency(self, value, currency="ރުފިޔާ", cents="ލާރި")`.
    ///
    /// Shares no machinery with `base.to_currency`: no forms table, no
    /// precision, no pluralize, no separator, no adjective. `separator` and
    /// `adjective` are therefore ignored rather than defaulted — the Python
    /// method has no such parameters, so nothing could consume them.
    ///
    /// `has_decimal` is ignored for the same reason. `base.to_currency` needs
    /// it to decide whether the cents segment appears; DV decides that with a
    /// plain truthiness test on `frac_part` instead (quirk 7), and its
    /// `to_decimal` treats an `int` and a `float` identically.
    fn to_currency(
        &self,
        val: &CurrencyValue,
        currency: &str,
        cents: bool,
        _separator: Option<&str>,
        _adjective: bool,
    ) -> Result<String> {
        // decimal_value = self.to_decimal(value). Decimal(int) and
        // Decimal(str(float)) — which is what the shim already handed us.
        let decimal_value = match val {
            CurrencyValue::Int(i) => BigDecimal::from(i.clone()),
            CurrencyValue::Decimal { value, .. } => value.clone(),
        };

        if decimal_value.is_zero() {
            return Ok(format!("{} {}", self.base_stem(0)?, currency));
        }

        // ROUND_HALF_EVEN, not floor — quirk 6. 99.99 rounds *up* to 100 and
        // frac_part comes out negative.
        let int_part = to_integral_value(&decimal_value);
        let frac_part =
            to_integral_value(&((&decimal_value - &int_part) * BigDecimal::from(100)));

        let mut result: Vec<String> = Vec::new();

        if !int_part.is_zero() {
            result.push(self.to_cardinal_float_dec(&int_part, false)?);
            result.push(currency.to_string());
        }

        if !frac_part.is_zero() {
            result.push(self.to_cardinal_float_dec(&frac_part, false)?);
            // Python appends `cents` — a *word*, defaulting to ލާރި. The trait
            // hands us a bool, because `base.to_currency`'s `cents=` is a
            // verbosity flag. The shim sends `kwargs.get("cents", True)`, so
            // `true` is the only value an ordinary call produces and the
            // default word is what Python would have used.
            //
            // `false` can only mean the caller explicitly passed `cents=False`,
            // and Python then puts the bool itself into the list and dies in
            // `" ".join(...)`. Reproduced rather than papered over — but note
            // it fires only once the cents segment exists at all, which is why
            // `to_currency(1.0, cents=False)` still returns "އެއް EUR", and why
            // this sits after frac_part has been rendered and pushed: an
            // OverflowError from that render happens first in Python too.
            if !cents {
                return Err(N2WError::Type(format!(
                    "sequence item {}: expected str instance, bool found",
                    result.len()
                )));
            }
            result.push(CENTSWORD.to_string());
        }

        // Both parts zero but the value itself non-zero (0.001) => "" — quirk 7.
        Ok(result.join(" "))
    }

    /// `Num2Word_DV` defines no `to_cheque`, and inherits none — it has no base
    /// class. The dispatcher's `getattr(converter, "to_cheque")` is what fails,
    /// before any conversion runs, so this is an `AttributeError` and *not* the
    /// `NotImplementedError` that `default_to_cheque` would raise on the empty
    /// forms table. The corpus records `AttributeError` for all nine codes.
    fn to_cheque(&self, _val: &BigDecimal, _currency: &str) -> Result<String> {
        Err(N2WError::Attribute(
            "'Num2Word_DV' object has no attribute 'to_cheque'".into(),
        ))
    }
}

/// 10^n.
fn pow10(n: usize) -> BigInt {
    let mut p = BigInt::from(1);
    for _ in 0..n {
        p *= 10;
    }
    p
}

/// The shortest round-trip decimal digits of `f` and its adjusted (power of
/// the leading digit) exponent, via Rust's `{:e}` — whose default precision
/// is "the smallest number of digits necessary to represent the value
/// uniquely", i.e. the same digits CPython's `repr(float)` prints, since the
/// shortest representation of a double is unique.
fn shortest_digits(f: f64) -> (String, i64) {
    let s = format!("{:e}", f); // e.g. "1.234e3", "-5e-1", "0e0"
    let (mant, exp) = s.split_once('e').expect("LowerExp always contains 'e'");
    let digits: String = mant.chars().filter(|c| c.is_ascii_digit()).collect();
    let adj: i64 = exp.parse().expect("LowerExp exponent is an integer");
    (digits, adj)
}

/// Reproduce `Decimal(str(f)).as_tuple()` as `(sign_negative, digit_str,
/// exponent)`, matching Python's `to_decimal(float)`.
///
/// `repr(float)` prints the shortest round-trip digits, fixed-point while the
/// adjusted exponent is in [-4, 16) and scientific outside. The regimes give
/// the Decimal *different* tuples:
///
///   * scientific: the coefficient is the bare digits (`'1e+16'` -> `(1,)`,
///     exponent 16) — quirk 9's collapse-to-coefficient;
///   * fixed-point, integral value: repr appends ".0", so the coefficient
///     gains the padding zeros plus one more and the exponent is -1
///     (`'1000.0'` -> `(1,0,0,0,0)`, exponent -1) — quirk 10;
///   * fixed-point, fractional value: digits as-is with the natural exponent
///     (`'12.34'` -> `(1,2,3,4)`, exponent -2). The tiny-scientific regime
///     (`'1e-05'`) lands on the same tuple as its fixed expansion would,
///     because `Decimal` strips leading coefficient zeros.
fn py_float_dec_tuple(f: f64) -> (bool, String, i64) {
    let sign_negative = f.is_sign_negative();
    let (m, adj) = shortest_digits(f);
    let ndig = m.chars().count() as i64;
    let e_nat = adj - (ndig - 1);
    if adj >= 16 || adj < -4 {
        // repr is scientific either way; both directions keep the bare digits.
        return (sign_negative, m, e_nat);
    }
    if e_nat >= 0 {
        // Integral fixed-point repr: '.0' appended.
        let mut d = m;
        for _ in 0..=e_nat {
            d.push('0');
        }
        // 0.0's coefficient collapses back to a single 0.
        let trimmed = d.trim_start_matches('0');
        let d = if trimmed.is_empty() { "0".to_string() } else { trimmed.to_string() };
        (sign_negative, d, -1)
    } else {
        (sign_negative, m, e_nat)
    }
}

/// Python's `str(float)` — repr with the same regime split as
/// [`py_float_dec_tuple`]. Only used for exception messages
/// (`errmsg_floatord` / `errmsg_negord` format the original value); the
/// corpora compare exception types, not text.
fn py_float_str(f: f64) -> String {
    let sign = if f.is_sign_negative() { "-" } else { "" };
    let (m, adj) = shortest_digits(f);
    if (-4..16).contains(&adj) {
        let intlen = adj + 1;
        if intlen <= 0 {
            format!("{}0.{}{}", sign, "0".repeat((-intlen) as usize), m)
        } else if intlen as usize >= m.len() {
            format!("{}{}{}.0", sign, m, "0".repeat(intlen as usize - m.len()))
        } else {
            let (a, b) = m.split_at(intlen as usize);
            format!("{}{}.{}", sign, a, b)
        }
    } else {
        let mut chars = m.chars();
        let lead = chars.next().unwrap_or('0');
        let rest: String = chars.collect();
        let coeff = if rest.is_empty() {
            lead.to_string()
        } else {
            format!("{}.{}", lead, rest)
        };
        // Python zero-pads the exponent to two digits: 1e-05, 1e+16.
        format!(
            "{}{}e{}{:02}",
            sign,
            coeff,
            if adj < 0 { '-' } else { '+' },
            adj.abs()
        )
    }
}

/// `self.to_decimal(value).as_tuple()` — the `(sign, digits, exponent)` view
/// every DV float path renders from.
fn float_value_tuple(value: &FloatValue) -> (bool, String, i64) {
    match value {
        // float -> Decimal(str(value)), reconstructed from the f64 repr.
        FloatValue::Float { value, .. } => py_float_dec_tuple(*value),
        // Decimal -> the Decimal unchanged. as_bigint_and_exponent() is
        // (coefficient, scale); Python's exponent is -scale. bigdecimal
        // preserves trailing zeros from the source string, so Decimal("1.10")
        // keeps coefficient 110 / exponent -2 — the trailing zero the corpus
        // depends on.
        FloatValue::Decimal { value, .. } => {
            let (coeff, scale) = value.as_bigint_and_exponent();
            (coeff.is_negative(), coeff.abs().to_string(), -scale)
        }
    }
}

/// `"{}".format(value)` for verify_ordinal's error messages: `str(float)`
/// for a float, `str(Decimal)` for a Decimal.
fn float_value_str(value: &FloatValue) -> String {
    match value {
        FloatValue::Float { value, .. } => py_float_str(*value),
        FloatValue::Decimal { .. } => {
            let (sign, digits, exponent) = float_value_tuple(value);
            py_decimal_str_parts(sign, &digits, exponent)
        }
    }
}

/// The `nominal=` kwarg under Python truthiness — `if not nominal` is the
/// only test the class ever applies, so False/0/None/""/[] all mean stem.
fn kw_nominal(kw: &Kwargs) -> bool {
    match kw.get("nominal") {
        Option::None => true, // not passed: the default
        Some(KwVal::Bool(b)) => *b,
        Some(KwVal::Int(i)) => *i != 0,
        Some(KwVal::None) => false,
        Some(KwVal::Str(s)) => !s.is_empty(),
        Some(KwVal::List(l)) => !l.is_empty(),
    }
}

/// `str(Decimal)` (the spec's to-scientific-string) from a
/// `(sign, digit_str, exponent)` tuple. Only reached to build an OverflowError
/// *message*; the differential harness compares exception *type*, not text, so
/// this is never on the parity path — implemented in full for fidelity anyway.
fn py_decimal_str_parts(sign_negative: bool, digit_str: &str, exponent: i64) -> String {
    let sign = if sign_negative { "-" } else { "" };
    let chars: Vec<char> = digit_str.chars().collect();
    let ndigits = chars.len() as i64;
    let adjusted = exponent + ndigits - 1;

    if exponent <= 0 && adjusted >= -6 {
        // Fixed-point form.
        if exponent == 0 {
            return format!("{}{}", sign, digit_str);
        }
        let leftdigits = exponent + ndigits; // where the point falls
        let (intpart, fracpart) = if leftdigits <= 0 {
            (
                "0".to_string(),
                format!(".{}{}", "0".repeat((-leftdigits) as usize), digit_str),
            )
        } else {
            let l = leftdigits as usize;
            (
                chars[..l].iter().collect::<String>(),
                format!(".{}", chars[l..].iter().collect::<String>()),
            )
        };
        return format!("{}{}{}", sign, intpart, fracpart);
    }

    // Scientific form.
    let coeff = if ndigits == 1 {
        chars[0].to_string()
    } else {
        format!("{}.{}", chars[0], chars[1..].iter().collect::<String>())
    };
    let esign = if adjusted < 0 { "-" } else { "+" };
    format!("{}{}E{}{}", sign, coeff, esign, adjusted.abs())
}

/// Round a non-negative integer to `CTX_PREC` significant decimal digits using
/// ROUND_HALF_EVEN — what `Decimal.__abs__` does under the default context.
///
/// Verified against CPython at the boundary: `10**33 - 50001` rounds to
/// `9.999999999999999999999999999E+32` (below MAXVAL, converts fine) while
/// `10**33 - 50000` is a tie and rounds to even, giving `1E+33` == MAXVAL and
/// tripping the overflow guard.
fn round_half_even_28(a: &BigInt) -> BigInt {
    let ndigits = a.to_string().len(); // `a` is non-negative: no sign char
    if ndigits <= CTX_PREC {
        return a.clone();
    }

    let divisor = pow10(ndigits - CTX_PREC);
    let (mut q, r) = a.div_rem(&divisor);
    let twice = &r * 2;

    if twice > divisor {
        q += 1;
    } else if twice == divisor {
        // Exact tie: round half to even.
        if !q.is_even() {
            q += 1;
        }
    }
    q * divisor
}

/// Python's `Decimal.to_integral_value()` — round to an integer using the
/// context's rounding, which `__init__` leaves at the default ROUND_HALF_EVEN.
/// (The commented-out `getcontext().rounding = ROUND_FLOOR` never took effect;
/// were it live, 99.99 would floor to 99 and quirk 6's negative cents could not
/// arise.)
///
/// A value whose exponent is already `>= 0` comes back **untouched**, keeping
/// its coefficient and exponent — so `Decimal("1E+21")` stays `1E+21` rather
/// than expanding to 22 digits. That is what quirk 8 rides on.
fn to_integral_value(d: &BigDecimal) -> BigDecimal {
    let (coefficient, scale) = d.as_bigint_and_exponent();
    // scale <= 0 is Python's exponent >= 0.
    if scale <= 0 {
        return d.clone();
    }

    let divisor = pow10(scale as usize);
    let negative = coefficient.is_negative();
    let (mut q, r) = coefficient.abs().div_rem(&divisor);
    // ROUND_HALF_EVEN on the magnitude; the mode is symmetric about zero.
    let twice = &r * 2;
    if twice > divisor || (twice == divisor && !q.is_even()) {
        q += 1;
    }
    if negative {
        q = -q;
    }
    // Rounding always lands on exponent 0, matching Python.
    BigDecimal::new(q, 0)
}

/// Python's `str(Decimal)` — the spec's *to-scientific-string* — restricted to
/// the integral values this file can reach it with.
///
/// Only two of the spec's three branches can fire. Exponent 0 prints the
/// coefficient plainly; a positive exponent switches to scientific notation
/// keyed on the adjusted exponent, so `Decimal('1.5E+33')` is `"1.5E+33"` and
/// not `"1500000000000000000000000000000000"`. A negative exponent would need
/// the third branch, which `to_integral_value` rules out.
fn py_decimal_str(d: &BigDecimal) -> String {
    let (coefficient, scale) = d.as_bigint_and_exponent();
    let exponent = -scale;
    let digits = coefficient.abs().to_string();
    let sign = if coefficient.is_negative() { "-" } else { "" };

    if exponent <= 0 {
        return format!("{}{}", sign, digits);
    }

    // adjusted exponent = exponent + len(digits) - 1
    let adjusted = exponent + digits.chars().count() as i64 - 1;
    let mut chars = digits.chars();
    let lead = chars.next().unwrap_or('0');
    let rest: String = chars.collect();
    let coeff = if rest.is_empty() {
        lead.to_string()
    } else {
        format!("{}.{}", lead, rest)
    };
    // Python prints the exponent's sign explicitly and never zero-pads it.
    let esign = if adjusted < 0 { "-" } else { "+" };
    format!("{}{}E{}{}", sign, coeff, esign, adjusted.abs())
}

/// Python's `int(s)` over an ASCII digit string. Every call site feeds it a
/// slice of at most 3 digits, so `i64` cannot overflow.
fn py_int(s: &str) -> Result<i64> {
    s.parse::<i64>().map_err(|_| {
        N2WError::Value(format!(
            "invalid literal for int() with base 10: '{}'",
            s
        ))
    })
}

/// Python's `s[i]`, raising `IndexError` past the end.
fn char_at(s: &str, i: usize) -> Result<String> {
    s.chars()
        .nth(i)
        .map(|c| c.to_string())
        .ok_or_else(|| N2WError::Index("string index out of range".into()))
}

/// Python's `s[start:end]` with negative-index and clamping semantics.
/// Operates on chars; every caller passes an ASCII digit string.
fn py_slice(s: &str, start: isize, end: isize) -> String {
    let chars: Vec<char> = s.chars().collect();
    let len = chars.len() as isize;

    let norm = |i: isize| -> usize {
        if i < 0 {
            let j = len + i;
            if j < 0 {
                0
            } else {
                j as usize
            }
        } else if i > len {
            len as usize
        } else {
            i as usize
        }
    };

    let (a, b) = (norm(start), norm(end));
    if a >= b {
        return String::new();
    }
    chars[a..b].iter().collect()
}

#[cfg(test)]
mod float_tests {
    use super::*;
    use std::str::FromStr;

    fn f(value: f64, precision: u32) -> Result<String> {
        // Fully-qualified: the inherent to_cardinal_float(&BigInt, bool) would
        // otherwise shadow the trait method under method-call syntax.
        Lang::to_cardinal_float(
            &LangDv::new(),
            &FloatValue::Float { value, precision },
            None,
        )
    }

    fn d(s: &str) -> Result<String> {
        Lang::to_cardinal_float(
            &LangDv::new(),
            &FloatValue::Decimal {
                value: BigDecimal::from_str(s).unwrap(),
                // DV ignores precision; a plausible value all the same.
                precision: s.split_once('.').map_or(0, |(_, fr)| fr.len() as u32),
            },
            None,
        )
    }

    fn is_index(r: &Result<String>) -> bool {
        matches!(r, Err(N2WError::Index(_)))
    }

    #[test]
    fn float_cardinal_matches_corpus_and_interpreter() {
        assert!(is_index(&f(0.5, 1)));
        assert_eq!(f(1.5, 1).unwrap(), "އެކެއް ޕޮއިންޓް ފަހެއް");
        assert_eq!(f(3.14, 2).unwrap(), "ތިނެއް ޕޮއިންޓް އެކެއް ހަތަރެއް");
        assert_eq!(f(12.34, 2).unwrap(), "ބާރަ ޕޮއިންޓް ތިނެއް ހަތަރެއް");
        assert_eq!(f(-12.34, 2).unwrap(), "މައިނަސް  ބާރަ ޕޮއިންޓް ތިނެއް ހަތަރެއް");
        assert_eq!(f(1.005, 3).unwrap(), "އެކެއް ޕޮއިންޓް ސުމެއް ސުމެއް ފަހެއް");
        assert_eq!(f(2.675, 3).unwrap(), "ދޭއް ޕޮއިންޓް ހައެއް ހަތެއް ފަހެއް");
        assert!(is_index(&f(0.01, 2)));
        assert_eq!(f(99.99, 2).unwrap(), "ނުވަދިހަނުވައެއް ޕޮއިންޓް ނުވައެއް ނުވައެއް");
        assert_eq!(f(1.0, 1).unwrap(), "އެކެއް ޕޮއިންޓް ސުމެއް");
        assert!(is_index(&f(0.0, 1)));
        assert!(is_index(&f(-0.5, 1)));
        assert_eq!(f(100.5, 1).unwrap(), "ސަތޭކަ ޕޮއިންޓް ފަހެއް");
        assert_eq!(
            f(1234.56, 2).unwrap(),
            "އެއްހާސް ދުއިސައްތަތިރީސްހަތަރެއް ޕޮއިންޓް ފަހެއް ހައެއް"
        );
        assert_eq!(f(-1.5, 1).unwrap(), "މައިނަސް  އެކެއް ޕޮއިންޓް ފަހެއް");
        assert!(is_index(&f(0.1, 1)));
        assert!(is_index(&f(0.99, 2)));
        assert_eq!(f(1.01, 2).unwrap(), "އެކެއް ޕޮއިންޓް ސުމެއް އެކެއް");
        assert_eq!(f(2.25, 2).unwrap(), "ދޭއް ޕޮއިންޓް ދޭއް ފަހެއް");
    }

    #[test]
    fn decimal_cardinal_matches_corpus() {
        assert!(is_index(&d("0.01")));
        assert_eq!(d("1.10").unwrap(), "އެކެއް ޕޮއިންޓް އެކެއް ސުމެއް");
        assert_eq!(d("12.345").unwrap(), "ބާރަ ޕޮއިންޓް ތިނެއް ހަތަރެއް ފަހެއް");
        assert_eq!(
            d("98746251323029.99").unwrap(),
            "ނުވަދިހައައްޓްރިޔަން ހަތްސަތޭކަ ސާޅީސްހަބިލިޔަން ދުއިސައްތަފަންސާސްއެއްމިލިޔަން ތިންލައްކަ ތޭވީސްހާސް ނަވާވީސް ޕޮއިންޓް ނުވައެއް ނުވައެއް"
        );
        assert!(is_index(&d("0.001")));
        assert_eq!(d("1.005").unwrap(), "އެކެއް ޕޮއިންޓް ސުމެއް ސުމެއް ފަހެއް");
        assert_eq!(d("2.675").unwrap(), "ދޭއް ޕޮއިންޓް ހައެއް ހަތެއް ފަހެއް");
        assert!(is_index(&d("0.50")));
    }

    #[test]
    fn whole_float_entries_match_corpus() {
        let l = LangDv::new();
        let fv = |v: f64| FloatValue::Float { value: v, precision: 1 };

        // cardinal: no whole-value fast path (quirk 10) + scientific collapse
        // (quirk 9) + IndexError on empty integer part (quirk 11).
        assert_eq!(
            l.cardinal_float_entry(&fv(5.0), None).unwrap(),
            "ފަހެއް ޕޮއިންޓް ސުމެއް"
        );
        assert_eq!(
            l.cardinal_float_entry(&fv(-2.0), None).unwrap(),
            "މައިނަސް  ދޭއް ޕޮއިންޓް ސުމެއް"
        );
        assert_eq!(
            l.cardinal_float_entry(&fv(-1000.0), None).unwrap(),
            "މައިނަސް އެއްހާސް ޕޮއިންޓް ސުމެއް"
        );
        assert_eq!(l.cardinal_float_entry(&fv(1e16), None).unwrap(), "އެކެއް");
        assert_eq!(l.cardinal_float_entry(&fv(1e20), None).unwrap(), "އެކެއް");
        assert!(matches!(
            l.cardinal_float_entry(&fv(0.0), None),
            Err(N2WError::Index(_))
        ));
        assert!(matches!(
            l.cardinal_float_entry(&fv(-0.0), None),
            Err(N2WError::Index(_))
        ));

        // ordinal: verify_ordinal order (quirk 12) + nominal/stem mix (13).
        assert_eq!(
            l.ordinal_float_entry(&fv(1.0)).unwrap(),
            "އެކެއް ޕޮއިންޓް ސުން ވަނަ"
        );
        assert_eq!(l.ordinal_float_entry(&fv(1e16)).unwrap(), "އެއް ވަނަ");
        assert!(matches!(l.ordinal_float_entry(&fv(2.5)), Err(N2WError::Type(_))));
        assert!(matches!(l.ordinal_float_entry(&fv(-1.5)), Err(N2WError::Type(_))));
        assert!(matches!(l.ordinal_float_entry(&fv(-1.0)), Err(N2WError::Type(_))));
        assert!(matches!(l.ordinal_float_entry(&fv(-0.0)), Err(N2WError::Index(_))));

        // ordinal_num: -0.0 passes verify and echoes the repr.
        assert_eq!(
            l.ordinal_num_float_entry(&fv(-0.0), "-0.0").unwrap(),
            "-0.0 ވަނަ"
        );
        assert!(matches!(
            l.ordinal_num_float_entry(&fv(-1.0), "-1.0"),
            Err(N2WError::Type(_))
        ));

        // year: abs-before-cardinal + the [1100, 2000) float split (quirk 14).
        assert_eq!(
            l.year_float_entry(&fv(-1.5)).unwrap(),
            "އެކެއް ޕޮއިންޓް ފަހެއް ބީ.ސީ"
        );
        assert_eq!(
            l.year_float_entry(&fv(1234.0)).unwrap(),
            "ބާރަ ޕޮއިންޓް ސުމެއް ސަތޭކަ ތިރީސްހަތަރެއް ޕޮއިންޓް ސުމެއް"
        );
        assert_eq!(l.year_float_entry(&fv(1e16)).unwrap(), "އެކެއް");
        assert!(matches!(l.year_float_entry(&fv(-0.0)), Err(N2WError::Index(_))));
    }

    #[test]
    fn decimal_entries_match_corpus() {
        let l = LangDv::new();
        let dv = |s: &str| FloatValue::Decimal {
            value: BigDecimal::from_str(s).unwrap(),
            precision: 0,
        };

        assert_eq!(l.cardinal_float_entry(&dv("1E+2"), None).unwrap(), "އެކެއް");
        assert_eq!(l.cardinal_float_entry(&dv("1E+20"), None).unwrap(), "އެކެއް");
        assert_eq!(l.ordinal_float_entry(&dv("0")).unwrap(), "ސުން ވަނަ");
        assert_eq!(l.ordinal_float_entry(&dv("5")).unwrap(), "ފަސް ވަނަ");
        assert_eq!(l.ordinal_float_entry(&dv("100")).unwrap(), "ސަތޭކަ ވަނަ");
        assert_eq!(
            l.ordinal_float_entry(&dv("5.00")).unwrap(),
            "ފަހެއް ޕޮއިންޓް ސުން ސުން ވަނަ"
        );
        assert_eq!(l.ordinal_float_entry(&dv("1E+2")).unwrap(), "އެއް ވަނަ");
        assert!(matches!(l.ordinal_float_entry(&dv("-3.0")), Err(N2WError::Type(_))));
        assert_eq!(
            l.year_float_entry(&dv("-3.0")).unwrap(),
            "ތިނެއް ޕޮއިންޓް ސުމެއް ބީ.ސީ"
        );
        assert_eq!(l.year_float_entry(&dv("1E+2")).unwrap(), "އެކެއް");
        assert_eq!(
            l.year_float_entry(&dv("12345.000")).unwrap(),
            "ބާރަހާސް ތިންސަތޭކަ ސާޅީސްފަހެއް ޕޮއިންޓް ސުމެއް ސުމެއް ސުމެއް"
        );
    }

    #[test]
    fn strings_fraction_and_kwargs_match_corpus() {
        use crate::base::{KwVal, Kwargs};
        let l = LangDv::new();

        // str_to_number: TypeError instead of InvalidOperation; NaN
        // short-circuits the compare's InvalidOperation.
        assert!(matches!(l.str_to_number("abc"), Err(N2WError::Type(_))));
        assert!(matches!(l.str_to_number(""), Err(N2WError::Type(_))));
        assert!(matches!(
            l.str_to_number("NaN"),
            Err(N2WError::Custom { class: "InvalidOperation", .. })
        ));
        assert!(matches!(l.str_to_number("1e3"), Ok(ParsedNumber::Dec(_))));

        // to_fraction: AttributeError on lookup, even for 1/0.
        assert!(matches!(
            l.to_fraction(&BigInt::from(1), &BigInt::from(0)),
            Err(N2WError::Attribute(_))
        ));

        // nominal= kwarg (the kwargs corpus rows).
        let kw = |v: KwVal| Kwargs(vec![("nominal".to_string(), v)]);
        assert_eq!(
            l.to_cardinal_kw(&BigInt::from(1234), &kw(KwVal::Bool(false))).unwrap(),
            "އެއްހާސް ދުއިސައްތަތިރީސްހަތަރު"
        );
        assert_eq!(
            l.to_cardinal_kw(&BigInt::from(-5), &kw(KwVal::Bool(false))).unwrap(),
            "މައިނަސް  ފަސް"
        );
        assert_eq!(
            l.to_cardinal_kw(&BigInt::from(0), &kw(KwVal::Bool(false))).unwrap(),
            "ސުން"
        );
        assert_eq!(
            l.to_cardinal_kw(&BigInt::from(0), &kw(KwVal::Bool(true))).unwrap(),
            "ސުމެއް"
        );
        assert!(matches!(
            l.to_cardinal_kw(
                &BigInt::from(1),
                &Kwargs(vec![("case".to_string(), KwVal::Str("dative".into()))])
            ),
            Err(N2WError::Fallback(_))
        ));

        // suffix= kwarg on to_year.
        let skw = Kwargs(vec![("suffix".to_string(), KwVal::Str("AD".into()))]);
        assert_eq!(l.to_year_kw(&BigInt::from(5), &skw).unwrap(), "ފަހެއް AD");
        assert_eq!(l.to_year_kw(&BigInt::from(-17), &skw).unwrap(), "ސަތާރަ AD");
        assert_eq!(
            l.to_year_kw(
                &BigInt::from(-17),
                &Kwargs(vec![("suffix".to_string(), KwVal::None)])
            )
            .unwrap(),
            "ސަތާރަ ބީ.ސީ"
        );
    }

    #[test]
    fn overflow_boundary_matches_python() {
        // Python raises OverflowError when floor(round28(|v|)) >= 10**33 in the
        // float/Decimal path (quirk 4: abs() rounds to 28 significant digits
        // half-to-even first). Boundary values verified against CPython.
        let overflow = |s: &str| matches!(d(s), Err(N2WError::Overflow(_)));

        assert!(overflow(&"9".repeat(33))); // 10**33 - 1 rounds up to 10**33
        assert!(overflow(&format!("1{}", "0".repeat(33)))); // 10**33
        assert!(overflow(&(10u128.pow(33) - 50000).to_string())); // exact tie, up
        assert!(d(&(10u128.pow(33) - 50001).to_string()).is_ok()); // just under
        assert!(d(&"9".repeat(28)).is_ok()); // 28 digits, no rounding
        assert!(d(&format!("1{}", "0".repeat(32))).is_ok()); // 10**32
        // A fractional value floors below the bound and converts fine.
        assert!(d(&format!("{}.5", "9".repeat(32))).is_ok());
    }
}