mrz 0.9.1

Zero-dependency (by default) ICAO 9303 Machine Readable Zone (MRZ) parser, emitter, and check-digit validator for TD1/TD2/TD3 and MRV-A/MRV-B (visa) documents.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
//! MRZ line parsers (TD1/TD2/TD3/MRV-A/MRV-B) and the free-text scanner [`find_and_parse`].
//!
//! Field offsets follow ICAO 9303 Parts 4 (TD3), 5 (TD1), 6 (TD2) and 7 (MRV-A/B). Each
//! parser verifies applicable printed check digits; the scanner drives OCR
//! repair in [`crate::checksum`] and accepts a fully validating reading. Agreement is checksum
//! consistency, not byte-identity with the printed zone — see
//! [`crate::Blindspot`].

use crate::checksum::{
    aggressive_defiller, char_value, defiller, digitize, fix_doc_code, fix_name_separator,
    is_mrz_charset, letterize, line1_variants, normalize_line, repair_positions, variants, verify,
};
use crate::repair::{solve_class_sweep, FieldKind, Resolution};
use crate::{
    country_name, passport_type, Checks, DateRole, Format, MrzData, MrzDate, MrzError,
    ParseOptions, RawDateField, Sex,
};

/// A document number that overflowed its 9-character field.
struct Overflow {
    /// The nine principal characters (spec form) or the legacy crate's
    /// truncated eight (legacy form), plus the remainder read from the
    /// optional field. See [`legacy`](Overflow::legacy).
    full: String,
    /// Whether the remainder's own check digit validates the reassembly.
    check_ok: bool,
    /// `true` when `full` was reassembled using the pre-0.6 eight-character
    /// encoding this crate used to emit, rather than the Doc 9303 form.
    legacy: bool,
    /// Characters of the optional field consumed by the overflow encoding
    /// (remainder + its check digit + the terminating filler).
    consumed: usize,
}

/// Decode the ICAO 9303 long-document-number overflow encoding: TD1 note j
/// (`knowledge/docs9303/Doc_9303_Part5_Specs_for_TD1_MROTDs.md:373`) and its
/// §4.2.4 check-digit table (`:464-469`), TD2 note j
/// (`knowledge/docs9303/Doc_9303_Part6_Specs_for_TD2_MROTDs.md:346`).
///
/// **Part 4 defines no overflow encoding for TD3 at all** — nothing in the
/// corpus states a "more than 9 characters" rule for TD3; that language
/// appears only in Parts 5, 6 and 7 (Part 7 explicitly caps at "positions 1
/// to 9" with no spillover — MRV-A/MRV-B never call this function). Applying
/// the TD1/TD2 rule to TD3 below is a deliberate extension by analogy, made
/// because issuers do it in practice, not something Part 4 licenses. See
/// `knowledge/docs9303/CONFORMANCE_BASIS.md`'s "Part 5 §4.2.4 / Part 6 note
/// j" entry for the full corroboration.
///
/// When the number exceeds the 9-character field, all nine principal
/// characters are printed, the field's check-digit position is set to a
/// filler to signal a truncated number, and the *remainder* plus a check
/// digit computed over the whole number (nine principal characters plus
/// remainder) is written at the start of the optional/personal-number field,
/// terminated by a filler.
///
/// This crate emitted a non-conformant eight-character form before 0.6.0
/// (first 8 characters + filler, remainder starting at the 9th). Both forms
/// are attempted here so a zone written by an older version of this crate
/// still parses. **The two forms are distinguishable but not perfectly**:
/// because `<` has character value 0 yet still consumes a 7-3-1 weight slot,
/// the spec-form and legacy-form candidate inputs differ in both length and
/// weight alignment, so they generally produce different check digits — but
/// a legacy zone will spuriously satisfy the spec-form check roughly 1 time
/// in 10 (one digit out of ten possible check-digit values), yielding a full
/// number with one extra stray character. That is inherent to testing two
/// encodings against a single printed check digit; there is no heuristic
/// that defeats it, so this function does not attempt one.
///
/// Returns `None` when the zone does not carry an overflow signature at all
/// (check digit position isn't a filler, or the optional field has no
/// remainder to read), in which case the caller keeps the ordinary
/// fixed-width reading. MRV-A/MRV-B never use this — ICAO 9303 part 7 defines
/// no overflow encoding.
fn read_overflow(number_field: &str, check: char, optional: &str) -> Option<Overflow> {
    if check != '<' {
        return None;
    }
    if number_field.trim_end_matches('<').is_empty() {
        // A blank document-number field is a blank field, not an overflow.
        return None;
    }
    // The remainder runs to the terminating filler and ends with its check digit.
    let end = optional.find('<')?;
    if end < 2 {
        return None; // need at least one remainder character plus a check digit
    }
    let (remainder, check_digit) = optional[..end].split_at(end - 1);
    let check_digit = check_digit.chars().next()?;
    if !check_digit.is_ascii_digit() {
        return None;
    }
    let consumed = end + 1;

    // Spec form: all nine principal characters plus the remainder.
    let spec_full = format!("{number_field}{remainder}");
    if verify(&spec_full, check_digit) {
        return Some(Overflow {
            full: spec_full,
            check_ok: true,
            legacy: false,
            consumed,
        });
    }

    // Legacy form: this crate's pre-0.6 eight-character truncation + filler.
    if number_field.ends_with('<') {
        let head = number_field[0..8].trim_end_matches('<');
        let legacy_full = format!("{head}{remainder}");
        if verify(&legacy_full, check_digit) {
            return Some(Overflow {
                full: legacy_full,
                check_ok: true,
                legacy: true,
                consumed,
            });
        }
    }

    // Neither form verifies: surface the spec-form reassembly with a failed
    // check so the caller still sees the full number, not a truncated one.
    Some(Overflow {
        full: spec_full,
        check_ok: false,
        legacy: false,
        consumed,
    })
}

/// Trim an optional-data field to what remains after any overflow encoding.
fn optional_tail<'a>(optional: &'a str, overflow: &Option<Overflow>) -> &'a str {
    match overflow {
        Some(o) => optional[o.consumed..].trim_end_matches('<'),
        None => optional.trim_end_matches('<'),
    }
}

fn opt_string(s: &str) -> Option<String> {
    (!s.is_empty()).then(|| s.to_string())
}

/// Split a name field on the ICAO 9303 primary/secondary identifier
/// separator `<<`. Falls back to a single `<` when no `<<` survives OCR —
/// a real, measured failure mode distinct from [`fix_name_separator`]'s `<`
/// misread as `KK`: OCR sometimes drops one of the two filler characters
/// outright rather than misreading it, collapsing `SURNAME<<GIVEN` to
/// `SURNAME<GIVEN` with no `KK` anywhere for that repair to catch. Before
/// this fallback, that single dropped character sent `given_names` to `""`
/// unconditionally — first measured on MRV-A/MRV-B (`given_names` CER
/// 63.5%/76.7% at first measurement, 30 seeds, `--profile clean`, seed 42;
/// see `knowledge/ROADMAP.md`'s M6 section) but present on every format that
/// calls this function, since none of them check-digit-cover line 1's name
/// field to begin with. The fallback is unambiguous for this crate's own
/// generated corpus (`synthpass-gen`'s `SURNAMES`/`GIVEN_NAMES_M`/
/// `GIVEN_NAMES_F` are single tokens, never containing an internal `<`), but
/// is a best-effort guess against a real-world compound name (e.g. `DE<LA
/// <CRUZ<<MARIA` losing its `<<` down to `<` is indistinguishable from a
/// compound *surname*'s own internal `<`) — never claimed as proven, since
/// `FieldConfidence` never rates a name field above `MRZ_STRUCTURAL` (0.9)
/// regardless of which branch below produced it.
fn clean_name(field: &str) -> (String, String) {
    let trimmed = field.trim_end_matches('<');
    let (surname, given) = match trimmed.split_once("<<") {
        Some((s, g)) => (s, g),
        None => match trimmed.split_once('<') {
            Some((s, g)) => (s, g),
            None => (trimmed, ""),
        },
    };
    (
        surname.replace('<', " ").trim().to_string(),
        given.replace('<', " ").trim().to_string(),
    )
}

fn ensure_charset(line: &str, line_number: usize) -> Result<(), MrzError> {
    for (position, c) in line.chars().enumerate() {
        if char_value(c).is_none() {
            return Err(MrzError::BadCharacter {
                character: c,
                line: Some(line_number),
                position,
            });
        }
    }
    Ok(())
}

/// Refuse a document-number field whose first cell is the filler `<`,
/// including an all-filler field. Doc 9303 enters data from the left-hand
/// position of each field (Part 3 PDF p.28; Part 4 PDF p.25 for TD3), so a
/// leading filler is not representable data the way an *interior* one is
/// (Part 4 §4.2.2.2 permits those). Called after the charset and
/// document-code checks, before the field's own check digit is evaluated —
/// the ICAO 7-3-1 arithmetic gives `<` the same residue-0 value as `0`, `A`,
/// `K` and `U` (see [`crate::Blindspot`]), so a misread first cell can still
/// verify. `field` is the field's text, `position` its zero-based first `char`
/// column and `line` its zero-based line within the zone.
fn ensure_document_number_leads(field: &str, line: usize, position: usize) -> Result<(), MrzError> {
    if field.starts_with('<') {
        return Err(MrzError::LeadingFiller {
            field: crate::Field::DocumentNumber,
            line,
            position,
        });
    }
    Ok(())
}

/// Read the six-character date field at `line[start..start + 6]`.
///
/// Every caller has vetted the line and its length. The error arm maps an
/// impossible failed conversion to the same error as `ensure_charset` without
/// panicking if this helper is called on an unvetted slice.
fn date_field(
    line: &str,
    line_number: usize,
    start: usize,
    role: DateRole,
    pivot_yy: u32,
) -> Result<MrzDate, MrzError> {
    let text = line
        .get(start..start + 6)
        .unwrap_or_else(|| line.get(start..).unwrap_or(""));
    match RawDateField::try_from(text) {
        Ok(field) => Ok(MrzDate::from_field(field, role, pivot_yy)),
        Err(_) => {
            let (offset, character) = text
                .chars()
                .enumerate()
                .find(|&(_, c)| char_value(c).is_none())
                .unwrap_or_else(|| (0, text.chars().next().unwrap_or('<')));
            Err(MrzError::BadCharacter {
                character,
                line: Some(line_number),
                position: start + offset,
            })
        }
    }
}

/// Parse a TD3 (passport) MRZ: two lines of exactly 44 characters
/// (ICAO 9303 part 4 §4.2.2). Long-document-number overflow is decoded here
/// too, though Part 4 defines no such rule for TD3 — it is applied by analogy
/// to part 5 note j / part 6 note j, because issuers do it in practice.
///
/// ```
/// // Pre-amendment Utopia line 1, paired with Part 3 §3.2 line 2.
/// let doc = mrz::parse_td3(
///     "P<UTOERIKSSON<<ANNA<MARIA<<<<<<<<<<<<<<<<<<<",
///     "L898902C36UTO7408122F1204159ZE184226B<<<<<10",
/// ).unwrap();
/// assert_eq!(doc.surname, "ERIKSSON");
/// assert_eq!(doc.given_names, "ANNA MARIA");
/// assert_eq!(doc.date_of_birth.to_string(), "1974-08-12"); // expanded to ISO 8601
/// assert!(doc.valid());                        // every check digit verified
/// ```
pub fn parse_td3(line1: &str, line2: &str) -> Result<MrzData, MrzError> {
    parse_td3_with(line1, line2, &ParseOptions::default())
}

/// [`parse_td3`] with an explicit [`ParseOptions`] — pin the two-digit-year
/// pivot instead of inheriting [`CURRENT_YY`](crate::CURRENT_YY).
///
/// ```
/// use mrz::{parse_td3_with, ParseOptions};
///
/// let l1 = "P<UTOERIKSSON<<ANNA<MARIA<<<<<<<<<<<<<<<<<<<";
/// let l2 = "L898902C36UTO7408122F1204159ZE184226B<<<<<10";
///
/// // The default pivot dates a `74` birth year to last century.
/// let d = parse_td3_with(l1, l2, &ParseOptions::default()).unwrap();
/// assert_eq!(d.date_of_birth.to_string(), "1974-08-12");
///
/// // Raise the pivot past 74 and the same digits read as this century —
/// // the check digits are unaffected, so the document still validates.
/// let d = parse_td3_with(l1, l2, &ParseOptions::default().with_pivot_yy(80)).unwrap();
/// assert_eq!(d.date_of_birth.to_string(), "2074-08-12");
/// assert!(d.valid());
/// ```
pub fn parse_td3_with(line1: &str, line2: &str, opts: &ParseOptions) -> Result<MrzData, MrzError> {
    for (line_number, line) in [line1, line2].into_iter().enumerate() {
        let got = line.chars().count();
        if got != 44 {
            return Err(MrzError::BadLength { expected: 44, got });
        }
        ensure_charset(line, line_number)?;
    }
    if !line1.starts_with('P') {
        return Err(MrzError::BadDocumentCode(line1[0..2].to_string()));
    }
    ensure_document_number_leads(&line2[0..9], 1, 0)?;

    let (surname, given_names) = clean_name(&line1[5..44]);

    let document_number = line2[0..9].trim_end_matches('<').to_string();
    let personal_raw = &line2[28..42];
    let overflow = read_overflow(&line2[0..9], line2.as_bytes()[9] as char, personal_raw);
    let personal = optional_tail(personal_raw, &overflow);

    let checks = Checks::from_verifications(
        Format::Td3,
        [
            match &overflow {
                Some(o) => o.check_ok,
                None => verify(&line2[0..9], line2.as_bytes()[9] as char),
            },
            verify(&line2[13..19], line2.as_bytes()[19] as char),
            verify(&line2[21..27], line2.as_bytes()[27] as char),
            verify(personal_raw, line2.as_bytes()[42] as char),
            // Composite: doc number + check, DOB + check, expiry + check +
            // personal number + check (line 2 positions 1-10, 14-20, 22-43).
            verify(
                &format!("{}{}{}", &line2[0..10], &line2[13..20], &line2[21..43]),
                line2.as_bytes()[43] as char,
            ),
        ],
    );

    let document_number_legacy_encoding = overflow.as_ref().is_some_and(|o| o.legacy);
    Ok(MrzData {
        format: Format::Td3,
        document_type: line1[0..2].trim_end_matches('<').to_string(),
        issuing_country: line1[2..5].trim_end_matches('<').to_string(),
        document_number,
        document_number_full: overflow.map(|o| o.full),
        document_number_legacy_encoding,
        surname,
        given_names,
        nationality: line2[10..13].trim_end_matches('<').to_string(),
        date_of_birth: date_field(line2, 1, 13, DateRole::Birth, opts.pivot_yy)?,
        sex: Sex::from_zone(line2.as_bytes()[20] as char),
        date_of_expiry: date_field(line2, 1, 21, DateRole::Expiry, opts.pivot_yy)?,
        optional_data_1: opt_string(personal),
        optional_data_2: None,
        mrz_lines: format!("{line1}\n{line2}"),
        checks,
        // These functions parse a single, already-final line pair/triple —
        // there is no search here for a reading to have been recovered
        // *from*, so this is always `false`. `find_and_parse_with` is the
        // only place that sets it `true`, on the specific reading its
        // damaged-capture search returns.
        damaged_recovery: false,
    })
}

/// Parse a TD2 MRZ: two lines of exactly 36 characters (ICAO 9303 part 6).
/// Covers identity-card document codes (`I`/`A`/`C`); MRV-B visas share the
/// geometry but lack a composite check digit and are not handled here.
///
/// ```
/// let doc = mrz::parse_td2(
///     "I<UTOERIKSSON<<ANNA<MARIA<<<<<<<<<<<",
///     "D231458907UTO7408122F1204159<<<<<<<6",
/// ).unwrap();
/// assert_eq!(doc.surname, "ERIKSSON");
/// assert!(doc.valid());
/// ```
pub fn parse_td2(line1: &str, line2: &str) -> Result<MrzData, MrzError> {
    parse_td2_with(line1, line2, &ParseOptions::default())
}

/// [`parse_td2`] with an explicit [`ParseOptions`] — pin the two-digit-year
/// pivot instead of inheriting [`CURRENT_YY`](crate::CURRENT_YY).
///
/// ```
/// use mrz::{parse_td2_with, ParseOptions};
///
/// let l1 = "I<UTOERIKSSON<<ANNA<MARIA<<<<<<<<<<<";
/// let l2 = "D231458907UTO7408122F1204159<<<<<<<6";
///
/// assert_eq!(
///     parse_td2_with(l1, l2, &ParseOptions::default()).unwrap().date_of_birth.to_string(),
///     "1974-08-12",
/// );
/// assert_eq!(
///     parse_td2_with(l1, l2, &ParseOptions::default().with_pivot_yy(80)).unwrap().date_of_birth.to_string(),
///     "2074-08-12",
/// );
/// ```
pub fn parse_td2_with(line1: &str, line2: &str, opts: &ParseOptions) -> Result<MrzData, MrzError> {
    for (line_number, line) in [line1, line2].into_iter().enumerate() {
        let got = line.chars().count();
        if got != 36 {
            return Err(MrzError::BadLength { expected: 36, got });
        }
        ensure_charset(line, line_number)?;
    }
    let code = line1[0..2].trim_end_matches('<');
    if !matches!(code.as_bytes().first(), Some(b'I' | b'A' | b'C')) {
        return Err(MrzError::BadDocumentCode(line1[0..2].to_string()));
    }
    ensure_document_number_leads(&line2[0..9], 1, 0)?;

    let (surname, given_names) = clean_name(&line1[5..36]);

    let document_number = line2[0..9].trim_end_matches('<').to_string();
    let optional_raw = &line2[28..35];
    let overflow = read_overflow(&line2[0..9], line2.as_bytes()[9] as char, optional_raw);
    let optional = optional_tail(optional_raw, &overflow);

    let checks = Checks::from_verifications(
        Format::Td2,
        [
            match &overflow {
                Some(o) => o.check_ok,
                None => verify(&line2[0..9], line2.as_bytes()[9] as char),
            },
            verify(&line2[13..19], line2.as_bytes()[19] as char),
            verify(&line2[21..27], line2.as_bytes()[27] as char),
            // This layout's fourth slot is absent; the format matrix stamps None.
            false,
            // Composite: line 2 positions 1-10, 14-20, 22-35 (doc number + check,
            // DOB + check, expiry + check + optional data).
            verify(
                &format!("{}{}{}", &line2[0..10], &line2[13..20], &line2[21..35]),
                line2.as_bytes()[35] as char,
            ),
        ],
    );

    let document_number_legacy_encoding = overflow.as_ref().is_some_and(|o| o.legacy);
    Ok(MrzData {
        format: Format::Td2,
        document_type: code.to_string(),
        issuing_country: line1[2..5].trim_end_matches('<').to_string(),
        document_number,
        document_number_full: overflow.map(|o| o.full),
        document_number_legacy_encoding,
        surname,
        given_names,
        nationality: line2[10..13].trim_end_matches('<').to_string(),
        date_of_birth: date_field(line2, 1, 13, DateRole::Birth, opts.pivot_yy)?,
        sex: Sex::from_zone(line2.as_bytes()[20] as char),
        date_of_expiry: date_field(line2, 1, 21, DateRole::Expiry, opts.pivot_yy)?,
        optional_data_1: opt_string(optional),
        optional_data_2: None,
        mrz_lines: format!("{line1}\n{line2}"),
        checks,
        // These functions parse a single, already-final line pair/triple —
        // there is no search here for a reading to have been recovered
        // *from*, so this is always `false`. `find_and_parse_with` is the
        // only place that sets it `true`, on the specific reading its
        // damaged-capture search returns.
        damaged_recovery: false,
    })
}

/// Parse a TD1 (ID card) MRZ: three lines of exactly 30 characters
/// (ICAO 9303 part 5).
///
/// ```
/// let doc = mrz::parse_td1(
///     "I<UTOD231458907<<<<<<<<<<<<<<<",
///     "7408122F1204159UTO<<<<<<<<<<<6",
///     "ERIKSSON<<ANNA<MARIA<<<<<<<<<<",
/// ).unwrap();
/// assert_eq!(doc.surname, "ERIKSSON");
/// assert!(doc.valid());
/// ```
pub fn parse_td1(line1: &str, line2: &str, line3: &str) -> Result<MrzData, MrzError> {
    parse_td1_with(line1, line2, line3, &ParseOptions::default())
}

/// [`parse_td1`] with an explicit [`ParseOptions`] — pin the two-digit-year
/// pivot instead of inheriting [`CURRENT_YY`](crate::CURRENT_YY).
///
/// ```
/// use mrz::{parse_td1_with, ParseOptions};
///
/// let l1 = "I<UTOD231458907<<<<<<<<<<<<<<<";
/// let l2 = "7408122F1204159UTO<<<<<<<<<<<6";
/// let l3 = "ERIKSSON<<ANNA<MARIA<<<<<<<<<<";
///
/// assert_eq!(
///     parse_td1_with(l1, l2, l3, &ParseOptions::default()).unwrap().date_of_birth.to_string(),
///     "1974-08-12",
/// );
/// assert_eq!(
///     parse_td1_with(l1, l2, l3, &ParseOptions::default().with_pivot_yy(80)).unwrap().date_of_birth.to_string(),
///     "2074-08-12",
/// );
/// ```
pub fn parse_td1_with(
    line1: &str,
    line2: &str,
    line3: &str,
    opts: &ParseOptions,
) -> Result<MrzData, MrzError> {
    for (line_number, line) in [line1, line2, line3].into_iter().enumerate() {
        let got = line.chars().count();
        if got != 30 {
            return Err(MrzError::BadLength { expected: 30, got });
        }
        ensure_charset(line, line_number)?;
    }
    let code = line1[0..2].trim_end_matches('<');
    if !matches!(code.as_bytes().first(), Some(b'I' | b'A' | b'C')) {
        return Err(MrzError::BadDocumentCode(line1[0..2].to_string()));
    }
    ensure_document_number_leads(&line1[5..14], 0, 5)?;

    let (surname, given_names) = clean_name(line3);

    let optional1_raw = &line1[15..30];
    let overflow = read_overflow(&line1[5..14], line1.as_bytes()[14] as char, optional1_raw);
    let optional1 = optional_tail(optional1_raw, &overflow);
    let optional2 = line2[18..29].trim_end_matches('<');

    let checks = Checks::from_verifications(
        Format::Td1,
        [
            match &overflow {
                Some(o) => o.check_ok,
                None => verify(&line1[5..14], line1.as_bytes()[14] as char),
            },
            verify(&line2[0..6], line2.as_bytes()[6] as char),
            verify(&line2[8..14], line2.as_bytes()[14] as char),
            // This layout's fourth slot is absent; the format matrix stamps None.
            false,
            // Composite: line1 positions 6-30, line2 positions 1-7, 9-15, 19-29.
            verify(
                &format!(
                    "{}{}{}{}",
                    &line1[5..30],
                    &line2[0..7],
                    &line2[8..15],
                    &line2[18..29]
                ),
                line2.as_bytes()[29] as char,
            ),
        ],
    );

    let document_number_legacy_encoding = overflow.as_ref().is_some_and(|o| o.legacy);
    Ok(MrzData {
        format: Format::Td1,
        document_type: code.to_string(),
        issuing_country: line1[2..5].trim_end_matches('<').to_string(),
        document_number: line1[5..14].trim_end_matches('<').to_string(),
        document_number_full: overflow.map(|o| o.full),
        document_number_legacy_encoding,
        surname,
        given_names,
        nationality: line2[15..18].trim_end_matches('<').to_string(),
        date_of_birth: date_field(line2, 1, 0, DateRole::Birth, opts.pivot_yy)?,
        sex: Sex::from_zone(line2.as_bytes()[7] as char),
        date_of_expiry: date_field(line2, 1, 8, DateRole::Expiry, opts.pivot_yy)?,
        optional_data_1: opt_string(optional1),
        optional_data_2: opt_string(optional2),
        mrz_lines: format!("{line1}\n{line2}\n{line3}"),
        checks,
        // These functions parse a single, already-final line pair/triple —
        // there is no search here for a reading to have been recovered
        // *from*, so this is always `false`. `find_and_parse_with` is the
        // only place that sets it `true`, on the specific reading its
        // damaged-capture search returns.
        damaged_recovery: false,
    })
}

/// Parse an MRV-A machine readable visa: two lines of exactly 44 characters
/// (ICAO 9303 part 7). Geometry mirrors TD3 through the expiry check digit,
/// but there is no personal-number field and no composite check digit.
///
/// ```
/// let doc = mrz::parse_mrv_a(
///     "V<UTOERIKSSON<<ANNA<MARIA<<<<<<<<<<<<<<<<<<<",
///     "L898902C<3UTO6908061F9406236ZE184226B<<<<<<<",
/// ).unwrap();
/// assert_eq!(doc.surname, "ERIKSSON");
/// assert!(doc.valid());
/// ```
pub fn parse_mrv_a(line1: &str, line2: &str) -> Result<MrzData, MrzError> {
    parse_mrv_a_with(line1, line2, &ParseOptions::default())
}

/// [`parse_mrv_a`] with an explicit [`ParseOptions`] — pin the two-digit-year
/// pivot instead of inheriting [`CURRENT_YY`](crate::CURRENT_YY).
///
/// ```
/// use mrz::{parse_mrv_a_with, ParseOptions};
///
/// let l1 = "V<UTOERIKSSON<<ANNA<MARIA<<<<<<<<<<<<<<<<<<<";
/// let l2 = "L898902C<3UTO6908061F9406236ZE184226B<<<<<<<";
///
/// let d = parse_mrv_a_with(l1, l2, &ParseOptions::default().with_pivot_yy(80)).unwrap();
/// assert_eq!(d.date_of_birth.to_string(), "2069-08-06"); // `69` reads as this century past the pivot
/// assert!(d.valid());
/// ```
pub fn parse_mrv_a_with(
    line1: &str,
    line2: &str,
    opts: &ParseOptions,
) -> Result<MrzData, MrzError> {
    for (line_number, line) in [line1, line2].into_iter().enumerate() {
        let got = line.chars().count();
        if got != 44 {
            return Err(MrzError::BadLength { expected: 44, got });
        }
        ensure_charset(line, line_number)?;
    }
    if !line1.starts_with('V') {
        return Err(MrzError::BadDocumentCode(line1[0..2].to_string()));
    }
    ensure_document_number_leads(&line2[0..9], 1, 0)?;

    let (surname, given_names) = clean_name(&line1[5..44]);

    let document_number = line2[0..9].trim_end_matches('<').to_string();
    let optional = line2[28..44].trim_end_matches('<');

    let checks = Checks::from_verifications(
        Format::MrvA,
        [
            verify(&line2[0..9], line2.as_bytes()[9] as char),
            verify(&line2[13..19], line2.as_bytes()[19] as char),
            verify(&line2[21..27], line2.as_bytes()[27] as char),
            // MRV prints neither a personal-number nor a composite check digit.
            false,
            false,
        ],
    );

    Ok(MrzData {
        format: Format::MrvA,
        document_type: line1[0..2].trim_end_matches('<').to_string(),
        issuing_country: line1[2..5].trim_end_matches('<').to_string(),
        document_number,
        // ICAO 9303 part 7 defines no overflow encoding for visas.
        document_number_full: None,
        document_number_legacy_encoding: false,
        surname,
        given_names,
        nationality: line2[10..13].trim_end_matches('<').to_string(),
        date_of_birth: date_field(line2, 1, 13, DateRole::Birth, opts.pivot_yy)?,
        sex: Sex::from_zone(line2.as_bytes()[20] as char),
        date_of_expiry: date_field(line2, 1, 21, DateRole::Expiry, opts.pivot_yy)?,
        optional_data_1: opt_string(optional),
        optional_data_2: None,
        mrz_lines: format!("{line1}\n{line2}"),
        checks,
        // These functions parse a single, already-final line pair/triple —
        // there is no search here for a reading to have been recovered
        // *from*, so this is always `false`. `find_and_parse_with` is the
        // only place that sets it `true`, on the specific reading its
        // damaged-capture search returns.
        damaged_recovery: false,
    })
}

/// Parse an MRV-B machine readable visa: two lines of exactly 36 characters
/// (ICAO 9303 part 7). Geometry mirrors TD2 through the expiry check digit,
/// but there is no personal-number field and no composite check digit.
///
/// ```
/// let doc = mrz::parse_mrv_b(
///     "V<UTOERIKSSON<<ANNA<MARIA<<<<<<<<<<<",
///     "L898902C<3UTO6908061F9406236ZE184226",
/// ).unwrap();
/// assert_eq!(doc.surname, "ERIKSSON");
/// assert!(doc.valid());
/// ```
pub fn parse_mrv_b(line1: &str, line2: &str) -> Result<MrzData, MrzError> {
    parse_mrv_b_with(line1, line2, &ParseOptions::default())
}

/// [`parse_mrv_b`] with an explicit [`ParseOptions`] — pin the two-digit-year
/// pivot instead of inheriting [`CURRENT_YY`](crate::CURRENT_YY).
///
/// ```
/// use mrz::{parse_mrv_b_with, ParseOptions};
///
/// let l1 = "V<UTOERIKSSON<<ANNA<MARIA<<<<<<<<<<<";
/// let l2 = "L898902C<3UTO6908061F9406236ZE184226";
///
/// let d = parse_mrv_b_with(l1, l2, &ParseOptions::default().with_pivot_yy(80)).unwrap();
/// assert_eq!(d.date_of_birth.to_string(), "2069-08-06");
/// assert!(d.valid());
/// ```
pub fn parse_mrv_b_with(
    line1: &str,
    line2: &str,
    opts: &ParseOptions,
) -> Result<MrzData, MrzError> {
    for (line_number, line) in [line1, line2].into_iter().enumerate() {
        let got = line.chars().count();
        if got != 36 {
            return Err(MrzError::BadLength { expected: 36, got });
        }
        ensure_charset(line, line_number)?;
    }
    if !line1.starts_with('V') {
        return Err(MrzError::BadDocumentCode(line1[0..2].to_string()));
    }
    ensure_document_number_leads(&line2[0..9], 1, 0)?;

    let (surname, given_names) = clean_name(&line1[5..36]);

    let document_number = line2[0..9].trim_end_matches('<').to_string();
    let optional = line2[28..36].trim_end_matches('<');

    let checks = Checks::from_verifications(
        Format::MrvB,
        [
            verify(&line2[0..9], line2.as_bytes()[9] as char),
            verify(&line2[13..19], line2.as_bytes()[19] as char),
            verify(&line2[21..27], line2.as_bytes()[27] as char),
            // MRV prints neither a personal-number nor a composite check digit.
            false,
            false,
        ],
    );

    Ok(MrzData {
        format: Format::MrvB,
        document_type: line1[0..2].trim_end_matches('<').to_string(),
        issuing_country: line1[2..5].trim_end_matches('<').to_string(),
        document_number,
        // ICAO 9303 part 7 defines no overflow encoding for visas.
        document_number_full: None,
        document_number_legacy_encoding: false,
        surname,
        given_names,
        nationality: line2[10..13].trim_end_matches('<').to_string(),
        date_of_birth: date_field(line2, 1, 13, DateRole::Birth, opts.pivot_yy)?,
        sex: Sex::from_zone(line2.as_bytes()[20] as char),
        date_of_expiry: date_field(line2, 1, 21, DateRole::Expiry, opts.pivot_yy)?,
        optional_data_1: opt_string(optional),
        optional_data_2: None,
        mrz_lines: format!("{line1}\n{line2}"),
        checks,
        // These functions parse a single, already-final line pair/triple —
        // there is no search here for a reading to have been recovered
        // *from*, so this is always `false`. `find_and_parse_with` is the
        // only place that sets it `true`, on the specific reading its
        // damaged-capture search returns.
        damaged_recovery: false,
    })
}

/// Undo a **dropped** (not merely misread) line-1 position-1 filler —
/// generalizes [`repair_td1_line1_unshifted`]'s transformation to other
/// formats. A genuine second document-code letter is possible; the country
/// gate below guards against shifting one away.
///
/// **Ordering is load-bearing here, unlike TD1.** TD1 tries its unshifted
/// reading as a second candidate in either order, because its own line-1
/// check digit (the document number's) arbitrates which candidate — if
/// either — is real. TD3/MRV-A/MRV-B have no check digit on line 1 at all,
/// so `consider()` in `find_and_parse_with` accepts the *first*
/// checksum-passing line-1/line-2 combination it tries that no `rank` check
/// flags, regardless of what line 1 says — meaning an unshifted candidate
/// offered only *after* the unrepaired one is dead code in practice: the
/// unrepaired reading already satisfies line 2's checksums just as well (line
/// 1 never gates them), so it always wins first and the unshifted candidate
/// never gets a chance to matter. The call sites (TD3/MRV-A/MRV-B in
/// `find_and_parse_with`) therefore try `repair_*_line1_unshifted` *before*
/// `repair_*_line1`.
///
/// This is also why the fix is a **second candidate at all**, rather than
/// applied unconditionally inside `repair_td3_line1`/`repair_mrv_line1`
/// (the first version of this fix, before either of the two points above
/// were understood). That version — despite "position 1 isn't `<`" being
/// unambiguous evidence of the drop, not a guess, for these formats (see
/// `Td3Fields`'/`MrvAFields`'/`MrvBFields`' doc comments: no diplomatic/
/// subtype variant with a genuine second letter is modeled anywhere in this
/// crate) — measured a real, reproducible **Tier-1 hit-rate regression** on
/// a 30-seed TD3 corpus (`--profile clean --seed 42`): 76.7% → 63.3%,
/// confirmed via a same-binary A/B env-var toggle to rule out the run-to-run
/// OCR-timing variance this repo's contention note already documents. The
/// mechanism: `variants()` builds `[repaired, fitted, last_resort]` per
/// candidate and deduplicates by exact string equality; mutating what
/// `repaired` is (rather than adding a second, independent `variants()` call
/// for it) also changes what `last_resort = aggressive_defiller(&repaired)`
/// evaluates to, silently removing a previously-tried, load-bearing
/// candidate string in some cases rather than only adding a new one. Kept as
/// two separate `variants()` calls — one per repair function — specifically
/// avoids that collapse: each keeps its own independent `[repaired, fitted,
/// last_resort]` triplet, so the search space is provably a strict superset
/// of the unmodified pipeline's.
///
/// Net effect, measured 30 seeds, `--profile clean`, seed 42, same-day: hit
/// rate unchanged for all three formats (TD3 76.7%, MRV-A 86.7%, MRV-B
/// 93.3% — identical to the pre-fix baseline), `document_type`/
/// `issuing_country` CER: TD3 76.67%/52.22% → 23.33%/16.67%, MRV-A
/// 6.67%/4.44% → 0%/0%, MRV-B 40.00%/26.67% → 3.33%/2.22%. Not a full fix
/// for TD3/MRV-B (some corrupted readings still win over the unshifted
/// candidate when both parse structurally, since nothing on line 1
/// discriminates between them) — a partial, hit-rate-safe improvement, not
/// a claim of completeness.
///
/// First measured via `synthpass-bench --dump-ocr` against TD3 and MRV-B
/// (`knowledge/ROADMAP.md`'s M6 note): the OCR retry loop's internal passes
/// sometimes drop this filler exactly the way TD1's did, e.g.
/// `V<BRAESKANDARI...` read as `VBRAESKANDARI...` — shifting
/// `issuing_country` (and everything after it) one position left. Silent on
/// these formats specifically because nothing check-digit-covers line 1
/// here, so it never fails a Tier-1 hit on its own, only corrupts
/// `document_type`/`issuing_country`/the name behind a passing read.
///
/// `target_width` is `l.len()` at the call site (44 for TD3/MRV-A, 36 for
/// MRV-B) — `variants()` always calls its `repair` function on an
/// already-`fit_length`-padded string (`checksum.rs`'s `variants`), so the
/// input is guaranteed to already be at the format's fixed width; the
/// length check below is a defensive no-op guard, not a real branch, for
/// the same reason [`repair_td1_line1_unshifted`] carries one.
fn unshift_line1_prefix(repaired: String, target_width: usize) -> String {
    if repaired.len() != target_width || repaired.as_bytes().get(1) == Some(&b'<') {
        return repaired;
    }
    format!("{}<{}", &repaired[0..1], &repaired[1..target_width - 1])
}

/// Whether an issuing-state slice resolves to a known state once its filler
/// padding is removed.
///
/// The repair gates below take a raw 3-byte slice off line 1, and
/// [`country_name`] is exact string equality. A state shorter than three
/// characters is filler-padded in the MRZ -- Germany's current ICAO code is `D<<` --
/// so passing the untrimmed slice asked the table for `"D<<"`, got `None`, and
/// silently discarded an otherwise correct repair for every German document
/// whose line 1 had lost its position-1 filler. `D` is the only sub-3-character
/// code in the table, so trimming cannot make any other slice newly resolve;
/// `<<<` trims to the empty string, which still does not resolve.
pub(crate) fn country_resolves(slice: &str) -> bool {
    country_name(slice.trim_end_matches('<')).is_some()
}

/// Whether a best-scoring, non-validating reading is more likely OCR that found
/// MRZ-shaped visual-inspection-zone text (card boilerplate, a printed legend)
/// than a genuine MRZ read too badly to verify.
///
/// The signal is three independent line-1/line-2 fields — the issuing state,
/// the nationality, and the date of birth — being *simultaneously*
/// unrecognizable: neither three-letter code is in the table, and the date of
/// birth field is not even six digits or fillers. None of the three carries a
/// check digit that could arbitrate a misread, so a document that fails all
/// three at once is one nothing downstream can trust. A genuinely degraded MRZ
/// does not land here — a real non-conformant line 1 (Argentina's `<AR`,
/// Spain's stateless `TAP`) still carries a resolving nationality and a real
/// date of birth, and a mis-paired-lines parser bug still resolves at least the
/// issuing state. Measured against the 2026-09-08 real-specimen dump
/// (`knowledge/benchmarks/checksum-failed-real-specimens-2026-09-08.md`): it
/// rejects 18 of the 19 no-MRZ specimens and none of the 118 hits.
fn looks_like_non_mrz_text(data: &MrzData) -> bool {
    !country_resolves(&data.issuing_country)
        && !country_resolves(&data.nationality)
        && matches!(data.date_of_birth, MrzDate::Malformed(_))
}

/// Undo a spurious extra character **inserted** at line-1 position 2, right
/// after `document_type`'s filler and before `issuing_country` — the mirror
/// image of [`unshift_line1_prefix`]'s dropped-filler case, and the missing
/// half [`unshift_line1_prefix`]'s own doc comment already flags ("not a
/// full fix... a partial, hit-rate-safe improvement, not a claim of
/// completeness").
///
/// Measured on real specimens (`crates/synthpass-ocr/examples/
/// integrity_survey.rs --dir passports --mrz-only`, 2026-08-17): 34 of 57
/// `UnrecognizedIssuingCountry` findings across 24 distinct countries shared
/// this exact shape — one garbage character prepended, the real third
/// letter lost, e.g. Czechia (`CZE`) read as `SCZ`, Iceland (`ISL`) as
/// `AIS`, Slovakia (`SVK`) as `SSV`, the UK (`GBR`) as `SGB`, the USA
/// (`USA`) as `SUS`.
///
/// **Why this needs a content-based guard, unlike the drop case.**
/// `unshift_line1_prefix` self-limits purely from shape: position 1 not
/// being `<` is unambiguous evidence of the drop, since a correctly-formed
/// line always has `<` there. This corruption leaves position 1 alone — the
/// filler survives — so shape alone can't distinguish a genuine insertion
/// from a correctly-formed line (both have `<` at position 1). Worse, some
/// real ICAO document codes genuinely have a second real letter there
/// (Doc 9303 Part 4's document-code table: `PO` = official/service,
/// `PS` = stateless, `PP` = national/ordinary passport, printed by Canada
/// and, from 2025-12-15, Cyprus — see `synthpass_core::fusion::document_types_agree`) —
/// a `fix_doc_code`-style "no real code has X there" blocklist would be
/// simply wrong for this position. [`crate::country_name`] is the
/// discriminator instead: only apply the shift when the as-read
/// `issuing_country` fails to resolve to a real code but the
/// one-position-right-shifted read does. A line with a genuine two-letter
/// document code and a genuinely correct `issuing_country` already resolves
/// on the first check and is returned unchanged.
fn shift_line1_right_at_country(repaired: String, target_width: usize) -> String {
    if repaired.len() != target_width
        || target_width < 6
        || repaired.as_bytes().get(1) != Some(&b'<')
    {
        return repaired;
    }
    if country_resolves(&repaired[2..5]) {
        return repaired;
    }
    if !country_resolves(&repaired[3..6]) {
        return repaired;
    }
    format!("{}{}<", &repaired[0..2], &repaired[3..target_width])
}

/// Tries [`shift_line1_right_at_country`] first, falling back to
/// [`unshift_line1_prefix`] when it doesn't apply.
///
/// The two can't be registered as independent `variants()` candidates in a
/// fixed order the way `repair_td3_line1`/`repair_td3_line1_unshifted` are:
/// each is a **no-op passthrough of the other's trigger case**. A dropped
/// filler (position 1 not `<`) is exactly `shift_line1_right_at_country`'s
/// guard condition for skipping — it returns the corrupted string
/// unchanged. An inserted character (position 1 still `<`) is exactly
/// `unshift_line1_prefix`'s guard condition for skipping — same thing.
/// TD3/MRV-A/MRV-B carry no check digit on line 1, so `consider()` accepts
/// whichever checksum-passing candidate it's offered first regardless of
/// what line 1 says — an unhelpful no-op tried first would silently outrun
/// the real fix for the *other* corruption, exactly the failure mode this
/// composition avoids by trying both, in order, inside one candidate.
///
/// The unshift fallback is additionally gated on [`country_name`] —
/// shared across all three callers, though only TD3 actually needs it:
/// TD3's document code genuinely has real two-letter forms (Doc 9303 Part 4's
/// document-code table: `PO` = official/service passport, `PS` = stateless
/// passport, `PP` = national/ordinary passport, printed by Canada and, from
/// 15 December 2025, Cyprus; see `synthpass_core::fusion::document_types_agree`'s
/// doc comment), which [`unshift_line1_prefix`]'s shape-only guard cannot
/// tell apart from a genuine drop (both leave position 1 as a real letter,
/// not `<`). Applying the transform unconditionally would silently corrupt
/// those — pinned by `crates/mrz/tests/line1_right_shift.rs`'s
/// `a_genuine_two_letter_document_code_is_unaffected`, which caught this
/// pre-existing gap in `unshift_line1_prefix` itself (present before this
/// fix, on the raw candidate — this composition is the first place it's
/// actually guarded). MRV-A/MRV-B also allow an issuer-defined second character after `V`, so
/// the country gate protects those codes too. Only accept the unshifted reading when it
/// actually resolves to a real country; otherwise there's no positive
/// evidence it helped, so leave the line as
/// `repair_td3_line1`/`repair_mrv_*_line1` already produced it.
fn shift_or_unshift_line1(repaired: String, target_width: usize) -> String {
    let shifted = shift_line1_right_at_country(repaired.clone(), target_width);
    if shifted != repaired {
        return shifted;
    }
    unshift_if_country_resolves(repaired, target_width)
}

/// [`unshift_line1_prefix`], accepted only when the *unshifted* reading's
/// issuing-country slot (positions 2..5) resolves to a real [`country_name`].
/// Factored out of [`shift_or_unshift_line1`] so [`repair_td2_line1_shifted`]
/// can reuse the exact same gate without also pulling in
/// [`shift_line1_right_at_country`]'s independent insertion-repair, which is
/// out of scope for TD2 (see that function's call site).
fn unshift_if_country_resolves(repaired: String, target_width: usize) -> String {
    let unshifted = unshift_line1_prefix(repaired.clone(), target_width);
    if unshifted != repaired && target_width >= 5 && country_resolves(&unshifted[2..5]) {
        unshifted
    } else {
        repaired
    }
}

fn repair_td3_line1(l: &str) -> String {
    // Issuing state must be letters; the name field suffers filler misreads.
    let l = fix_doc_code(&repair_positions(l, &[(2..5, letterize)]));
    format!("{}{}", &l[0..5], fix_name_separator(&defiller(&l[5..])))
}

/// Whether TD3 line 1, after [`repair_td3_line1`]'s ordinary repairs, already
/// carries a genuine Part 4 §4.4 document code (or the `P<` filler) *and* an
/// issuing state that resolves — the collision [`shift_or_unshift_line1`]'s
/// unshift must be refused for, not merely outvoted by a checksum TD3's line 1
/// doesn't have.
///
/// [`unshift_line1_prefix`] fires whenever position 1 is a letter, and a
/// genuine §4.4 second letter (`PP`, `PD`, `PS`, `PR`, ...) always is one too
/// — nothing on the line distinguishes "second letter of a real table code"
/// from "dropped filler" by shape alone, which is exactly why
/// [`unshift_if_country_resolves`] instead asks whether the *unshifted*
/// reading's issuer resolves. That question is not enough on its own: 67
/// pairs of a §4.4 letter and a real ISO/ICAO three-letter code collide (e.g.
/// `PP` + `NGA`, whose unshift `P<PNG` also resolves), so a genuine `PPNGA…`
/// was being silently rewritten to issuer `PNG` (#445). Checking the as-read
/// line first — a real table code plus a resolving issuer — settles those
/// collisions in favor of the printed text before the unshifted reading is
/// even considered. TD2 and MRV share [`unshift_if_country_resolves`] and are
/// deliberately not covered here: neither format has a closed document-code
/// table to check the as-read line against (see [`repair_td2_line1`]'s doc
/// comment), so there is nothing for an equivalent guard to test.
fn td3_line1_is_genuine_table_code(l: &str) -> bool {
    l.len() >= 5
        && (&l[0..2] == "P<" || crate::passport_type(&l[0..2]).is_some())
        && country_resolves(&l[2..5])
}

/// Second candidate alongside [`repair_td3_line1`] — composes both
/// [`shift_line1_right_at_country`] and [`unshift_line1_prefix`], see
/// [`shift_or_unshift_line1`]'s doc comment for why they can't be two
/// independently-ordered candidates the way TD1's are, and why the unshift
/// half is gated on [`country_name`] here specifically (TD3's document code
/// has genuine two-letter forms `unshift_line1_prefix`'s shape-only guard
/// can't tell apart from a real drop — the whole reason for the gate).
///
/// [`td3_line1_is_genuine_table_code`] runs first and, when it holds, returns
/// the as-read (ordinarily repaired) line untouched — see that function's
/// doc comment for the collision it exists to settle.
fn repair_td3_line1_shifted(l: &str) -> String {
    let target_width = l.len();
    let repaired = repair_td3_line1(l);
    if td3_line1_is_genuine_table_code(&repaired) {
        return repaired;
    }
    shift_or_unshift_line1(repaired, target_width)
}

/// Outcome of [`td3_prefix_verdict`]'s search for which single-cell deletion
/// in a too-long TD3 line 1's issuing-state slot the OCR noise inserted.
///
/// #436: `fit_length` (`crate::checksum`) shrinks whatever filler run is
/// longest — almost always the trailing name padding, never the
/// issuing-state slot — so a character inserted *there* survives untouched
/// into the "repaired" line. TD3 line 1 carries no check digit at all
/// (Doc 9303 Part 4 §4.2.1), so that unresolved slot survives as an
/// ordinary checksum-consistent success.
#[derive(Debug, PartialEq, Eq)]
enum Td3Prefix {
    /// The line's own issuing-state slot already resolves once letterized,
    /// or the line isn't the one-cell-too-long shape this deletion search
    /// applies to. Callers proceed exactly as before this fix existed.
    ///
    /// Enumerating deletions is gated on the as-read slot *not* resolving:
    /// a genuine `P<CAN` holder whose surname starts with `F` deletes to
    /// the equally real `CAF` (Central African Republic), so touching an
    /// already-resolving slot would break correct reads at a
    /// name-dependent rate.
    Keep,
    /// Exactly one single-cell deletion inside the issuing-state slot
    /// (positions 2..=4 — never the document code or its own position-1
    /// filler repair) leaves an admissible reading (see
    /// [`td3_line1_admissible`]). This is that corrected 44-character line.
    Repair(String),
    /// Two or more *distinct resulting lines* are each admissible. Nothing
    /// on line 1 can arbitrate between them, so the read is refused rather
    /// than guessed — the `COH` counterexample in
    /// `crates/mrz/tests/alignment_threat_atlas.rs` deletes to both the
    /// real, distinct `COL` and `CHL`.
    Ambiguous,
}

/// Whether a 44-character TD3 line 1 is an admissible reading: its
/// document code is real (`P<`, or one of Part 4 §4.4's genuine two-letter
/// forms — see [`passport_type`]) and its issuing state, letterized,
/// resolves in [`country_name`].
fn td3_line1_admissible(line1: &str) -> bool {
    if line1.len() != 44 {
        return false;
    }
    let doc_code = &line1[0..2];
    if doc_code != "P<" && passport_type(doc_code).is_none() {
        return false;
    }
    let Some(issuer) = line1.get(2..5) else {
        return false;
    };
    let issuer: String = issuer.chars().map(letterize).collect();
    country_resolves(&issuer)
}

/// Decides [`Td3Prefix`] for a raw TD3 line-1 candidate, computed straight
/// off the OCR text after [`normalize_line`] and [`fix_doc_code`] — before
/// [`variants`]/[`fit_length`](crate::checksum::fit_length) ever see it.
/// Every path that turns a raw candidate line into a TD3 line 1 (the merged
/// 88-char fast path, the split-line scan, `class_sweep_pass`, and
/// `damaged_pass`) must call this on that same pre-fitting text: fitting a
/// too-long line first can shrink it down to 44 characters by a route that
/// never touches the issuing-state slot, so a gate placed after fitting
/// never sees the shape this function looks for.
fn td3_prefix_verdict(line: &str) -> Td3Prefix {
    const TD3_LINE1_LEN: usize = 44;
    if line.len() != TD3_LINE1_LEN + 1 || !line.starts_with('P') || !is_mrz_charset(line) {
        return Td3Prefix::Keep;
    }
    let as_read: String = line[2..5].chars().map(letterize).collect();
    if country_resolves(&as_read) {
        return Td3Prefix::Keep;
    }
    let mut resolved: Vec<String> = Vec::new();
    for cell in 2..=4 {
        let mut candidate = String::with_capacity(TD3_LINE1_LEN);
        candidate.push_str(&line[..cell]);
        candidate.push_str(&line[cell + 1..]);
        if td3_line1_admissible(&candidate) && !resolved.contains(&candidate) {
            resolved.push(candidate);
        }
    }
    match resolved.len() {
        1 => Td3Prefix::Repair(repair_td3_line1(&resolved.remove(0))),
        0 => Td3Prefix::Keep,
        _ => Td3Prefix::Ambiguous,
    }
}

/// [`variants`] for a TD3 line-1 candidate, gated by [`td3_prefix_verdict`]
/// when `(width, prefixes)` identify the caller's two-line-format-table row
/// as TD3's. `class_sweep_pass` and `damaged_pass` share one data-driven
/// loop across TD3/MRV-A/TD2/MRV-B (see their own `two_line` tables), so the
/// gate has to be selected by row rather than hard-coded into the loop —
/// every other row delegates to [`two_line_line1_variants_shifted`], TD3's
/// table-verdict gate having no equivalent for a format with no closed
/// document-code table.
///
/// #461: the `Keep` arm used to call `variants(raw, width, rep1)` alone —
/// `rep1` is always [`repair_td3_line1`] at this row, never
/// [`repair_td3_line1_shifted`], so a line whose position-1 filler was
/// dropped by the OCR retry loop (rather than caught by
/// [`td3_prefix_verdict`]'s 45-cell search) was never unshifted here, only in
/// `find_and_parse_with`'s ordinary TD3 scan. `class_sweep_pass` and
/// `damaged_pass` both call this function to build a TD3 line 1 and then
/// cross it against a *repaired line 2* the ordinary scan never gets to try
/// before returning its own (still left-shifted) candidate first — so a
/// checksum-valid repaired line 2 paired with this still-shifted line 1 was
/// returned outright, with the wrong `document_type`/`issuing_country`/
/// name. Chaining [`repair_td3_line1_shifted`]'s candidates here, exactly as
/// `find_and_parse_with`'s `l1_candidates` already does for the ordinary
/// scan, is a **second, independent [`variants`] call** rather than
/// replacing `rep1` — see [`unshift_line1_prefix`]'s doc comment for why
/// mutating what a single repair function returns silently drops a
/// previously-tried candidate rather than only adding one.
fn td3_line1_variants(
    raw: &str,
    width: usize,
    prefixes: &[u8],
    rep1: fn(&str) -> String,
) -> Vec<String> {
    if width != 44 || prefixes != b"P" {
        return two_line_line1_variants_shifted(raw, width, prefixes, rep1);
    }
    match td3_prefix_verdict(&fix_doc_code(&normalize_line(raw))) {
        Td3Prefix::Ambiguous => Vec::new(),
        Td3Prefix::Repair(fixed) => vec![fixed],
        Td3Prefix::Keep => {
            let candidates: Vec<String> = line1_variants(raw, width, repair_td3_line1_shifted)
                .into_iter()
                .chain(line1_variants(raw, width, rep1))
                .collect();
            // #469: the unshift chain above and `rep1` can each produce a
            // *distinct* 44-character line that individually passes
            // `variants`' own checksum/length gate — one the genuine,
            // unshifted reading, the other the original left-shifted text
            // with its issuing-state slot still wrong. Both survive to
            // `single()`, which then refuses on the disagreement even
            // though only one of them is a document `td3_line1_admissible`
            // would ever accept on its own. When at least one candidate is
            // admissible, drop the ones that are not: this is the same
            // predicate `td3_prefix_verdict` already applies above, not a
            // new heuristic, and it never invents a candidate that was not
            // already produced by `variants`. If none is admissible,
            // behaviour is unchanged — `single()` still sees every
            // candidate it always did.
            if candidates.iter().any(|c| td3_line1_admissible(c)) {
                candidates
                    .into_iter()
                    .filter(|c| td3_line1_admissible(c))
                    .collect()
            } else {
                candidates
            }
        }
    }
}

/// [`td3_line1_admissible`] generalized to MRV-A/TD2/MRV-B/TD1: the right
/// width, one of the format's own first-character prefixes, and an issuing
/// state (positions 2..5, letterized) that resolves in [`country_name`].
/// Unlike TD3, none of these four formats has a closed document-code table
/// (see [`repair_td2_line1`]'s doc comment), so admissibility here can never
/// rest on "the code is in the table" — only on the issuer resolving.
///
/// TD1 is here although its line 1 carries a check digit. That digit covers
/// the nine document-number cells and the composite covers line 1's cells
/// 5..30, so neither ever looks at the document code or the issuing state. A
/// line 1 that lost its position-1 filler moves the document number one
/// cell left; with empty optional data the shifted reading's
/// document-number check cell is then the first optional-data cell, `<`
/// (value 0), and the shifted document number validates against it about
/// one time in ten. The shifted composite then differs from the true one by
/// `8 * c`, `c` being the true check digit, so it passes as well whenever
/// `c` is `0` or `5`. The check digits cannot tell the two readings apart;
/// the issuer can (see [`prefer_admissible_line1`]).
fn line1_admissible(line1: &str, width: usize, prefixes: &[u8]) -> bool {
    if line1.len() != width || !line1.bytes().next().is_some_and(|c| prefixes.contains(&c)) {
        return false;
    }
    let issuer: String = line1[2..5].chars().map(letterize).collect();
    country_resolves(&issuer)
}

/// The selection step every line-1 candidate list built by
/// [`two_line_line1_variants_shifted`] and [`td1_line1_variants`] (and TD1's
/// merged-line scan) goes through: when at least one candidate is
/// [`line1_admissible`], keep only the admissible ones, in their existing
/// order; when none is, return every candidate unchanged. A document whose
/// issuer is not in [`country_name`] is therefore never refused on this
/// basis, and no candidate is ever invented — the filter only removes.
fn prefer_admissible_line1(candidates: Vec<String>, width: usize, prefixes: &[u8]) -> Vec<String> {
    if candidates
        .iter()
        .any(|c| line1_admissible(c, width, prefixes))
    {
        candidates
            .into_iter()
            .filter(|c| line1_admissible(c, width, prefixes))
            .collect()
    } else {
        candidates
    }
}

/// [`td3_line1_variants`]'s `Keep` arm, generalized to MRV-A/TD2/MRV-B —
/// [`line1_admissible`]'s doc comment explains why these three
/// formats get [`country_name`]-only admissibility rather than TD3's table
/// check. `class_sweep_pass` and `damaged_pass` share `td3_line1_variants`
/// across all four two-line formats (see its own doc comment), so before
/// this function existed only TD3's shared candidates were ever chained with
/// their `*_line1_shifted` repair — a line whose position-1 filler was
/// dropped by the OCR retry loop reached these two passes with only the
/// still-shifted `rep1` candidate to offer, exactly the gap #468/#469 closed
/// for TD3 alone (#476 generalizes it).
///
/// Chains each format's own `repair_*_line1_shifted` variants ahead of
/// `rep1`'s plain ones — the same "second, independent `variants()` call"
/// shape [`unshift_line1_prefix`]'s doc comment requires — then, when at
/// least one resulting candidate is admissible, drops the ones that are not.
/// A genuine issuer-defined second document-code letter whose unshifted read
/// also happens to resolve (TD2/MRV's analogue of TD3's #445 collision) is
/// not resolved here the way TD3 resolves it: with no table to prefer the
/// as-read line, both readings survive the filter and disagree, so
/// [`single`]'s unanimity gate refuses rather than guessing — the correct,
/// honest outcome per #440 when line 1 alone cannot arbitrate.
fn two_line_line1_variants_shifted(
    raw: &str,
    width: usize,
    prefixes: &[u8],
    rep1: fn(&str) -> String,
) -> Vec<String> {
    let shifted: fn(&str) -> String = match (width, prefixes) {
        (44, b"V") => repair_mrv_a_line1_shifted,
        (36, b"V") => repair_mrv_b_line1_shifted,
        (36, b"IAC") => repair_td2_line1_shifted,
        _ => return line1_variants(raw, width, rep1),
    };
    let candidates: Vec<String> = line1_variants(raw, width, shifted)
        .into_iter()
        .chain(line1_variants(raw, width, rep1))
        .collect();
    prefer_admissible_line1(candidates, width, prefixes)
}

fn repair_td3_line2(l: &str) -> String {
    let l = repair_positions(
        l,
        &[
            (9..10, digitize),   // doc number check digit
            (10..13, letterize), // nationality
            (13..20, digitize),  // DOB + check digit
            (21..28, digitize),  // expiry + check digit
            (42..44, digitize),  // personal-number check + composite
        ],
    );
    // The personal-number field is filler-dominated on most passports.
    // Note: `K` ≡ `<` (both value 20 ≡ 0 mod 10) under every 7-3-1 weight, so
    // check digits are provably blind to this misread — heuristics must do it.
    format!(
        "{}{}{}",
        &l[0..28],
        aggressive_defiller(&defiller(&l[28..42])),
        &l[42..44]
    )
}

/// Deliberately does **not** call [`unshift_line1_prefix`], unlike
/// [`repair_td3_line1`]/[`repair_mrv_line1`]. TD2 shares TD1's ICAO
/// ID-document-family code space (`"I"`, `"A"`, `"C"`, and genuine
/// two-real-letter subtypes — `crates/mrz/tests/td1_line_gap.rs`'s own
/// fixture uses `document_code: "ID"` deliberately, for the sibling
/// format), so "position 1 isn't `<`" is not unambiguous evidence of a
/// dropped filler here the way it is for TD3/MRV-A/MRV-B (whose document
/// code is always a single letter plus filler, no exceptions modeled
/// anywhere in this crate). TD1 resolves that ambiguity by trying the
/// unshifted reading as a *second* candidate, letting its own line-1
/// check digit (the document number's) and the issuer's resolution decide —
/// but TD2 has no check digit on line 1 either, so a checksum can't
/// arbitrate an unshifted TD2 candidate against the unrepaired one the way
/// TD1's can. See
/// [`repair_td2_line1_shifted`] for the fix: an issuing-country-based gate,
/// not a checksum, arbitrates instead.
fn repair_td2_line1(l: &str) -> String {
    let l = fix_doc_code(&repair_positions(l, &[(2..5, letterize)]));
    format!("{}{}", &l[0..5], fix_name_separator(&defiller(&l[5..])))
}

/// Second candidate alongside [`repair_td2_line1`]: undoes a dropped
/// position-1 filler, TD2's version of the drop
/// [`repair_td3_line1_shifted`]/[`repair_mrv_a_line1_shifted`] already fix
/// for their formats — see [`repair_td2_line1`]'s doc comment for why TD2
/// couldn't get this for free the way those formats did, and why this one
/// works anyway.
///
/// **The document-code dictionary this crate's own MRZ_SEQUENCE_COMPLETENESS
/// plan proposed for this doesn't exist.** ICAO 9303 Part 5 §Note k / Part 6
/// §Note k are explicit: the document code's second character is "at the
/// discretion of the issuing State or organization" — Part 6 excludes `V` and `AC`; Part 5 also excludes `AI`
/// but permits `AC` for a crew member certificate. That's not a closed enumerable set;
/// building a "known-legitimate TD2 code" table would mean guessing at
/// real-world issuer choices with no normative ground truth, exactly the
/// kind of unproven heuristic `crate::repair::solve_substitution`'s "prove
/// it or don't touch it" discipline (and `synthpass_core::fusion.rs`'s
/// reverted 69.5%→61.5% heuristic) argue against.
///
/// The fix is [`unshift_if_country_resolves`] instead — the exact
/// country-name gate [`shift_or_unshift_line1`] already ships and has
/// measured for TD3/MRV-A/MRV-B (`crates/mrz/tests/line1_prefix_shift.rs`).
/// TD2's line-1 layout puts `issuing_country` at the same positions 2..5 as
/// TD3's, and [`crate::country_name`] — unlike a document-code table — *is*
/// a genuine closed ICAO/ISO registry already in production use. Only the
/// unshift half is reused (not [`shift_line1_right_at_country`]'s insertion
/// repair, the mirror-image corruption): this chunk's scope is the dropped
/// filler only, per `knowledge/MRZ_SEQUENCE_COMPLETENESS.md`'s Chunk 6.
///
/// Correctly leaves a genuine two-letter document code alone: unshifting
/// `"IPBRA..."` (document code `IP`, country `BRA`) produces
/// `"I<PBR..."`, whose positions 2..5 read `PBR` — not a real country — so
/// the gate fails and the original is returned untouched (pinned by
/// `crates/mrz/tests/line1_prefix_shift.rs`'s
/// `td2_with_a_genuine_two_letter_document_code_is_unaffected`). A genuinely
/// dropped filler (`"IBRA..."` from `"I<BRA..."`) unshifts to `"I<BRA..."`,
/// whose positions 2..5 read `BRA` — a real country — so the gate passes.
fn repair_td2_line1_shifted(l: &str) -> String {
    let target_width = l.len();
    unshift_if_country_resolves(repair_td2_line1(l), target_width)
}

fn repair_td2_line2(l: &str) -> String {
    let l = repair_positions(
        l,
        &[
            (9..10, digitize),   // doc number check digit
            (10..13, letterize), // nationality
            (13..20, digitize),  // DOB + check digit
            (21..28, digitize),  // expiry + check digit
            (35..36, digitize),  // composite check digit
        ],
    );
    format!(
        "{}{}{}",
        &l[0..28],
        aggressive_defiller(&defiller(&l[28..35])),
        &l[35..36]
    )
}

fn repair_td1_line1(l: &str) -> String {
    let l = fix_doc_code(&repair_positions(
        l,
        &[(2..5, letterize), (14..15, digitize)],
    ));
    format!("{}{}", &l[0..15], aggressive_defiller(&defiller(&l[15..])))
}

/// A second candidate for TD1 line 1, alongside [`repair_td1_line1`]: undoes
/// a **dropped** (not merely misread) filler at position 1.
///
/// Measured via `synthpass-bench --dump-ocr` against the M6 TD1 corpus
/// (`knowledge/ROADMAP.md`'s M6 execution note): OCR does not misread the
/// position-1 filler as some lookalike character (that case is
/// [`fix_doc_code`]'s `K`↔`<` blind spot) — it drops the glyph outright,
/// which shifts every field from `issuing_country` onward one position left
/// and reads as e.g. `IBRAFLLF2W1316...` where the truth is `I<BRAFLLF2W1316...`.
/// `variants`'s own length-fitting (`fit_length`) cannot undo this: a line
/// that arrives one character short gets padded by *extending its longest
/// filler run*, which is the trailing run, not by inserting a filler back
/// at position 1 — so the shift survives unrepaired through the ordinary
/// pipeline, and TD1 is the one format where that matters: unlike TD3 (whose
/// only check digits live on line 2), TD1's document-number check digit is
/// on line 1 itself, so this single dropped character was breaking the
/// checksum outright, not just cosmetically corrupting `issuing_country`.
///
/// Reinserting `<` at position 1 and dropping the now-redundant final
/// character (the one `fit_length` added to compensate the length deficit)
/// undoes both steps in one move. Applied *after* [`repair_td1_line1`]'s
/// ordinary pipeline, so `fix_doc_code`/letterize/digitize/defiller already
/// ran; a no-op when position 1 already reads `<` (nothing to unshift, and
/// unshifting an already-correct line would wrongly discard a real
/// character). Like every repair candidate in this module, this is not an
/// assumption — `variants` tries it *alongside* the unshifted reading, and
/// the printed check digits decide which one, if either, is real. They do
/// not decide alone: a shifted reading can validate too, so
/// [`td1_line1_variants`] and the merged-line scan then prefer the candidates
/// whose issuing state resolves (see [`line1_admissible`]).
fn repair_td1_line1_unshifted(l: &str) -> String {
    let repaired = repair_td1_line1(l);
    if repaired.len() != 30 || repaired.as_bytes().get(1) == Some(&b'<') {
        return repaired;
    }
    format!("{}<{}", &repaired[0..1], &repaired[1..29])
}

/// [`repair_td1_line1`]'s plain candidates chained with
/// [`repair_td1_line1_unshifted`]'s, narrowed by [`prefer_admissible_line1`]:
/// when at least one candidate has the width, a leading `I`/`A`/`C` and an
/// issuing state that resolves in [`country_name`], only those are returned,
/// in their existing order; when none does, every candidate is returned
/// unchanged. The ordinary TD1 scan in `find_and_parse_with`,
/// `class_sweep_pass` and `damaged_pass` share this helper, so a line 1 that
/// needs unshifting *and* whose line 2 or line 3 separately needs damaged-
/// pass recovery isn't left with only the plain (still-shifted, checksum-
/// failing) candidate to offer — #476's TD1 side of #468/#469's TD3
/// generalization.
///
/// TD1's own check digits do not make the filter redundant, as they do not
/// cover the document code or the issuing state: a shifted reading can
/// validate too, and would be returned ahead of the unshifted one. See
/// [`line1_admissible`] for how that happens.
fn td1_line1_variants(raw: &str) -> Vec<String> {
    let candidates: Vec<String> = variants(raw, 30, repair_td1_line1)
        .into_iter()
        .chain(variants(raw, 30, repair_td1_line1_unshifted))
        .collect();
    prefer_admissible_line1(candidates, 30, b"IAC")
}

/// The same preference for the damaged-capture searches that build TD1 line 1
/// candidates from one search of their own ([`substituted`] and
/// [`class_swept`]) rather than from [`variants`]. `search` is run once with
/// [`repair_td1_line1`] and once with [`repair_td1_line1_unshifted`], the
/// pairing [`td1_line1_variants`] uses, so a line 1 that lost its position-1
/// filler is also offered with the filler put back and the same one-cell (or
/// one-field) repair applied to it. The unshifted search runs only when the
/// shifted one found something: an empty shifted search returns at once, so a
/// line 1 whose only repair is the unshifted reading is not offered here.
///
/// When at least one of the combined candidates is [`line1_admissible`], only
/// the admissible ones are returned, in order and without repeats. When none
/// is, the result is exactly `search(repair_td1_line1)`, the list these sites
/// produced before the unshifted reading was added: a document whose issuer is
/// unknown gains no candidate here. Before this, a 30-cell line 1 with its
/// filler dropped and one further misread cell reached the search only as the
/// shifted line, and a shifted reading that validates was recorded as the
/// answer (`IFRAE0E0W2012...`, issuer `RAE`).
///
/// [`restored`] does not use this. Its candidates are built by inserting the
/// missing cell at every position, so the unshifted alignment is already
/// among them, and no shifted reading was found to win there.
fn td1_line1_searched(search: impl Fn(fn(&str) -> String) -> Vec<String>) -> Vec<String> {
    let plain = search(repair_td1_line1);
    if plain.is_empty() {
        return plain;
    }
    let unshifted = search(repair_td1_line1_unshifted);
    let mut seen = std::collections::HashSet::new();
    let admissible: Vec<String> = plain
        .iter()
        .chain(&unshifted)
        .filter(|c| line1_admissible(c, 30, b"IAC") && seen.insert(c.as_str()))
        .cloned()
        .collect();
    if admissible.is_empty() {
        plain
    } else {
        admissible
    }
}

fn repair_td1_line2(l: &str) -> String {
    let l = repair_positions(
        l,
        &[
            (0..7, digitize),    // DOB + check digit
            (8..15, digitize),   // expiry + check digit
            (15..18, letterize), // nationality
            (29..30, digitize),  // composite
        ],
    );
    format!(
        "{}{}{}",
        &l[0..18],
        aggressive_defiller(&defiller(&l[18..29])),
        &l[29..30]
    )
}

fn repair_td1_line3(l: &str) -> String {
    fix_name_separator(&defiller(l))
}

/// MRV name/document-code line repair, shared shape by MRV-A (44 chars) and
/// MRV-B (36 chars). Modeled on `repair_td3_line1`/`repair_td2_line1`: letterize
/// the issuing-state field, fix the doc-code filler, defiller + fix the name
/// separator. Neither `repair_positions` (range starts at index 2) nor
/// `fix_doc_code` (only ever rewrites index 1) can touch index 0, so the
/// leading `V` document code always survives repair unchanged — the caller's
/// `l1.starts_with('V')` check after repair is exactly as strict as before.
///
fn repair_mrv_line1(l: &str) -> String {
    let l = fix_doc_code(&repair_positions(l, &[(2..5, letterize)]));
    format!("{}{}", &l[0..5], fix_name_separator(&defiller(&l[5..])))
}

fn repair_mrv_a_line1(l: &str) -> String {
    repair_mrv_line1(l)
}

fn repair_mrv_b_line1(l: &str) -> String {
    repair_mrv_line1(l)
}

/// Second candidate alongside `repair_mrv_a_line1`/`repair_mrv_b_line1` —
/// see [`unshift_line1_prefix`]'s doc comment for why this is additive, not
/// a replacement, and why the call site must try this one *first*. MRV-A/
/// MRV-B's code can have an issuer-defined second character after `V`, so
/// this remains a second candidate rather than an unconditional rewrite.
/// The country gate and the hit-rate regression are documented on
/// [`unshift_line1_prefix`].
fn repair_mrv_a_line1_unshifted(l: &str) -> String {
    let target_width = l.len();
    unshift_line1_prefix(repair_mrv_a_line1(l), target_width)
}

/// See [`repair_mrv_a_line1_unshifted`] — identical reasoning, MRV-B side.
fn repair_mrv_b_line1_unshifted(l: &str) -> String {
    let target_width = l.len();
    unshift_line1_prefix(repair_mrv_b_line1(l), target_width)
}

/// Third candidate alongside `repair_mrv_a_line1`/`repair_mrv_a_line1_unshifted`
/// — see [`shift_line1_right_at_country`]'s doc comment, and
/// [`repair_td3_line1_shifted`]'s for why the call site must try this one
/// *before* `repair_mrv_a_line1_unshifted`.
fn repair_mrv_a_line1_shifted(l: &str) -> String {
    let target_width = l.len();
    shift_or_unshift_line1(repair_mrv_a_line1(l), target_width)
}

/// See [`repair_mrv_a_line1_shifted`] — identical reasoning, MRV-B side.
fn repair_mrv_b_line1_shifted(l: &str) -> String {
    let target_width = l.len();
    shift_or_unshift_line1(repair_mrv_b_line1(l), target_width)
}

/// MRV-A line-2 repair: same geometry as TD3 through the expiry check digit,
/// but positions 28..44 are free-form optional data with no check digit of
/// its own — unlike `repair_td3_line2`, we must NOT digitize/defiller the
/// tail as if it were a personal-number + composite check field, since that
/// data is never checked and unconstrained.
fn repair_mrv_a_line2(l: &str) -> String {
    repair_positions(
        l,
        &[
            (9..10, digitize),   // doc number check digit
            (10..13, letterize), // nationality
            (13..20, digitize),  // DOB + check digit
            (21..28, digitize),  // expiry + check digit
        ],
    )
}

/// MRV-B line-2 repair: same geometry as TD2 through the expiry check digit;
/// positions 28..36 are free-form optional data, left untouched.
fn repair_mrv_b_line2(l: &str) -> String {
    repair_positions(
        l,
        &[
            (9..10, digitize),   // doc number check digit
            (10..13, letterize), // nationality
            (13..20, digitize),  // DOB + check digit
            (21..28, digitize),  // expiry + check digit
        ],
    )
}

/// Scan free-form text (e.g. OCR output) for an MRZ and parse it.
///
/// Tries TD3, MRV-B, MRV-A, TD1, then TD2. Tolerates HTML-escaped fillers (`&lt;`, as produced by
/// docling's Markdown) and MRZ lines merged onto a single physical line.
///
/// A reading whose check digits all validate is returned immediately, unless a
/// line check flags it as probably holding a wrong physical line: check digits
/// cannot tell, because a format's line 1 (and, on TD1, line 3) enters few or
/// none of them, so a second reading of line 2, a visual-zone header or a name
/// line can stand in for it and the zone still validates. A flagged zone is
/// kept aside while the scan (and the damaged-capture pass below) looks for an
/// unflagged valid one, which then wins; when there is none, the flagged zone
/// is returned. The checks only re-rank between valid zones — they never
/// refuse one. A zone is flagged when
///
/// - line 1's issuing state (cells 2..5) is not in [`country_name`]'s table;
/// - two of its lines are near-identical (similarity of at least 0.6 after
///   dropping fillers and folding lookalike characters, where the most similar
///   pair in a correctly read zone scores at most 0.30); or
/// - a two-line format's line 1 holds a digit from cell 5 on, where the name
///   field is (TD1 is exempt).
///
/// When no candidate fully validates, a damaged-capture pass may reconstruct one.
/// Otherwise the fallback ranks by verified/applicable check-digit fraction,
/// then applicable count, and returns the best reading with its honest (partially `false`)
/// [`Checks`], so callers can see how close the read came and decide whether to
/// escalate. When nothing validates and nothing falls back either, but some
/// candidate's document number began with a filler, [`MrzError::LeadingFiller`]
/// is returned instead of a bare [`MrzError::IncompleteSequence`] — it says
/// *why* nothing here parsed, which "incomplete" does not. [`MrzError::NotFound`]
/// means nothing MRZ-shaped was found at all — or that the best-scoring
/// candidate fails every structural signal at once (unrecognized issuing state
/// *and* nationality *and* a non-numeric date of birth), which is OCR that
/// matched MRZ-shaped visual-zone text rather than a real MRZ read too badly
/// to verify.
///
/// ```
/// let text = "## PASSPORT\n\nsome OCR noise\n\n\
///     P<UTOERIKSSON<<ANNA<MARIA<<<<<<<<<<<<<<<<<<<\n\
///     L898902C36UTO7408122F1204159ZE184226B<<<<<10\n\n\
///     footer text";
/// let doc = mrz::find_and_parse(text).unwrap();
/// assert_eq!(doc.surname, "ERIKSSON");
/// assert!(doc.valid());
/// ```
pub fn find_and_parse(text: &str) -> Result<MrzData, MrzError> {
    find_and_parse_with(text, &ParseOptions::default())
}

/// Rejoin one OCR-inserted space only when two adjacent fragments recover an
/// exact MRZ line width. Widths are UTF-8 bytes of the text as read, before
/// normalization, so a fragment holding a non-ASCII character is measured
/// wider than the cells it prints. A token that is already 30, 36 or 44 bytes
/// is a complete candidate and is never consumed into its neighbour. The join
/// *replaces* the two fragments: the pair is not kept as an extra candidate, so
/// a pair that happens to add up to a line width is no longer read as two
/// separate tokens. The caller still applies its existing long-token filter
/// and physical-line fallback after this step.
fn rejoin_exact_width_tokens(line: &str) -> Vec<String> {
    let is_line_width = |len| matches!(len, 30 | 36 | 44);
    let raw: Vec<&str> = line.split_whitespace().collect();
    let mut tokens = Vec::with_capacity(raw.len());
    let mut i = 0;

    while i < raw.len() {
        if i + 1 < raw.len()
            && !is_line_width(raw[i].len())
            && !is_line_width(raw[i + 1].len())
            && is_line_width(raw[i].len() + raw[i + 1].len())
        {
            let mut joined = String::with_capacity(raw[i].len() + raw[i + 1].len());
            joined.push_str(raw[i]);
            joined.push_str(raw[i + 1]);
            tokens.push(joined);
            i += 2;
        } else {
            tokens.push(raw[i].to_string());
            i += 1;
        }
    }

    tokens
}

/// The candidate MRZ lines of an OCR text, in reading order: the one line walk
/// [`find_and_parse_with`] scans and [`crate::select_line1`] draws its
/// alternatives from, so the two agree about what counts as a line. The one
/// exception is a merged zone with no whitespace between its lines, which
/// [`find_and_parse_with`] splits on its own (below) and `select_line1` never
/// sees.
///
/// Markdown/HTML pipelines escape the filler character, so `&lt;` is undone
/// first. OCR often emits several MRZ lines as ONE physical line,
/// space-separated (docling renders the whole zone as a single paragraph), so
/// long whitespace-separated tokens are treated as individual candidate lines.
/// The lines are returned as read: `normalize_line` is the caller's step.
pub(crate) fn candidate_lines(text: &str) -> Vec<String> {
    let text = text.replace("&lt;", "<");
    let mut out: Vec<String> = Vec::new();
    for line in text.lines() {
        let tokens: Vec<String> = rejoin_exact_width_tokens(line)
            .into_iter()
            .filter(|t| t.len() >= 20)
            .collect();
        if tokens.len() >= 2 {
            out.extend(tokens);
        } else {
            out.push(line.to_string());
        }
    }
    out
}

/// [`find_and_parse`] with an explicit [`ParseOptions`].
///
/// Both entry points normalize the input the same way before scanning, which is
/// what lets a Markdown-escaped MRZ and one collapsed onto a single physical
/// line still read as the document they came from:
///
/// ```
/// use mrz::{find_and_parse_with, ParseOptions};
///
/// // `&lt;` as produced by docling's Markdown, and both lines merged into one.
/// let text = "P&lt;UTOERIKSSON&lt;&lt;ANNA&lt;MARIA&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;\
///             L898902C36UTO7408122F1204159ZE184226B&lt;&lt;&lt;&lt;&lt;10";
///
/// let doc = find_and_parse_with(text, &ParseOptions::default()).unwrap();
/// assert_eq!(doc.surname, "ERIKSSON");
/// assert!(doc.valid());
/// ```
pub fn find_and_parse_with(text: &str, opts: &ParseOptions) -> Result<MrzData, MrzError> {
    let owned_lines = candidate_lines(text);
    let lines: Vec<&str> = owned_lines.iter().map(String::as_str).collect();

    // Best parseable-but-checksum-failed hit, reported when nothing fully
    // validates so callers can see which check digits failed and how close the
    // read came. Ties keep the earlier candidate: the repair pipeline emits its
    // most conservative variants first, so the first reading at a given score
    // is the one that assumed least about the OCR noise.
    let mut fallback: Option<MrzData> = None;
    // The first checksum-valid zone that a `crate::rank` check flagged as
    // probably holding a wrong physical line. It is not returned by
    // `consider`: the scan keeps looking for an unflagged valid zone, and this
    // one is returned only when none turns up (see its use after the damaged
    // pass). First wins, like `fallback`, for the same reason.
    let mut flagged_first: Option<MrzData> = None;
    let mut consider = |data: MrzData| -> Option<MrzData> {
        if data.valid() {
            if crate::rank::flagged(&data) {
                flagged_first.get_or_insert(data);
                return None;
            }
            return Some(data);
        }
        match &fallback {
            Some(best)
                if fallback_rank(&best.checks, &data.checks) != core::cmp::Ordering::Less => {}
            _ => fallback = Some(data),
        }
        None
    };

    // The first structural refusal any candidate line pair/triple hit — today
    // only `LeadingFiller`, from a document-number field whose first cell is
    // the filler. Kept like `fallback` (first one wins: the repair pipeline
    // tries its most conservative variants first), and consulted only in the
    // final precedence below, after a validating reading and a
    // checksum-failed `fallback` — see its use there for why a refused
    // candidate outranks `IncompleteSequence`/`NotFound` but never a reading
    // that actually parsed.
    let mut refused: Option<MrzError> = None;
    let mut note_refusal = |result: Result<MrzData, MrzError>| -> Option<MrzData> {
        match result {
            Ok(data) => Some(data),
            Err(e @ MrzError::LeadingFiller { .. }) => {
                refused.get_or_insert(e);
                None
            }
            Err(_) => None,
        }
    };

    // The first format whose line-1 document-code prefix was recognized
    // among the *split-line* candidates below, even though no companion line
    // ever combined with it into a full parse — kept only from the
    // split-line loops, never the merged-single-token fast path just above
    // each one: a merged token already carries the full byte length for
    // every field the format has, so if nothing there validates that is a
    // checksum/repair problem, not a missing-line one. Consulted only if
    // `fallback` is still `None` at the very end, to distinguish
    // [`MrzError::IncompleteSequence`] from a bare
    // [`MrzError::NotFound`] — see `knowledge/MRZ_SEQUENCE_COMPLETENESS.md`
    // chunk 4. Purely additive bookkeeping: it never influences which
    // `MrzData` is returned, only which error variant is returned when none
    // is.
    let mut shape_seen: Option<Format> = None;

    // TD3: a line starting with 'P' followed by a candidate line — or both
    // 44-char lines merged into one ~88-char physical line.
    for i in 0..lines.len() {
        let merged = normalize_line(lines[i]);
        if merged.starts_with('P') && (84..=92).contains(&merged.len()) && is_mrz_charset(&merged) {
            let head = &merged[0..44];
            let tail = &merged[44..];
            // `head` is always exactly 44 characters by construction (the
            // split point is fixed), so `td3_prefix_verdict` — which only
            // ever fires on a 45-character candidate — is a documented no-op
            // here today. It is still called, so a future change to the
            // split point cannot silently reopen this path to the same
            // unresolved-issuer defect the split-line scan below closes.
            match td3_prefix_verdict(&fix_doc_code(head)) {
                Td3Prefix::Ambiguous => {}
                Td3Prefix::Repair(l1) => {
                    for l2 in variants(tail, 44, repair_td3_line2) {
                        if let Some(data) = note_refusal(parse_td3_with(&l1, &l2, opts)) {
                            if let Some(valid) = consider(data) {
                                return Ok(valid);
                            }
                        }
                    }
                }
                Td3Prefix::Keep => {
                    for l1 in [
                        repair_td3_line1_shifted(head),
                        repair_td3_line1(head),
                        head.to_string(),
                    ] {
                        for l2 in variants(tail, 44, repair_td3_line2) {
                            if let Some(data) = note_refusal(parse_td3_with(&l1, &l2, opts)) {
                                if let Some(valid) = consider(data) {
                                    return Ok(valid);
                                }
                            }
                        }
                    }
                }
            }
        }

        // A line 1 that arrived exactly one cell too long gets a narrower,
        // more targeted pass first: see `td3_prefix_verdict`. Both non-`Keep`
        // outcomes bypass the ordinary length-fitting candidates below
        // entirely — `Repair` because it is already the better-evidenced
        // reading, `Ambiguous` because those candidates cannot tell the
        // unresolved issuing state apart from a genuine read either, so
        // retrying them would just reproduce the same checksum-consistent
        // wrong issuer.
        match td3_prefix_verdict(&fix_doc_code(&merged)) {
            Td3Prefix::Repair(l1) => {
                shape_seen.get_or_insert(Format::Td3);
                for l2_raw in lines.iter().skip(i + 1).take(3) {
                    for l2 in variants(l2_raw, 44, repair_td3_line2) {
                        if let Some(data) = note_refusal(parse_td3_with(&l1, &l2, opts)) {
                            if let Some(valid) = consider(data) {
                                return Ok(valid);
                            }
                        }
                    }
                }
                continue;
            }
            Td3Prefix::Ambiguous => {
                shape_seen.get_or_insert(Format::Td3);
                continue;
            }
            Td3Prefix::Keep => {}
        }

        let l1_candidates = line1_variants(lines[i], 44, repair_td3_line1_shifted)
            .into_iter()
            .chain(line1_variants(lines[i], 44, repair_td3_line1));
        for l1 in l1_candidates {
            if !l1.starts_with('P') {
                continue;
            }
            shape_seen.get_or_insert(Format::Td3);
            for l2_raw in lines.iter().skip(i + 1).take(3) {
                for l2 in variants(l2_raw, 44, repair_td3_line2) {
                    if let Some(data) = note_refusal(parse_td3_with(&l1, &l2, opts)) {
                        if let Some(valid) = consider(data) {
                            return Ok(valid);
                        }
                    }
                }
            }
        }
    }

    // MRV-B: a line starting with 'V' followed by a candidate line — or both
    // 36-char lines merged into one ~68-76 char physical line. Tried before
    // MRV-A: both share the 'V' document-code prefix (no length hint from the
    // code itself), and `variants`'s padding tolerance (+14) is far more
    // generous than its truncation tolerance (+4) — trying the *narrower*
    // format first means a genuine MRV-B line never gets loosely padded up
    // and misparsed as MRV-A before MRV-B gets a chance at its exact length.
    for i in 0..lines.len() {
        let merged = normalize_line(lines[i]);
        if merged.starts_with('V') && (68..=76).contains(&merged.len()) && is_mrz_charset(&merged) {
            let head = &merged[0..36];
            let tail = &merged[36..];
            for l1 in [
                repair_mrv_b_line1_shifted(head),
                repair_mrv_b_line1_unshifted(head),
                repair_mrv_b_line1(head),
                head.to_string(),
            ] {
                for l2 in variants(tail, 36, repair_mrv_b_line2) {
                    if let Some(data) = note_refusal(parse_mrv_b_with(&l1, &l2, opts)) {
                        if let Some(valid) = consider(data) {
                            return Ok(valid);
                        }
                    }
                }
            }
        }

        let l1_candidates = line1_variants(lines[i], 36, repair_mrv_b_line1_shifted)
            .into_iter()
            .chain(line1_variants(lines[i], 36, repair_mrv_b_line1_unshifted))
            .chain(line1_variants(lines[i], 36, repair_mrv_b_line1));
        for l1 in l1_candidates {
            if !l1.starts_with('V') {
                continue;
            }
            shape_seen.get_or_insert(Format::MrvB);
            for l2_raw in lines.iter().skip(i + 1).take(3) {
                for l2 in variants(l2_raw, 36, repair_mrv_b_line2) {
                    if let Some(data) = note_refusal(parse_mrv_b_with(&l1, &l2, opts)) {
                        if let Some(valid) = consider(data) {
                            return Ok(valid);
                        }
                    }
                }
            }
        }
    }

    // MRV-A: a line starting with 'V' followed by a candidate line — or both
    // 44-char lines merged into one ~84-92 char physical line. Disjoint from
    // TD3 ('P'-prefixed) and TD1/TD2 (I/A/C-prefixed), so no cannibalization
    // against those; see the MRV-B comment above for why MRV-B runs first.
    for i in 0..lines.len() {
        let merged = normalize_line(lines[i]);
        if merged.starts_with('V') && (84..=92).contains(&merged.len()) && is_mrz_charset(&merged) {
            let head = &merged[0..44];
            let tail = &merged[44..];
            for l1 in [
                repair_mrv_a_line1_shifted(head),
                repair_mrv_a_line1_unshifted(head),
                repair_mrv_a_line1(head),
                head.to_string(),
            ] {
                for l2 in variants(tail, 44, repair_mrv_a_line2) {
                    if let Some(data) = note_refusal(parse_mrv_a_with(&l1, &l2, opts)) {
                        if let Some(valid) = consider(data) {
                            return Ok(valid);
                        }
                    }
                }
            }
        }

        let l1_candidates = line1_variants(lines[i], 44, repair_mrv_a_line1_shifted)
            .into_iter()
            .chain(line1_variants(lines[i], 44, repair_mrv_a_line1_unshifted))
            .chain(line1_variants(lines[i], 44, repair_mrv_a_line1));
        for l1 in l1_candidates {
            if !l1.starts_with('V') {
                continue;
            }
            shape_seen.get_or_insert(Format::MrvA);
            for l2_raw in lines.iter().skip(i + 1).take(3) {
                for l2 in variants(l2_raw, 44, repair_mrv_a_line2) {
                    if let Some(data) = note_refusal(parse_mrv_a_with(&l1, &l2, opts)) {
                        if let Some(valid) = consider(data) {
                            return Ok(valid);
                        }
                    }
                }
            }
        }
    }

    // TD1: three candidate lines starting with I/A/C — tolerating a gap
    // between them (line 2 within the next 3 detected lines after line 1,
    // line 3 within the next 3 after line 2), or all three merged into one
    // ~90-char physical line. Runs before TD2 below deliberately: a genuine
    // TD1 line 1 starts with 'I' too, and `variants`'s padding tolerance
    // (+14) is generous enough that a 30-char TD1 line is a valid-shaped TD2
    // line-1 candidate once padded — see the MRV-B-before-MRV-A comment
    // above for the same cannibalization hazard, guarded here by running
    // first rather than by any length check
    // (`a_genuine_td1_never_parses_as_td2` pins this).
    //
    // The gap tolerance exists because this crate's own OCR probe
    // (`synthpass-bench --dump-ocr`, see knowledge/ROADMAP.md's M6 note)
    // found TD1's three MRZ rows are not always the *next* three detected
    // lines: the OCR engine's internal multi-pass retry loop concatenates
    // several attempts into one text blob, and a pass that fails to detect
    // line 3 as its own region leaves the watermark or a stray repeated
    // line sitting where line 3 "should" be, adjacent to a line 1/line 2
    // pair from a *different* pass. `take(3)`, not an unbounded scan, keeps
    // this from turning into a scan of the whole page — same bound the
    // two-line formats below already use for their own gap tolerance.
    for i in 0..lines.len() {
        let merged = normalize_line(lines[i]);
        if matches!(merged.as_bytes().first(), Some(b'I' | b'A' | b'C'))
            && (86..=94).contains(&merged.len())
            && is_mrz_charset(&merged)
        {
            let head = &merged[0..30];
            let mid = &merged[30..60];
            let tail = &merged[60..];
            // The same admissibility preference `td1_line1_variants` applies
            // to the per-line scan below: a shifted `head` can validate too.
            let l1_candidates = prefer_admissible_line1(
                vec![
                    repair_td1_line1(head),
                    repair_td1_line1_unshifted(head),
                    head.to_string(),
                ],
                30,
                b"IAC",
            );
            for l1 in l1_candidates {
                for l2 in [repair_td1_line2(mid), mid.to_string()] {
                    for l3 in variants(tail, 30, repair_td1_line3) {
                        if let Some(data) = note_refusal(parse_td1_with(&l1, &l2, &l3, opts)) {
                            if let Some(valid) = consider(data) {
                                return Ok(valid);
                            }
                        }
                    }
                }
            }
        }

        for l1 in td1_line1_variants(lines[i]) {
            if !matches!(l1.as_bytes().first(), Some(b'I' | b'A' | b'C')) {
                continue;
            }
            shape_seen.get_or_insert(Format::Td1);
            for (j, l2_raw) in lines.iter().enumerate().skip(i + 1).take(3) {
                for l2 in variants(l2_raw, 30, repair_td1_line2) {
                    for l3_raw in lines.iter().skip(j + 1).take(3) {
                        for l3 in variants(l3_raw, 30, repair_td1_line3) {
                            if let Some(data) = note_refusal(parse_td1_with(&l1, &l2, &l3, opts)) {
                                if let Some(valid) = consider(data) {
                                    return Ok(valid);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    // An intact TD1 triple carries stronger format evidence than a 36-cell
    // reading manufactured by padding its first two 30-cell rows (#409, the
    // Türkiye 2020 specimen: its printed check digits fail, and the padded TD2
    // happened to verify one more digit). Record the exact start positions, so
    // a separate genuine TD2 elsewhere in the OCR text stays eligible. A
    // checksum failure does not erase the TD1 shape.
    let intact_td1_starts = intact_td1_starts(&lines, opts);

    // TD2: two 36-char lines starting with I/A/C — or both merged into one
    // ~72-char physical line.
    for &line in &lines {
        let merged = normalize_line(line);
        if (68..=76).contains(&merged.len())
            && is_mrz_charset(&merged)
            && matches!(merged.as_bytes().first(), Some(b'I' | b'A' | b'C'))
        {
            let head = &merged[0..36];
            let tail = &merged[36..];
            for l1 in [
                repair_td2_line1_shifted(head),
                repair_td2_line1(head),
                head.to_string(),
            ] {
                for l2 in variants(tail, 36, repair_td2_line2) {
                    if let Some(data) = note_refusal(parse_td2_with(&l1, &l2, opts)) {
                        if let Some(valid) = consider(data) {
                            return Ok(valid);
                        }
                    }
                }
            }
        }
    }
    for i in 0..lines.len().saturating_sub(1) {
        if intact_td1_starts.contains(&i) {
            continue;
        }
        let l1_candidates = line1_variants(lines[i], 36, repair_td2_line1_shifted)
            .into_iter()
            .chain(line1_variants(lines[i], 36, repair_td2_line1));
        for l1 in l1_candidates {
            if !matches!(l1.as_bytes().first(), Some(b'I' | b'A' | b'C')) {
                continue;
            }
            shape_seen.get_or_insert(Format::Td2);
            for l2 in variants(lines[i + 1], 36, repair_td2_line2) {
                if let Some(data) = note_refusal(parse_td2_with(&l1, &l2, opts)) {
                    if let Some(valid) = consider(data) {
                        return Ok(valid);
                    }
                }
            }
        }
    }

    // Nothing validated on any ordinary variant. Before giving up, try the
    // damaged-capture case (see `crate::repair`): a line that arrived *narrow*
    // because the recognizer dropped a destroyed glyph instead of emitting a
    // placeholder, so every field after the damage is shifted and no amount of
    // lookalike repair can help. Runs only here, at the end, and only when
    // some line already matched a format's shape, checksum-failed, *or* a
    // structural refusal — a document with no MRZ at all never pays for it.
    // The `refused.is_some()` half of this gate matters: a TD3 whose only
    // candidate hit `LeadingFiller` never sets `fallback` (its `Err` skips
    // `consider` entirely), so without it a refused reading would fall
    // through to `IncompleteSequence` instead of getting a chance at repair.
    // A flagged valid zone opens this gate too: it may have an unflagged
    // alternative that only the damaged pass can build.
    if fallback.is_some() || refused.is_some() || flagged_first.is_some() {
        if let Some(mut data) = damaged_pass(&lines, opts, &intact_td1_starts) {
            // `damaged_pass` (and `class_sweep_pass`, which it tries first)
            // is the only path a reading can take here — see
            // `MrzData::damaged_recovery`'s doc comment for what this flags
            // and why a caller re-reading the source image might care.
            data.damaged_recovery = true;
            if !crate::rank::flagged(&data) {
                return Ok(data);
            }
            flagged_first.get_or_insert(data);
        }
    }

    // No unflagged valid zone exists, so the flagged one is the answer: the
    // ordinary scan's if it found one, else the damaged pass's. Ranking only
    // ever prefers between valid zones, so this comes before the fallback and
    // refusal precedence below and never lets a flagged zone be refused.
    if let Some(data) = flagged_first {
        return Ok(data);
    }

    // A best-scoring reading that never validated *and* fails every structural
    // signal at once (see `looks_like_non_mrz_text`) is OCR that found
    // MRZ-shaped VIZ text, not a genuine MRZ — reporting it as a checksum-failed
    // record invites a silent wrong extraction downstream. Report it as
    // not-found instead.
    if let Some(data) = &fallback {
        if !data.valid() && looks_like_non_mrz_text(data) {
            return Err(MrzError::NotFound);
        }
    }

    // Precedence among what is left: a validating reading already returned
    // above; next best is a checksum-failed `fallback` (a caller can see how
    // close the read came); next is the first structural refusal any
    // candidate hit (still more informative than "not found" — it says
    // *why* nothing here parsed); only then the shape-based
    // `IncompleteSequence`/bare `NotFound`.
    match fallback {
        Some(data) => Ok(data),
        None => Err(refused.unwrap_or_else(|| match shape_seen {
            Some(format) => MrzError::IncompleteSequence {
                format,
                lines_found: 1,
                lines_expected: expected_lines(format),
            },
            None => MrzError::NotFound,
        })),
    }
}

/// How many MRZ lines `format` requires — the one place that count lives,
/// so [`MrzError::IncompleteSequence`] doesn't hardcode it at its one call
/// site above.
fn expected_lines(format: Format) -> u8 {
    match format {
        Format::Td1 => 3,
        Format::Td2 | Format::Td3 | Format::MrvA | Format::MrvB => 2,
    }
}

/// A two-line format's parse entry point, as [`damaged_pass`]'s table stores it.
type TwoLineParse = fn(&str, &str, &ParseOptions) -> Result<MrzData, MrzError>;

/// One row of [`damaged_pass`]'s two-line format table: the ICAO line width,
/// the line-1 document-code bytes that identify the format, the per-line
/// lookalike repairs, and the parser. Adding a two-line format is a row here
/// rather than another nested loop.
type TwoLineFormat = (
    usize,
    &'static [u8],
    fn(&str) -> String,
    fn(&str) -> String,
    TwoLineParse,
);

/// Upper bound on parse attempts across the whole damaged pass.
///
/// The pass is a search, and a search inside an OCR retry loop needs a ceiling
/// rather than good intentions — the same reasoning as
/// `checksum::MAX_DEFILL_PASSES`. Generous enough for one narrow line crossed
/// against the ordinary variants of its neighbours; far below anything a user
/// would notice.
const MAX_DAMAGED_ATTEMPTS: usize = 200_000;

/// Concrete candidate readings for a line that is **exactly one** character
/// too narrow, with the missing character swept across every insertion point.
///
/// One is not an arbitrary cutoff. A single destroyed position admits one
/// residue class, which the calendar constraint in [`accept_damaged`] can cut
/// to a unique reading; two destroyed positions leave hundreds of readings that
/// every check digit accepts (`tests/repair.rs` pins this), so no amount of
/// searching can return an answer — it can only return a guess. Attempting it
/// would cost 37² candidates per insertion point for a result this function is
/// required to throw away.
///
/// The first cell is the format letter. Never fill an unknown there: a
/// missing passport letter must not become an invented visa letter.
///
/// Empty for any other line, which is what keeps this off the happy path.
fn restored(raw: &str, target: usize, repair: fn(&str) -> String) -> Vec<String> {
    let n = normalize_line(raw);
    if n.len() + 1 != target || !is_mrz_charset(&n) {
        return Vec::new();
    }
    let mut seen = std::collections::HashSet::new();
    let mut out: Vec<String> = Vec::new();
    for shaped in crate::repair::width_candidates(&n, target) {
        if shaped.starts_with(crate::repair::UNKNOWN) || !shaped.contains(crate::repair::UNKNOWN) {
            continue;
        }
        for concrete in crate::repair::concrete_fillings(&shaped) {
            for form in [repair(&concrete), concrete] {
                if seen.insert(form.clone()) {
                    out.push(form);
                }
            }
        }
    }
    out
}

/// Concrete candidate readings for a line that arrived **exactly** the target
/// width, with a single glyph swept across [`crate::repair::CONFUSABLES`].
///
/// The mirror image of [`restored`]: that function handles a line one
/// character too narrow, this one a line the right width but with one
/// position misread. Guarded by `n.len() == target` rather than `restored`'s
/// `n.len() + 1 == target`, so the two are mutually exclusive by
/// construction — a line can match at most one of them, and there is no
/// ordering question between the two repair kinds.
///
/// Empty for any other line, which is what keeps this off the happy path.
fn substituted(raw: &str, target: usize, repair: fn(&str) -> String) -> Vec<String> {
    let n = normalize_line(raw);
    if n.len() != target || !is_mrz_charset(&n) {
        return Vec::new();
    }
    let mut seen = std::collections::HashSet::new();
    let mut out: Vec<String> = Vec::new();
    for concrete in crate::repair::substitution_candidates(&n) {
        for form in [repair(&concrete), concrete] {
            if seen.insert(form.clone()) {
                out.push(form);
            }
        }
    }
    out
}

/// The fields on one line that carry a check digit of their own, as
/// `(field start, field end, check-digit column, kind)` in 0-based columns.
///
/// Only these can be class-swept, because the sweep is arbitrated by the
/// field's *own* check digit. A field covered only by the composite — TD1's
/// optional data, TD2/MRV optional data — has no local arbiter, and sweeping
/// it would be a guess the format cannot check.
type CdFields = &'static [(usize, usize, usize, FieldKind)];

const TD1_LINE1_CD_FIELDS: CdFields = &[(5, 14, 14, FieldKind::DocumentNumber)];
const TD1_LINE2_CD_FIELDS: CdFields = &[(0, 6, 6, FieldKind::Date), (8, 14, 14, FieldKind::Date)];
const TD2_LINE2_CD_FIELDS: CdFields = &[
    (0, 9, 9, FieldKind::DocumentNumber),
    (13, 19, 19, FieldKind::Date),
    (21, 27, 27, FieldKind::Date),
];
const TD3_LINE2_CD_FIELDS: CdFields = &[
    (0, 9, 9, FieldKind::DocumentNumber),
    (13, 19, 19, FieldKind::Date),
    (21, 27, 27, FieldKind::Date),
    (28, 42, 42, FieldKind::PersonalNumber),
];
const MRV_LINE2_CD_FIELDS: CdFields = &[
    (0, 9, 9, FieldKind::DocumentNumber),
    (13, 19, 19, FieldKind::Date),
    (21, 27, 27, FieldKind::Date),
];

#[cfg(test)]
pub(crate) fn cd_field_tables() -> [(Format, usize, CdFields); 6] {
    [
        (Format::Td1, 0, TD1_LINE1_CD_FIELDS),
        (Format::Td1, 1, TD1_LINE2_CD_FIELDS),
        (Format::Td2, 1, TD2_LINE2_CD_FIELDS),
        (Format::Td3, 1, TD3_LINE2_CD_FIELDS),
        (Format::MrvA, 1, MRV_LINE2_CD_FIELDS),
        (Format::MrvB, 1, MRV_LINE2_CD_FIELDS),
    ]
}

/// A two-line format plus the line-2 fields the class sweep may touch —
/// [`TwoLineFormat`] with the sweep's own table appended.
type TwoLineSweep = (
    usize,
    &'static [u8],
    fn(&str) -> String,
    fn(&str) -> String,
    TwoLineParse,
    CdFields,
);

/// Candidate readings for a line of the right width in which one OCR
/// confusable class was applied uniformly across a whole field — the repair
/// [`crate::solve_class_sweep`] performs, spliced back into the line it came
/// from.
///
/// **Field-scoped, never line-scoped**, and that is the safety property. A
/// line sweep would rewrite correct occurrences of the same character
/// elsewhere on the line — a document code legitimately containing it, say —
/// and those positions carry no check digit, so the result would validate
/// while being wrong. Every sweep here is arbitrated by the swept field's own
/// check digit.
fn class_swept(
    raw: &str,
    target: usize,
    repair: fn(&str) -> String,
    fields: CdFields,
) -> Vec<String> {
    let n = normalize_line(raw);
    if n.len() != target || !is_mrz_charset(&n) {
        return Vec::new();
    }
    let mut seen = std::collections::HashSet::new();
    let mut out: Vec<String> = Vec::new();
    for base in [repair(&n), n.clone()] {
        let mut cells: Vec<char> = base.chars().collect();
        if cells.len() != target {
            continue;
        }
        let mut changed = false;
        for &(start, end, cd_col, kind) in fields {
            if end > cells.len() || cd_col >= cells.len() {
                continue;
            }
            let field: String = cells[start..end].iter().collect();
            if let Resolution::Unique(fixed) = solve_class_sweep(&field, cells[cd_col], kind) {
                // `solve_class_sweep` returns the swept field only. Its gate
                // was `verify(swept_field, swept_check)`, so the digit this
                // field must now carry is exactly the one the repaired field
                // computes — take it from the arithmetic rather than from the
                // sweep, which never hands it back.
                let (Ok(cd), true) = (
                    crate::check_digit(&fixed),
                    fixed.chars().count() == end - start,
                ) else {
                    continue;
                };
                let Some(cd_char) = char::from_digit(cd, 10) else {
                    continue;
                };
                for (i, c) in fixed.chars().enumerate() {
                    cells[start + i] = c;
                }
                cells[cd_col] = cd_char;
                changed = true;
            }
        }
        if changed {
            let line: String = cells.into_iter().collect();
            if seen.insert(line.clone()) {
                out.push(line);
            }
        }
    }
    out
}

/// Readings recovered by the uniform class sweep, tried **before** the
/// ordinary damaged-capture search and preferred over it.
///
/// **Why a separate pass rather than more shapes in [`damaged_pass`], which
/// is where this began.** Pooled into that search, the sweep is outvoted by
/// the machinery it exists to complement. Measured on the motivating shape —
/// a nine-cell document number of one character, read as its lookalike, check
/// digit included — the single-substitution search
/// ([`crate::repair::substitution_candidates`]) finds **three** further
/// readings that also validate, because swapping one cell of that run shifts
/// the checksum by exactly the amount needed at any weight-3 position. Four
/// disagreeing readings then reach [`single`], which correctly refuses to
/// choose among them, and nothing is recovered at all. The sweep worked and
/// still lost.
///
/// So the tie-break is explicit, and it is a **prior, not arithmetic**: on the
/// checksum evidence alone all four readings are equal. The sweep's reading
/// explains every differing cell with one decision about one glyph class. Each
/// substitution rival instead requires the recogniser to have read eight of
/// nine identical glyphs correctly and exactly one of them differently — which
/// contradicts the uniformity actually observed in the capture. Preferring the
/// uniform explanation is a judgement about how OCR fails, and it is stated
/// here rather than buried in an ordering.
///
/// Returns `None` unless [`ParseOptions::class_sweep`] is on, so the whole
/// pass — and this judgement — costs nothing until the arm is measured.
fn class_sweep_pass(
    lines: &[&str],
    opts: &ParseOptions,
    intact_td1_starts: &[usize],
) -> Option<MrzData> {
    if !opts.class_sweep {
        return None;
    }
    let mut hits: Vec<MrzData> = Vec::new();

    // TD1: sweep line 1's document number, or line 2's two dates.
    for i in 0..lines.len().saturating_sub(2) {
        let (a, b, c) = (lines[i], lines[i + 1], lines[i + 2]);
        let v3 = variants(c, 30, repair_td1_line3);
        for (v1, v2) in [
            (
                td1_line1_searched(|repair| class_swept(a, 30, repair, TD1_LINE1_CD_FIELDS)),
                variants(b, 30, repair_td1_line2),
            ),
            (
                td1_line1_variants(a),
                class_swept(b, 30, repair_td1_line2, TD1_LINE2_CD_FIELDS),
            ),
        ] {
            for l1 in &v1 {
                if !matches!(l1.as_bytes().first(), Some(b'I' | b'A' | b'C')) {
                    continue;
                }
                for l2 in &v2 {
                    for l3 in &v3 {
                        if let Ok(data) = parse_td1_with(l1, l2, l3, opts) {
                            if accept_damaged(&data)
                                && !hits.iter().any(|h| h.mrz_lines == data.mrz_lines)
                            {
                                hits.push(data);
                            }
                        }
                    }
                }
            }
        }
    }

    // Two-line formats: every sweepable field lives on line 2.
    let two_line: [TwoLineSweep; 4] = [
        (
            44,
            b"P",
            repair_td3_line1,
            repair_td3_line2,
            parse_td3_with,
            TD3_LINE2_CD_FIELDS,
        ),
        (
            44,
            b"V",
            repair_mrv_a_line1,
            repair_mrv_a_line2,
            parse_mrv_a_with,
            MRV_LINE2_CD_FIELDS,
        ),
        (
            36,
            b"IAC",
            repair_td2_line1,
            repair_td2_line2,
            parse_td2_with,
            TD2_LINE2_CD_FIELDS,
        ),
        (
            36,
            b"V",
            repair_mrv_b_line1,
            repair_mrv_b_line2,
            parse_mrv_b_with,
            MRV_LINE2_CD_FIELDS,
        ),
    ];
    for i in 0..lines.len().saturating_sub(1) {
        let (a, b) = (lines[i], lines[i + 1]);
        for (width, prefixes, rep1, rep2, parse, cd_fields) in two_line {
            if width == 36 && prefixes == b"IAC" && intact_td1_starts.contains(&i) {
                continue;
            }
            let v1 = td3_line1_variants(a, width, prefixes, rep1);
            let v2 = class_swept(b, width, rep2, cd_fields);
            for l1 in &v1 {
                if !l1.bytes().next().is_some_and(|c| prefixes.contains(&c)) {
                    continue;
                }
                for l2 in &v2 {
                    if let Ok(data) = parse(l1, l2, opts) {
                        if accept_damaged(&data)
                            && !hits.iter().any(|h| h.mrz_lines == data.mrz_lines)
                        {
                            hits.push(data);
                        }
                    }
                }
            }
        }
    }

    single(hits)
}

/// Start indices of every three consecutive rows that are exactly a TD1 zone:
/// three 30-cell rows in the MRZ charset that `parse_td1_with` accepts as a
/// layout, whether or not their check digits verify (#409) — and whether or
/// not its document number is refused for a leading filler, which is a
/// structural error but not evidence *against* the TD1 shape (a corrupted
/// document number does not un-TD1 the other two lines). Treating only
/// `Ok` as intact would pad a refused TD1 into a TD2 reading, reopening
/// #409 for this specific new refusal. The TD2 paths skip a pair starting at
/// one of these rows, so an intact TD1 is never padded into a TD2 reading.
fn intact_td1_starts(lines: &[&str], opts: &ParseOptions) -> Vec<usize> {
    lines
        .windows(3)
        .enumerate()
        .filter_map(|(index, rows)| {
            let [first, second, third] = [rows[0], rows[1], rows[2]].map(normalize_line);
            let shaped = [&first, &second, &third]
                .iter()
                .all(|row| row.len() == 30 && is_mrz_charset(row));
            let intact = shaped
                && matches!(
                    parse_td1_with(&first, &second, &third, opts),
                    Ok(_) | Err(MrzError::LeadingFiller { .. })
                );
            intact.then_some(index)
        })
        .collect()
}

/// A reading recovered from damage has to clear a higher bar than one read
/// cleanly: every check digit valid **and** both dates real calendar dates.
///
/// The dates are load-bearing, not belt-and-braces. A check digit sees a field
/// only mod 10 and the composite sees the same characters, so a single
/// destroyed position admits an entire residue class that *both* digits
/// accept — four readings on the card this was measured against. Three of them
/// are not dates. Without this filter the pass would have to pick one, and a
/// wrong pick is indistinguishable from a proof.
fn accept_damaged(data: &MrzData) -> bool {
    data.valid()
        && data
            .validity(crate::Date::new(2000, 1, 1))
            .dates_well_formed
}

/// Try to recover a record in which exactly one line arrived too narrow.
///
/// Only one line is damaged in the captures this exists for (a punched hole, a
/// finger over one end), so each shape below restores a single line and
/// crosses it against the ordinary variants of the others — linear in the
/// number of restored candidates rather than a product of three searches.
///
/// Returns `Some` only when the surviving readings are one answer: they agree
/// on every field except the raw zone (see `single`). Several genuinely
/// different readings means the MRZ cannot distinguish them, and the honest
/// answer is the ordinary checksum-failed fallback, not the first candidate
/// off the list.
fn damaged_pass(
    lines: &[&str],
    opts: &ParseOptions,
    intact_td1_starts: &[usize],
) -> Option<MrzData> {
    // Preferred over the search below when it lands -- see `class_sweep_pass`
    // for why pooling the two makes the sweep lose to the machinery it
    // complements. No-op unless the arm is on.
    if let Some(data) = class_sweep_pass(lines, opts, intact_td1_starts) {
        return Some(data);
    }
    let mut budget = MAX_DAMAGED_ATTEMPTS;
    let mut hits: Vec<MrzData> = Vec::new();

    let record = |data: MrzData, hits: &mut Vec<MrzData>| {
        if accept_damaged(&data) && !hits.iter().any(|h| h.mrz_lines == data.mrz_lines) {
            hits.push(data);
        }
    };

    // TD1: three consecutive lines, any one of them narrow.
    for i in 0..lines.len().saturating_sub(2) {
        let (a, b, c) = (lines[i], lines[i + 1], lines[i + 2]);
        let shapes: [(Vec<String>, Vec<String>, Vec<String>); 6] = [
            (
                restored(a, 30, repair_td1_line1),
                variants(b, 30, repair_td1_line2),
                variants(c, 30, repair_td1_line3),
            ),
            (
                td1_line1_variants(a),
                restored(b, 30, repair_td1_line2),
                variants(c, 30, repair_td1_line3),
            ),
            (
                td1_line1_variants(a),
                variants(b, 30, repair_td1_line2),
                restored(c, 30, repair_td1_line3),
            ),
            (
                td1_line1_searched(|repair| substituted(a, 30, repair)),
                variants(b, 30, repair_td1_line2),
                variants(c, 30, repair_td1_line3),
            ),
            (
                td1_line1_variants(a),
                substituted(b, 30, repair_td1_line2),
                variants(c, 30, repair_td1_line3),
            ),
            (
                td1_line1_variants(a),
                variants(b, 30, repair_td1_line2),
                substituted(c, 30, repair_td1_line3),
            ),
        ];
        for (v1, v2, v3) in shapes {
            for l1 in &v1 {
                if !matches!(l1.as_bytes().first(), Some(b'I' | b'A' | b'C')) {
                    continue;
                }
                for l2 in &v2 {
                    for l3 in &v3 {
                        if budget == 0 {
                            return single(hits);
                        }
                        budget -= 1;
                        if let Ok(data) = parse_td1_with(l1, l2, l3, opts) {
                            record(data, &mut hits);
                        }
                    }
                }
            }
        }
    }

    // Two-line formats: TD3/MRV-A at 44, TD2/MRV-B at 36. Each entry is the
    // line-1 prefix that identifies the format plus its parse function, so a
    // new two-line format is one row rather than another nested loop.
    let two_line: [TwoLineFormat; 4] = [
        (44, b"P", repair_td3_line1, repair_td3_line2, parse_td3_with),
        (
            44,
            b"V",
            repair_mrv_a_line1,
            repair_mrv_a_line2,
            parse_mrv_a_with,
        ),
        (
            36,
            b"IAC",
            repair_td2_line1,
            repair_td2_line2,
            parse_td2_with,
        ),
        (
            36,
            b"V",
            repair_mrv_b_line1,
            repair_mrv_b_line2,
            parse_mrv_b_with,
        ),
    ];
    for i in 0..lines.len().saturating_sub(1) {
        let (a, b) = (lines[i], lines[i + 1]);
        for (width, prefixes, rep1, rep2, parse) in two_line {
            if width == 36 && prefixes == b"IAC" && intact_td1_starts.contains(&i) {
                continue;
            }
            for (v1, v2) in [
                (restored(a, width, rep1), variants(b, width, rep2)),
                (
                    td3_line1_variants(a, width, prefixes, rep1),
                    restored(b, width, rep2),
                ),
                (substituted(a, width, rep1), variants(b, width, rep2)),
                (
                    td3_line1_variants(a, width, prefixes, rep1),
                    substituted(b, width, rep2),
                ),
            ] {
                for l1 in &v1 {
                    if !l1.bytes().next().is_some_and(|c| prefixes.contains(&c)) {
                        continue;
                    }
                    for l2 in &v2 {
                        if budget == 0 {
                            return single(hits);
                        }
                        budget -= 1;
                        if let Ok(data) = parse(l1, l2, opts) {
                            record(data, &mut hits);
                        }
                    }
                }
            }
        }
    }

    single(hits)
}

/// Compare checksum evidence for two invalid fallback candidates. Applicable
/// digits beat no evidence, fractions are compared exactly, then the reading
/// with more applicable digits wins; ties retain the incumbent.
fn fallback_rank(a: &Checks, b: &Checks) -> core::cmp::Ordering {
    use core::cmp::Ordering;

    match (a.applicable(), b.applicable()) {
        (0, 0) => Ordering::Equal,
        (0, _) => Ordering::Less,
        (_, 0) => Ordering::Greater,
        (a_applicable, b_applicable) => (a.verified() * b_applicable)
            .cmp(&(b.verified() * a_applicable))
            .then_with(|| a_applicable.cmp(&b_applicable)),
    }
}

/// A damaged-recovery unanimity gate: the one recovered reading, or `None` if
/// the damage left more than one answer standing.
///
/// Two readings are the same answer when they agree on everything [`MrzData`]
/// exposes except `mrz_lines`, the raw zone they were read from. Two insertion
/// points inside one filler run reach the same answer twice, and count as one.
/// Every other field takes part, format included.
///
/// The gate used to compare only the document number, the dates, the names and
/// the nationality. Readings that disagreed on sex, issuer, document code,
/// optional data, the full document number or format therefore counted as
/// unanimous, and the first one off the list won. No check digit covers sex,
/// issuer, document code or format, so nothing downstream could catch that
/// pick. Comparing the whole record minus the zone also makes a field added
/// later take part by default, which is the safe direction for a refusal gate.
///
/// Every hit has already passed [`accept_damaged`], so their [`Checks`] agree
/// whenever their formats do. Comparing `checks` costs nothing and keeps the
/// rule simple.
fn single(mut hits: Vec<MrzData>) -> Option<MrzData> {
    // Not struct-update syntax: with the `zeroize` feature `MrzData` implements
    // `Drop`, and fields cannot be moved out of a `Drop` type.
    let answer = |data: &MrzData| {
        let mut data = data.clone();
        data.mrz_lines.clear();
        data
    };
    let first = answer(hits.first()?);
    if hits.iter().all(|h| answer(h) == first) {
        return Some(hits.remove(0));
    }
    None
}

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

    /// #476's TD1 side of #468/#469's TD3 generalization, pinned as a
    /// white-box unit test on [`td1_line1_variants`] rather than through
    /// [`find_and_parse`]: TD1 and TD2 share the `I`/`A`/`C` line-1 prefix by
    /// design, and forcing TD1's own ordinary scan to fail (the only way to
    /// reach `damaged_pass` at all) also hands `find_and_parse`'s
    /// unconditional TD2 scan the very same lines, whose `restored`/
    /// `substituted` search can coincidentally produce a structurally
    /// plausible TD2 fallback that wins before `damaged_pass` ever runs — a
    /// pre-existing cross-format ambiguity, not this fix, and exactly why
    /// `crates/mrz/tests/repair.rs`'s TD1 punched-hole fixtures test the
    /// repair primitives directly instead of the full multi-format scan.
    ///
    /// A dropped line-1 filler leaves the plain candidate's document number
    /// shifted by one cell, so its own check digit (positions 5..15) no
    /// longer validates — before this fix, that was the *only* line-1
    /// candidate `damaged_pass`'s TD1 shapes ever tried, so a document
    /// needing damaged recovery on line 2 or line 3 *as well* was an
    /// unrecoverable checksum failure even though the ordinary scan's own
    /// `repair_td1_line1_unshifted` would have recovered it.
    #[test]
    fn td1_line1_variants_recovers_a_dropped_filler() {
        use crate::checksum::check_digit;
        use crate::{format_td1, Td1Fields};

        // The first digit must not be one of `letterize`'s remapped digits
        // (`0`, `1`, `2`, `5`, `6`, `8`): once the drop shifts it into
        // `repair_td1_line1`'s hard-coded issuing-state range (positions
        // 2..5), a remapped digit would be corrupted to a letter before
        // `repair_td1_line1_unshifted` ever gets to move it back -- a
        // separate, pre-existing limitation of that composition, not what
        // this test is pinning.
        let document_number = "345678912";
        let mrz = format_td1(&Td1Fields {
            document_code: "I".to_string(),
            issuing_country: "UTO".to_string(),
            document_number: document_number.to_string(),
            optional_data_1: None,
            surname: "ESKANDARI".to_string(),
            given_names: "MAREN".to_string(),
            nationality: "UTO".to_string(),
            date_of_birth: MrzDate::from_field(
                RawDateField::try_from("440101").expect("six MRZ date characters"),
                DateRole::Birth,
                crate::CURRENT_YY,
            ),
            sex: Sex::Female,
            date_of_expiry: MrzDate::from_field(
                RawDateField::try_from("301230").expect("six MRZ date characters"),
                DateRole::Expiry,
                crate::CURRENT_YY,
            ),
            optional_data_2: None,
        });
        let mut lines = mrz.lines();
        let l1 = lines.next().expect("format_td1 emits line 1").to_string();
        let l2 = lines.next().expect("format_td1 emits line 2");
        let l3 = lines.next().expect("format_td1 emits line 3");
        assert_eq!(l1.len(), 30, "sanity: a TD1 line is 30 cells");
        assert!(
            parse_td1_with(&l1, l2, l3, &ParseOptions::default())
                .expect("the emitted fixture parses")
                .valid(),
            "sanity: the fixture must be checksum-valid before it is damaged"
        );

        let mut damaged = l1.clone();
        damaged.remove(1);
        assert_eq!(damaged.len(), 29, "dropping one character narrows the line");

        let candidates = td1_line1_variants(&damaged);
        assert!(
            candidates.contains(&l1),
            "the unshifted candidate must reconstruct the original line exactly, got {candidates:?}"
        );

        // The plain candidate `damaged_pass`'s TD1 shapes tried alone before
        // this fix keeps the shift, so its own document-number check digit
        // never validates -- confirming there is genuinely nothing else in
        // `candidates` this test's `l1` match could be confused with.
        let shifted_only: Vec<&String> = candidates.iter().filter(|c| c.as_str() != l1).collect();
        assert!(
            shifted_only.iter().all(|c| {
                c.len() != 30
                    || check_digit(&c[5..14]).ok()
                        != c.as_bytes().get(14).and_then(|b| (*b as char).to_digit(10))
            }),
            "every other candidate's own document-number check digit must fail, got {candidates:?}"
        );

        // The recovered candidate parses as a genuine, fully valid TD1
        // record when crossed against line 2/line 3 unchanged -- exactly the
        // shape `damaged_pass`'s TD1 loop crosses each restored/substituted
        // line 1 against.
        let recovered = parse_td1_with(&l1, l2, l3, &ParseOptions::default())
            .expect("the unshifted candidate parses");
        assert_eq!(recovered.document_number, document_number);
        assert!(recovered.valid());
    }

    /// [`prefer_admissible_line1`]'s contract: with at least one admissible
    /// candidate only the admissible ones survive, in their existing order
    /// (duplicates included); with none, every candidate comes back unchanged.
    #[test]
    fn prefer_admissible_line1_keeps_admissible_in_order_or_everything() {
        let good_a = "I<FRAAHGEK9H885<<<<<<<<<<<<<<<".to_string();
        let good_b = "IDFRAAHGEK9H885<<<<<<<<<<<<<<<".to_string();
        let shifted = "IFRAAHGEK9H885<<<<<<<<<<<<<<<<".to_string();
        let short = "I<FRA".to_string();
        for line in [&good_a, &good_b, &shifted] {
            assert_eq!(line.len(), 30, "sanity: {line}");
        }

        let mixed = vec![
            shifted.clone(),
            good_b.clone(),
            short.clone(),
            good_a.clone(),
            good_b.clone(),
        ];
        assert_eq!(
            prefer_admissible_line1(mixed, 30, b"IAC"),
            vec![good_b.clone(), good_a.clone(), good_b.clone()]
        );

        let none = vec![
            shifted.clone(),
            short.clone(),
            "I<QQQAAAAAAAAAA<<<<<<<<<<<<<<<".into(),
        ];
        assert_eq!(prefer_admissible_line1(none.clone(), 30, b"IAC"), none);
        assert_eq!(
            prefer_admissible_line1(Vec::new(), 30, b"IAC"),
            Vec::<String>::new()
        );

        // The prefix and width are part of admissibility, not just the issuer.
        assert!(!line1_admissible(&good_a.replacen('I', "P", 1), 30, b"IAC"));
        assert!(!line1_admissible(&good_a, 36, b"IAC"));
        assert!(line1_admissible(&good_a.replacen('I', "C", 1), 30, b"IAC"));
    }

    /// The composite blind spot, white-box: a TD1 line 1 whose true check
    /// digit is `5`, read with its position-1 filler dropped. Both readings
    /// validate against the same lines 2 and 3, and [`td1_line1_variants`]
    /// returns only the one whose issuer resolves.
    #[test]
    fn td1_line1_variants_drops_a_validating_shifted_reading() {
        use crate::{format_td1, Td1Fields};

        let mrz = format_td1(&Td1Fields {
            document_code: "I".to_string(),
            issuing_country: "FRA".to_string(),
            document_number: "AHGEK9H88".to_string(),
            optional_data_1: None,
            surname: "MARTIN".to_string(),
            given_names: "CLAIRE".to_string(),
            nationality: "FRA".to_string(),
            date_of_birth: MrzDate::from_field(
                RawDateField::try_from("070707").expect("six MRZ date characters"),
                DateRole::Birth,
                crate::CURRENT_YY,
            ),
            sex: Sex::Female,
            date_of_expiry: MrzDate::from_field(
                RawDateField::try_from("330615").expect("six MRZ date characters"),
                DateRole::Expiry,
                crate::CURRENT_YY,
            ),
            optional_data_2: None,
        });
        let lines: Vec<&str> = mrz.lines().collect();
        let (l1, l2, l3) = (lines[0], lines[1], lines[2]);
        let opts = ParseOptions::default();
        let shifted = format!("{}{}<", &l1[..1], &l1[2..]);

        assert_eq!(l1.as_bytes()[14], b'5', "sanity: the true check digit");
        assert!(parse_td1_with(l1, l2, l3, &opts)
            .expect("truth parses")
            .valid());
        assert!(
            parse_td1_with(&shifted, l2, l3, &opts)
                .expect("shifted parses")
                .valid(),
            "sanity: the shifted reading validates too"
        );

        let dropped = &shifted[..29];
        let candidates = td1_line1_variants(dropped);
        assert!(candidates.contains(&l1.to_string()), "{candidates:?}");
        assert!(
            candidates.iter().all(|c| line1_admissible(c, 30, b"IAC")),
            "no inadmissible candidate may survive when one is admissible: {candidates:?}"
        );
        assert!(!candidates.contains(&shifted), "{candidates:?}");
    }

    /// `single` treats readings as one answer only when every exposed field and
    /// the format agree. Each mutation below touches one field the gate once
    /// ignored; any of them makes the pair a disagreement, so the gate refuses.
    #[test]
    fn single_refuses_readings_that_disagree_on_any_exposed_field() {
        let base = parse_td3(
            "P<UTOERIKSSON<<ANNA<MARIA<<<<<<<<<<<<<<<<<<<",
            "L898902C36UTO7408122F1204159ZE184226B<<<<<10",
        )
        .expect("the Doc 9303 specimen parses");

        // The same answer reached through a different raw zone counts as one.
        let mut twin = base.clone();
        twin.mrz_lines.push('<');
        assert_eq!(single(vec![base.clone(), twin]), Some(base.clone()));
        assert_eq!(single(vec![base.clone()]), Some(base.clone()));
        assert_eq!(single(Vec::new()), None);

        /// A field's name, and an edit that changes only that field.
        type Mutation = (&'static str, fn(&mut MrzData));
        let mutations: [Mutation; 8] = [
            ("format", |d| d.format = Format::MrvA),
            ("document_type", |d| d.document_type = "PO".into()),
            ("issuing_country", |d| d.issuing_country = "D".into()),
            ("document_number_full", |d| {
                d.document_number_full = Some("L898902C3123".into());
            }),
            ("document_number_legacy_encoding", |d| {
                d.document_number_legacy_encoding = !d.document_number_legacy_encoding;
            }),
            ("sex", |d| d.sex = Sex::Male),
            ("optional_data_1", |d| {
                d.optional_data_1 = Some("ZE184226C".into())
            }),
            ("optional_data_2", |d| d.optional_data_2 = Some("1".into())),
        ];
        for (field, mutate) in mutations {
            let mut other = base.clone();
            mutate(&mut other);
            assert_ne!(other, base, "the {field} mutation must change the record");
            assert_eq!(
                single(vec![base.clone(), other.clone()]),
                None,
                "readings that disagree on {field} are not one answer"
            );
            assert_eq!(
                single(vec![other, base.clone()]),
                None,
                "the refusal on {field} does not depend on candidate order"
            );
        }
    }

    #[test]
    fn date_field_reads_a_vetted_slice() {
        assert_eq!(
            date_field("<<740812", 1, 2, DateRole::Birth, 30),
            Ok(MrzDate::Calendar(crate::Date::new(1974, 8, 12)))
        );
    }

    #[test]
    fn date_field_maps_an_unvetted_slice_to_bad_character_not_a_panic() {
        let line = format!("{}74a812", "<".repeat(13));
        assert_eq!(
            date_field(&line, 1, 13, DateRole::Birth, 30),
            Err(MrzError::BadCharacter {
                character: 'a',
                line: Some(1),
                position: 15
            })
        );
        assert_eq!(
            date_field("7408", 1, 0, DateRole::Expiry, 30),
            Err(MrzError::BadCharacter {
                character: '7',
                line: Some(1),
                position: 0
            })
        );
    }
    /// The cell-zero guard still permits an unknown inside the name field.
    #[test]
    fn a_missing_interior_cell_is_still_restored() {
        let zone = crate::format_td3(&crate::Td3Fields {
            document_code: "P".to_string(),
            issuing_country: "UTO".to_string(),
            document_number: "E00000000".to_string(),
            surname: "SPECIMEN".to_string(),
            given_names: "TEST".to_string(),
            nationality: "UTO".to_string(),
            date_of_birth: MrzDate::from_field(
                RawDateField::try_from("800101").expect("six MRZ date characters"),
                DateRole::Birth,
                crate::CURRENT_YY,
            ),
            sex: Sex::Female,
            date_of_expiry: MrzDate::from_field(
                RawDateField::try_from("301230").expect("six MRZ date characters"),
                DateRole::Expiry,
                crate::CURRENT_YY,
            ),
            personal_number: None,
        });
        let (line1, _) = zone.split_once('\n').expect("emitted TD3 has two lines");
        let at = line1.find("<<").expect("emitted name separator") + 1;
        let mut short_line1 = line1.to_string();
        short_line1.remove(at);
        assert_eq!(short_line1.len(), 43);

        let candidates = restored(&short_line1, 44, repair_td3_line1);
        assert!(
            candidates.iter().any(|line| line == line1),
            "the original line must remain a restoration candidate"
        );
    }

    /// #436: `td3_prefix_verdict` against a table of 45-character (one cell
    /// too long) and control inputs, each already `normalize_line` +
    /// `fix_doc_code`'d — the state every call site is required to pass it
    /// in.
    #[test]
    fn td3_prefix_verdict_table() {
        // Deleting the OCR-inserted `H` gives `COL` (Colombia); deleting the
        // originally-printed `O` gives `CHL` (Chile). Both real and
        // distinct: refused.
        let two_resolving = "P<COHLERIKSSON<<ANNA<MARIA<<<<<<<<<<<<<<<<<<<";
        assert_eq!(two_resolving.len(), 45);
        assert_eq!(td3_prefix_verdict(two_resolving), Td3Prefix::Ambiguous);

        // A spurious `X` right after the issuing state's first letter:
        // deleting it is the only deletion (of the three tried) that
        // resolves.
        let one_resolving = "P<UXTOERIKSSON<<ANNA<MARIA<<<<<<<<<<<<<<<<<<<";
        assert_eq!(one_resolving.len(), 45);
        let Td3Prefix::Repair(repaired) = td3_prefix_verdict(one_resolving) else {
            panic!("expected exactly one resolving deletion to repair the line");
        };
        assert_eq!(repaired.len(), 44);
        assert_eq!(&repaired[0..5], "P<UTO");
        assert_eq!(&repaired[5..], &one_resolving[6..]);

        // The as-read issuing state already resolves (`CAN`), even though
        // the line is one cell too long from an extra filler further down —
        // kept unmodified rather than enumerated. A genuine `P<CAN` holder
        // whose surname starts with `F` would otherwise delete to the
        // equally real `CAF` (Central African Republic).
        let already_resolves = "P<CANFOO<<GIVEN<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<";
        assert_eq!(already_resolves.len(), 45);
        assert_eq!(td3_prefix_verdict(already_resolves), Td3Prefix::Keep);

        // Same issuing-state corruption as `two_resolving`, but the
        // document code itself (`PX`) is not real, so no deletion is
        // admissible regardless of what its issuing state resolves to.
        let bogus_doc_code = "PXCOHLERIKSSON<<ANNA<MARIA<<<<<<<<<<<<<<<<<<<";
        assert_eq!(bogus_doc_code.len(), 45);
        assert_eq!(td3_prefix_verdict(bogus_doc_code), Td3Prefix::Keep);

        // Not one cell too long: the ordinary-width, ordinary-length line
        // and a two-cell overlong line are both left to the caller's usual
        // repairs.
        let right_length = "P<UTOERIKSSON<<ANNA<MARIA<<<<<<<<<<<<<<<<<<<";
        assert_eq!(right_length.len(), 44);
        assert_eq!(td3_prefix_verdict(right_length), Td3Prefix::Keep);
        let two_cells_long = "P<XUTOERIKSSON<<ANNA<MARIA<<<<<<<<<<<<<<<<<<<X";
        assert_eq!(two_cells_long.len(), 46);
        assert_eq!(td3_prefix_verdict(two_cells_long), Td3Prefix::Keep);
    }

    use core::cmp::Ordering;

    fn checks(states: [Option<bool>; 5]) -> Checks {
        Checks {
            document_number: states[0],
            date_of_birth: states[1],
            date_of_expiry: states[2],
            personal_number: states[3],
            composite: states[4],
        }
    }

    #[test]
    fn fallback_rank_uses_exact_fraction_then_coverage_then_incumbent() {
        let none = checks([None, None, None, None, None]);
        let one_verified = checks([Some(true), None, None, None, None]);
        assert_eq!(fallback_rank(&none, &one_verified), Ordering::Less);

        // Cross multiplication, rather than floats: 3/4 beats 2/3.
        let three_of_four = checks([Some(true), Some(true), Some(true), Some(false), None]);
        let two_of_three = checks([Some(true), Some(true), Some(false), None, None]);
        assert_eq!(
            fallback_rank(&three_of_four, &two_of_three),
            Ordering::Greater
        );

        // The raw fraction comes before coverage: 3/3 beats 4/5.
        let three_of_three = checks([Some(true), Some(true), Some(true), None, None]);
        let four_of_five = checks([Some(true), Some(true), Some(true), Some(true), Some(false)]);
        assert_eq!(
            fallback_rank(&three_of_three, &four_of_five),
            Ordering::Greater
        );

        // Equal fractions prefer more independently printed digits.
        let four_of_four = checks([Some(true), Some(true), Some(true), Some(true), None]);
        assert_eq!(
            fallback_rank(&three_of_three, &four_of_four),
            Ordering::Less
        );

        // Equal evidence leaves the incumbent unchanged.
        assert_eq!(
            fallback_rank(&three_of_three, &three_of_three),
            Ordering::Equal
        );
    }
}