stet-pdf-reader 0.7.0

PDF parser and renderer
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
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
// stet-pdf-reader
// Copyright (c) 2026 Scott Bowman
// SPDX-License-Identifier: Apache-2.0 OR MIT

//! PDF font resolution and glyph rendering.

use std::collections::HashMap;
use std::sync::Arc;

use skrifa::MetadataProvider;
use stet_fonts::cff_parser::{CffFont, parse_cff};
use stet_fonts::charstring::{execute_charstring, execute_charstring_mm};
use stet_fonts::encoding::{MACROMAN_ENCODING, STANDARD_ENCODING, WINANSI_ENCODING};
use stet_fonts::geometry::PathSegment;
use stet_fonts::geometry::{Matrix, PsPath};
use stet_fonts::truetype::{
    get_glyf_data, get_units_per_em, parse_cmap, parse_cmap_with_info, parse_glyf_to_path,
};
use stet_fonts::type1_parser::parse_type1;
use stet_fonts::type2_charstring::execute_type2_charstring;

use crate::FontProvider;
use crate::error::PdfError;
use crate::objects::{PdfDict, PdfObj};
use crate::resolver::Resolver;

/// Resolved PDF font, ready for glyph rendering.
pub enum PdfFont {
    Type1(Type1PdfFont),
    TrueType(TrueTypePdfFont),
    Cff(CffPdfFont),
    /// Type 0 composite font (CIDFontType2 with TrueType outlines)
    CidTrueType(CidTrueTypePdfFont),
    /// Type 0 composite font (CIDFontType0 with CFF outlines)
    CidCff(CidCffPdfFont),
    /// Type 3 font: glyphs defined as content streams.
    Type3(Type3PdfFont),
}

pub struct Type1PdfFont {
    pub font: stet_fonts::type1_parser::Type1Font,
    pub encoding: [Option<String>; 256],
    pub widths: [f64; 256],
    pub font_matrix: Matrix,
    /// Multiple Master weight vector (for blend OtherSubrs 14-17).
    pub weight_vector: Option<Vec<f64>>,
    /// When true, glyph lookup falls back to the font's built-in encoding
    /// if the PDF encoding's glyph name isn't in CharStrings. Only set for
    /// symbolic fonts where the naming convention is completely incompatible
    /// (e.g. StandardEncoding "A" vs font's custom "G41").
    pub builtin_fallback: bool,
    /// When true, per-character width scaling adjusts each glyph horizontally
    /// to match the PDF's /Widths. Set for non-metric-compatible substitutes
    /// (e.g. NimbusSans for LucidaSans) where the average width mismatch
    /// exceeds 3%. NOT set for metric-compatible substitutes (e.g. NimbusRoman
    /// for TimesNewRoman) where widths already match.
    pub per_char_width_scale: bool,
}

pub struct TrueTypePdfFont {
    pub data: Vec<u8>,
    pub encoding: [Option<String>; 256],
    pub widths: [f64; 256],
    pub cmap: HashMap<u32, u16>,
    /// Whether the cmap maps Unicode values (true) or re-encoded char codes (false).
    /// Non-Unicode cmaps come from (1,0) Mac Roman or (3,0) Symbol subtables in
    /// subset fonts — the encoding→unicode→cmap lookup path must be skipped.
    pub cmap_is_unicode: bool,
    /// Glyph name → GID mapping from the `post` table (for ligatures and
    /// other glyphs not reachable via Unicode cmap lookup).
    pub post_name_to_gid: HashMap<String, u16>,
    pub units_per_em: f64,
    /// Char code → Unicode mapping from /ToUnicode CMap (for gNNNN glyph names
    /// in substituted fonts where AGL lookup fails).
    pub to_unicode: HashMap<u16, u32>,
    /// When true, char codes map directly to GIDs (identity mapping).
    /// Set for symbolic TrueType fonts without an explicit /Encoding, where the
    /// cmap subtable maps to misleading Unicode values (re-encoded fonts).
    pub identity_gid: bool,
    /// When true, gNNNN glyph names in the encoding use hexadecimal GIDs
    /// (e.g. g003a = GID 58). Set when any gNNNN name contains hex letters (a-f).
    /// When false, gNNNN names use decimal (e.g. g1863 = GID 1863).
    pub gid_hex: bool,
}

pub struct CffPdfFont {
    pub font: CffFont,
    pub encoding: [Option<String>; 256],
    pub widths: [f64; 256],
    pub font_matrix: Matrix,
}

/// CIDFontType2: TrueType outlines accessed by CID (2-byte char codes).
pub struct CidTrueTypePdfFont {
    pub data: Vec<u8>,
    /// Default glyph width (from /DW, in text space ÷1000).
    pub default_width: f64,
    /// CID → width mapping (from /W array, in text space ÷1000).
    pub cid_widths: HashMap<u16, f64>,
    pub cmap: HashMap<u32, u16>,
    pub units_per_em: f64,
    /// If true, CID maps directly to GID (Identity CIDToGIDMap).
    pub identity_cid_to_gid: bool,
    /// If true, font data was loaded from the system (not embedded in PDF).
    /// For substituted fonts, CIDs are treated as Unicode and mapped via cmap.
    pub substituted: bool,
    /// Explicit CID-to-GID mapping from a CIDToGIDMap stream.
    /// Index = CID, value = GID. Takes priority over identity mapping.
    pub cid_to_gid_map: Option<Vec<u16>>,
    /// CID → Unicode mapping from the Type 0 font's /ToUnicode CMap.
    /// Used for substituted fonts to convert CID → Unicode → GID via cmap.
    pub to_unicode: HashMap<u16, u32>,
    /// CIDSystemInfo /Ordering (e.g. b"Japan1", b"GB1") for CID→Unicode fallback.
    pub ordering: Vec<u8>,
    /// If true, the encoding is UCS2-based (e.g. UniJIS-UCS2-H) and character
    /// codes are Unicode values that need mapping to CIDs for width lookup.
    pub ucs2_encoding: bool,
    /// First-byte → code length table from the encoding CMap's codespace ranges.
    /// Supports mixed-width encodings (e.g. 1-byte space + 2-byte CIDs).
    pub code_lengths: [u8; 256],
    /// Code → CID mapping from the encoding CMap (empty = identity).
    pub code_to_cid: HashMap<u32, u32>,
    /// Writing mode: 0 = horizontal, 1 = vertical.
    pub wmode: u8,
    /// Default vertical metrics [v_y, w1] from /DW2 (default: [880, -1000]).
    /// v_y = vertical origin offset, w1 = vertical advance width.
    pub dw2: [f64; 2],
    /// Per-CID vertical metrics from /W2: CID → (w1, v_x, v_y).
    /// w1 = vertical advance, v_x/v_y = position vector components (in 1/1000 em).
    pub w2: HashMap<u16, [f64; 3]>,
}

/// CIDFontType0: CFF outlines accessed by CID (2-byte char codes).
pub struct CidCffPdfFont {
    pub font: CffFont,
    /// Default glyph width (from /DW, in text space ÷1000).
    pub default_width: f64,
    /// CID → width mapping (from /W array, in text space ÷1000).
    pub cid_widths: HashMap<u16, f64>,
    /// Optional Unicode→GID cmap (from OpenType substitute fonts).
    /// When present, used for UCS2 glyph lookup instead of CFF's CID mapping.
    pub cmap: Option<HashMap<u32, u16>>,
    /// CID → GID mapping from the PDF's /CIDToGIDMap stream.
    /// Used for embedded OpenType/CFF fonts stored as FontFile2.
    pub pdf_cid_to_gid: Option<Vec<u16>>,
    /// When true, CID maps directly to charstring index (GID = CID).
    /// Set when CIDToGIDMap is /Identity or absent in CIDFontType2 fonts.
    pub identity_cid_to_gid: bool,
    /// CIDSystemInfo ordering for Unicode→CID width lookup.
    pub ordering: Vec<u8>,
    pub font_matrix: Matrix,
    /// First-byte → code length table from the encoding CMap's codespace ranges.
    pub code_lengths: [u8; 256],
    /// Code → CID mapping from the encoding CMap (empty = identity).
    pub code_to_cid: HashMap<u32, u32>,
    /// Writing mode: 0 = horizontal, 1 = vertical.
    pub wmode: u8,
    /// Default vertical metrics [v_y, w1] from /DW2 (default: [880, -1000]).
    pub dw2: [f64; 2],
    /// Per-CID vertical metrics from /W2: CID → (w1, v_x, v_y).
    pub w2: HashMap<u16, [f64; 3]>,
    /// Pre-computed glyph paths for Type 1 fonts used as CIDFontType0.
    /// When set, glyph_path_cid uses this cache instead of CFF charstrings.
    pub type1_paths: Option<HashMap<u16, PsPath>>,
}

/// Type 3 font: glyphs defined as content streams (CharProcs).
pub struct Type3PdfFont {
    /// Char code → decoded content stream bytes for the glyph.
    pub char_procs: HashMap<u8, Vec<u8>>,
    /// Char code → resources dict for the glyph stream (from font dict).
    pub resources: PdfDict,
    pub widths: [f64; 256],
    pub font_matrix: Matrix,
    pub font_bbox: [f64; 4],
}

/// Font cache: font resource name → resolved font.
pub type FontCache = HashMap<Vec<u8>, Arc<PdfFont>>;

/// Resolve a PDF font dict into a PdfFont ready for rendering.
pub fn resolve_font(
    resolver: &Resolver,
    font_ref: &PdfObj,
    font_provider: Option<&FontProvider>,
) -> Result<PdfFont, PdfError> {
    let font_obj = resolver.deref(font_ref)?;
    let font_dict = font_obj
        .as_dict()
        .ok_or(PdfError::Other("Font is not a dict".into()))?;

    let subtype = font_dict.get_name(b"Subtype").unwrap_or(b"Type1");
    // Handle Type 0 composite fonts (CID fonts)
    if subtype == b"Type0" {
        return resolve_type0(resolver, font_dict);
    }

    // Handle Type 3 fonts (glyph content streams)
    if subtype == b"Type3" {
        return resolve_type3(resolver, font_dict);
    }

    let first_char = font_dict.get_int(b"FirstChar").unwrap_or(0) as usize;
    let last_char = font_dict.get_int(b"LastChar").unwrap_or(255) as usize;

    // Parse widths array from font dict.
    // /Widths may be a direct array or an indirect reference — resolve if needed.
    let mut widths = [0.0f64; 256];
    let mut has_pdf_widths = false;
    let widths_obj = font_dict.get(b"Widths").and_then(|obj| {
        if obj.as_array().is_some() {
            Some(obj.clone())
        } else {
            resolver.deref(obj).ok()
        }
    });
    if let Some(PdfObj::Array(w_arr)) = &widths_obj {
        for (i, obj) in w_arr.iter().enumerate() {
            let code = first_char + i;
            if code < 256 {
                // Width entries may be indirect references (e.g. `9 0 R`)
                let val = if obj.as_f64().is_some() {
                    obj.as_f64().unwrap()
                } else if let Ok(resolved) = resolver.deref(obj) {
                    resolved.as_f64().unwrap_or(0.0)
                } else {
                    0.0
                };
                widths[code] = val / 1000.0;
            }
        }
        has_pdf_widths = true;

        // Apply /MissingWidth from FontDescriptor to charcodes outside [FirstChar, LastChar].
        // Per PDF spec, charcodes not covered by /Widths use /MissingWidth (default 0).
        let descriptor = get_font_descriptor(font_dict, resolver)?;
        if let Some(ref desc) = descriptor {
            let missing_w = desc.get_f64(b"MissingWidth").unwrap_or(0.0) / 1000.0;
            if missing_w != 0.0 {
                for (code, width) in widths.iter_mut().enumerate() {
                    if code < first_char || code > last_char {
                        *width = missing_w;
                    }
                }
            }
        }
    }

    // Resolve encoding.  Track whether the PDF dict had a valid /Encoding —
    // embedded CFF fonts that lack one should use the CFF's built-in encoding.
    // Invalid encoding names (e.g. /NULL) are treated as absent.
    let (encoding, has_valid_encoding, differences, no_base_encoding) =
        resolve_encoding(font_dict, resolver)?;
    let has_explicit_encoding = has_valid_encoding;

    // Get FontDescriptor
    let descriptor = get_font_descriptor(font_dict, resolver)?;

    // Extract font descriptor Flags for serif/sans-serif fallback selection
    let desc_flags = descriptor
        .as_ref()
        .and_then(|d| d.get_int(b"Flags"))
        .unwrap_or(0) as u32;

    let base_font_name = font_dict
        .get_name(b"BaseFont")
        .map(|n| String::from_utf8_lossy(n).to_string())
        .unwrap_or_default();

    // Route based on what font program is actually available in FontDescriptor,
    // not just the /Subtype (which says "Type1" even for CFF-embedded fonts).
    if let Some(ref desc) = descriptor {
        if desc.get(b"FontFile3").is_some() {
            // Try embedded CFF; fall back to substitution if decompression/parsing fails
            match resolve_cff(
                resolver,
                &descriptor,
                encoding.clone(),
                widths,
                has_explicit_encoding,
                has_pdf_widths,
                &differences,
                no_base_encoding,
            ) {
                Ok(font) => return Ok(font),
                Err(_) => {
                    if let Some(font) = substitute_font(
                        &base_font_name,
                        encoding.clone(),
                        widths,
                        has_pdf_widths,
                        font_provider,
                        desc_flags,
                        first_char,
                        last_char,
                    ) {
                        return Ok(font);
                    }
                }
            }
        }
        if desc.get(b"FontFile2").is_some() {
            // Try embedded TrueType (falls back to CFF internally if data is OTTO/CFF)
            match resolve_truetype(resolver, &descriptor, encoding.clone(), widths, font_dict) {
                Ok(font) => return Ok(font),
                Err(_) => {
                    if let Some(font) = substitute_font(
                        &base_font_name,
                        encoding.clone(),
                        widths,
                        has_pdf_widths,
                        font_provider,
                        desc_flags,
                        first_char,
                        last_char,
                    ) {
                        return Ok(font);
                    }
                }
            }
        }
        if desc.get(b"FontFile").is_some() {
            match resolve_type1(
                resolver,
                &descriptor,
                encoding.clone(),
                widths,
                has_explicit_encoding,
                has_pdf_widths,
                &differences,
                no_base_encoding,
            ) {
                Ok(font) => return Ok(font),
                Err(_) => {
                    if let Some(font) = substitute_font(
                        &base_font_name,
                        encoding.clone(),
                        widths,
                        has_pdf_widths,
                        font_provider,
                        desc_flags,
                        first_char,
                        last_char,
                    ) {
                        return Ok(font);
                    }
                }
            }
        }
    }
    // No embedded font program — try font substitution
    if let Some(font) = substitute_font(
        &base_font_name,
        encoding.clone(),
        widths,
        has_pdf_widths,
        font_provider,
        desc_flags,
        first_char,
        last_char,
    ) {
        return Ok(font);
    }
    // For TrueType fonts, try loading from system fonts before giving up
    if subtype == b"TrueType"
        && let Ok(data) = load_system_truetype_font(&base_font_name)
    {
        let units_per_em = get_units_per_em(&data) as f64;
        let (cmap, cmap_is_unicode) = parse_cmap_with_info(&data);
        let post_name_to_gid = stet_fonts::system_fonts::parse_post_table(&data)
            .map(|gid_to_name| {
                gid_to_name
                    .into_iter()
                    .map(|(gid, name)| (name, gid))
                    .collect()
            })
            .unwrap_or_default();
        let to_unicode = if let Some(tu_obj) = font_dict.get(b"ToUnicode") {
            resolver
                .stream_data_from_obj(tu_obj)
                .map(|d| parse_to_unicode(&d))
                .unwrap_or_default()
        } else {
            HashMap::new()
        };
        let gid_hex = TrueTypePdfFont::detect_gid_hex(&encoding);
        return Ok(PdfFont::TrueType(TrueTypePdfFont {
            data,
            encoding,
            widths,
            cmap,
            cmap_is_unicode,
            post_name_to_gid,
            units_per_em,
            to_unicode,
            identity_gid: false, // system font substitutes use normal cmap
            gid_hex,
        }));
    }

    // Final fallback based on subtype (will likely fail)
    match subtype {
        b"TrueType" => resolve_truetype(resolver, &descriptor, encoding, widths, font_dict),
        _ => resolve_type1(
            resolver,
            &descriptor,
            encoding,
            widths,
            has_explicit_encoding,
            has_pdf_widths,
            &differences,
            no_base_encoding,
        ),
    }
}

/// Get the FontDescriptor dict if present.
fn get_font_descriptor(
    font_dict: &PdfDict,
    resolver: &Resolver,
) -> Result<Option<PdfDict>, PdfError> {
    if let Some(fd_ref) = font_dict.get(b"FontDescriptor") {
        let fd_obj = resolver.deref(fd_ref)?;
        if let Some(d) = fd_obj.as_dict() {
            return Ok(Some(d.clone()));
        }
    }
    Ok(None)
}

/// Resolve encoding from font dict.
///
/// Priority: /Encoding dict with /Differences overlay > /Encoding name > StandardEncoding.
/// For symbolic fonts (ZapfDingbats, Symbol) with no explicit /BaseEncoding,
/// the font's built-in encoding is used instead of StandardEncoding.
///
/// Returns (encoding, has_valid_encoding, differences):
/// - `encoding`: fully resolved encoding (base + differences applied)
/// - `has_valid_encoding`: false when /Encoding is missing or unrecognized
/// - `differences`: raw (code, name) pairs from /Differences, populated ONLY when
///   the Encoding is a dict without /BaseEncoding (and not a symbol font). When
///   non-empty, embedded font resolvers should re-apply these on top of the font's
///   built-in encoding instead of using `encoding` directly (PDF spec 9.6.6.1).
fn resolve_encoding(
    font_dict: &PdfDict,
    resolver: &Resolver,
) -> Result<([Option<String>; 256], bool, Vec<(usize, String)>, bool), PdfError> {
    let mut encoding: [Option<String>; 256] = std::array::from_fn(|_| None);
    let mut differences: Vec<(usize, String)> = Vec::new();

    // Start with a base encoding — use the font's built-in encoding for
    // symbolic fonts (PDF spec 9.6.6.1: when no BaseEncoding, symbolic fonts
    // use their built-in encoding, not StandardEncoding).
    let base_font = font_dict.get_name(b"BaseFont").unwrap_or(b"");
    // Strip subset prefix for font name matching
    let clean_base = if base_font.len() > 7 && base_font.get(6) == Some(&b'+') {
        &base_font[7..]
    } else {
        base_font
    };
    let is_symbol_font = clean_base == b"ZapfDingbats" || clean_base == b"Symbol";
    let mut base_table: &[&str; 256] = if clean_base == b"ZapfDingbats" {
        &stet_fonts::encoding::ZAPFDINGBATS_ENCODING
    } else if clean_base == b"Symbol" {
        &stet_fonts::encoding::SYMBOL_ENCODING
    } else {
        &STANDARD_ENCODING
    };

    let mut has_valid_encoding = is_symbol_font; // symbol fonts always have valid built-in encoding
    if let Some(enc_obj) = font_dict.get(b"Encoding") {
        let enc_resolved = resolver.deref(enc_obj)?;
        match &enc_resolved {
            PdfObj::Name(name) => {
                // Symbol/ZapfDingbats: keep their fixed encoding, ignore overrides.
                // Unknown encoding names (e.g. /NULL): skip, keep the default base.
                if !is_symbol_font {
                    if let Some(table) = encoding_table_by_name(name) {
                        base_table = table;
                        has_valid_encoding = true;
                    }
                }
            }
            PdfObj::Dict(enc_dict) => {
                // Dict encoding: optional BaseEncoding + Differences.
                // Symbol/ZapfDingbats keep their fixed base encoding.
                has_valid_encoding = true;
                let mut has_base_encoding = false;
                if !is_symbol_font {
                    if let Some(base_name) = enc_dict.get_name(b"BaseEncoding") {
                        if let Some(table) = encoding_table_by_name(base_name) {
                            base_table = table;
                            has_base_encoding = true;
                        }
                    }
                }
                for (i, &name) in base_table.iter().enumerate() {
                    if name != ".notdef" {
                        encoding[i] = Some(name.to_string());
                    }
                }
                // Parse Differences array (may be an indirect reference)
                if let Some(diffs_obj) = enc_dict.get(b"Differences") {
                    let diffs_resolved = resolver.deref(diffs_obj)?;
                    if let Some(diffs) = diffs_resolved.as_array() {
                        let mut code = 0usize;
                        for obj in diffs {
                            let obj = resolver.deref(obj).unwrap_or(obj.clone());
                            match &obj {
                                PdfObj::Int(n) => code = *n as usize,
                                PdfObj::Name(name) => {
                                    if code < 256 {
                                        let name_str = String::from_utf8_lossy(name).to_string();
                                        encoding[code] = Some(name_str.clone());
                                        // Collect differences when no BaseEncoding was
                                        // specified — embedded fonts need to re-apply
                                        // these on their built-in encoding (PDF 9.6.6.1).
                                        if !has_base_encoding && !is_symbol_font {
                                            differences.push((code, name_str));
                                        }
                                        code += 1;
                                    }
                                }
                                _ => {}
                            }
                        }
                    }
                }
                // Signal "no base encoding" only for non-symbol fonts.
                // Symbol fonts (ZapfDingbats, Symbol) always use their fixed
                // built-in encoding, so their has_base_encoding is never set.
                return Ok((
                    encoding,
                    has_valid_encoding,
                    differences,
                    !has_base_encoding && !is_symbol_font,
                ));
            }
            _ => {}
        }
    }

    // Apply base table
    for (i, &name) in base_table.iter().enumerate() {
        if name != ".notdef" {
            encoding[i] = Some(name.to_string());
        }
    }

    Ok((encoding, has_valid_encoding, differences, false))
}

fn encoding_table_by_name(name: &[u8]) -> Option<&'static [&'static str; 256]> {
    match name {
        b"WinAnsiEncoding" => Some(&WINANSI_ENCODING),
        b"MacRomanEncoding" => Some(&MACROMAN_ENCODING),
        b"StandardEncoding" => Some(&STANDARD_ENCODING),
        _ => None,
    }
}

/// Load a fallback font (Helvetica/NimbusSans) for when no font resource exists.
pub fn fallback_font(font_provider: Option<&FontProvider>) -> Option<PdfFont> {
    let encoding: [Option<String>; 256] = std::array::from_fn(|i| {
        WINANSI_ENCODING.get(i).and_then(|&s| {
            if s.is_empty() {
                None
            } else {
                Some(s.to_string())
            }
        })
    });
    let widths = super::standard_fonts::standard_font_widths(b"Helvetica").unwrap_or([0.0f64; 256]);
    substitute_font(
        "Helvetica",
        encoding,
        widths,
        false,
        font_provider,
        0,
        0,
        255,
    )
}

/// Try to load a substitute font for a non-embedded font.
/// Load a predefined CMap file by searching multiple locations.
///
/// Search order:
/// 1. `STET_CMAP_DIR` environment variable (flat directory of CMap files)
/// 2. `~/.local/share/stet/CMap/` (user-local conventional location)
/// 3. System poppler-data directories (per-collection subdirs)
/// 4. System GhostScript directories
fn load_predefined_cmap(name: &[u8]) -> Option<Vec<u8>> {
    let name_str = std::str::from_utf8(name).ok()?;

    // 1. User-specified directory via environment variable
    if let Ok(dir) = std::env::var("STET_CMAP_DIR") {
        let path = format!("{}/{}", dir, name_str);
        if let Ok(data) = std::fs::read(&path) {
            return Some(data);
        }
    }

    // 2. User-local conventional location (~/.local/share/stet/CMap/)
    if let Some(home) = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")) {
        let path = std::path::Path::new(&home)
            .join(".local/share/stet/CMap")
            .join(name_str);
        if let Ok(data) = std::fs::read(&path) {
            return Some(data);
        }
    }

    // 3. System poppler-data directories (Linux/macOS)
    // poppler organizes CMaps in per-collection subdirs (Adobe-GB1/, Adobe-Japan1/, etc.)
    let poppler_dirs = [
        "/usr/share/poppler/cMap",
        "/usr/local/share/poppler/cMap",
        "/opt/homebrew/share/poppler/cMap", // macOS Homebrew ARM
        "/usr/local/opt/poppler-data/share/poppler/cMap", // macOS Homebrew Intel
    ];
    let collections = [
        "Adobe-GB1",
        "Adobe-CNS1",
        "Adobe-Japan1",
        "Adobe-Japan2",
        "Adobe-Korea1",
        "Adobe-KR",
    ];
    for base in &poppler_dirs {
        for collection in &collections {
            let path = format!("{}/{}/{}", base, collection, name_str);
            if let Ok(data) = std::fs::read(&path) {
                return Some(data);
            }
        }
    }

    // 4. GhostScript directories (flat CMap dirs)
    let gs_dirs = [
        "/var/lib/ghostscript/CMap",
        "/usr/share/ghostscript/Resource/CMap",
        "/usr/local/share/ghostscript/Resource/CMap",
    ];
    for dir in &gs_dirs {
        let path = format!("{}/{}", dir, name_str);
        if let Ok(data) = std::fs::read(&path) {
            return Some(data);
        }
    }

    None
}

fn substitute_font(
    base_font: &str,
    encoding: [Option<String>; 256],
    widths: [f64; 256],
    has_pdf_widths: bool,
    font_provider: Option<&FontProvider>,
    descriptor_flags: u32,
    first_char: usize,
    last_char: usize,
) -> Option<PdfFont> {
    use stet_fonts::FONT_SUBSTITUTIONS;

    // Strip subset prefix (e.g. "ABCDEF+Times-Roman" → "Times-Roman")
    let mut clean_name: &str = base_font;
    if clean_name.len() > 7 && clean_name.as_bytes().get(6) == Some(&b'+') {
        clean_name = &clean_name[7..];
    }
    // Strip trailing "*N" suffix (e.g. "ArialMT*1" → "ArialMT")
    if let Some(star_pos) = clean_name.rfind('*') {
        clean_name = &clean_name[..star_pos];
    }

    // Look up substitution (exact match first, then fuzzy family match)
    let urw_name = FONT_SUBSTITUTIONS
        .iter()
        .find(|&&(ps, _)| ps == clean_name)
        .map(|&(_, urw)| urw)
        .or_else(|| fuzzy_font_match(clean_name));

    let font_file_name = urw_name.unwrap_or(clean_name);

    // Try the font provider first (for WASM and other non-filesystem environments)
    let font_data = if let Some(provider) = font_provider {
        provider(font_file_name)
    } else {
        None
    };

    // Try system font (full glyph set) before bundled subset
    let font_data = font_data.or_else(|| {
        let cache = stet_fonts::system_fonts::get_system_font_cache();
        let path = cache.get_font_path(font_file_name)?;
        read_font_file(path, font_file_name).ok()
    });

    // Fall back to bundled subset font
    let font_data = font_data.or_else(|| embedded_font(font_file_name));

    // If the named font wasn't found, use a default substitute based on the
    // font descriptor Flags (serif bit) and weight/style from the font name.
    let font_data = font_data.or_else(|| {
        let lower = clean_name.to_ascii_lowercase();
        let is_bold = lower.contains("bold")
            || lower.contains("demi")
            || lower.contains("black")
            || lower.contains("heavy");
        let is_italic = lower.contains("italic") || lower.contains("oblique");
        let is_serif = descriptor_flags & 2 != 0; // PDF flag bit 2 = Serif
        let default_name = if is_serif {
            match (is_bold, is_italic) {
                (true, true) => "NimbusRoman-BoldItalic",
                (true, false) => "NimbusRoman-Bold",
                (false, true) => "NimbusRoman-Italic",
                (false, false) => "NimbusRoman-Regular",
            }
        } else {
            match (is_bold, is_italic) {
                (true, true) => "NimbusSans-BoldItalic",
                (true, false) => "NimbusSans-Bold",
                (false, true) => "NimbusSans-Italic",
                (false, false) => "NimbusSans-Regular",
            }
        };
        if let Some(provider) = font_provider {
            if let Some(data) = provider(default_name) {
                return Some(data);
            }
        }
        embedded_font(default_name)
    })?;

    let font = parse_type1(&font_data).ok()?;
    let fm = font.font_matrix;
    let mut font_matrix = Matrix::new(fm[0], fm[1], fm[2], fm[3], fm[4], fm[5]);
    let mut per_char_scale = false;

    // If the PDF didn't provide an explicit /Widths array, derive widths from
    // the substitute font's charstrings. Standard 14 font fallback tables are
    // indexed by StandardEncoding and give wrong widths for other encodings
    // (WinAnsiEncoding, MacRomanEncoding, or custom /Differences).
    let widths = if !has_pdf_widths {
        let mut derived = [0.0f64; 256];
        // Get .notdef width as fallback for unmapped codes
        let notdef_width = font
            .charstrings
            .get(".notdef")
            .and_then(|cs| execute_charstring(cs, &font.subrs, font.len_iv, false).ok())
            .map(|r| r.width_x * fm[0])
            .unwrap_or(0.0);
        for code in 0..256usize {
            let glyph_name = encoding[code].as_deref().unwrap_or(".notdef");
            if let Some(cs) = font.charstrings.get(glyph_name) {
                if let Ok(result) = execute_charstring(cs, &font.subrs, font.len_iv, false) {
                    // Width is in glyph space; scale by font matrix to get text space
                    derived[code] = result.width_x * fm[0];
                }
            } else {
                // Glyph not found — use .notdef width
                derived[code] = notdef_width;
            }
        }
        derived
    } else {
        // When the substitute font's glyph widths differ significantly from the
        // PDF's expected widths, scale glyph outlines horizontally to match.
        // This handles narrow/condensed variants AND unembedded decorative fonts
        // (e.g. Spumoni) where the substitute (NimbusSans) has wider glyphs.
        //
        // Skip for symbol/dingbat fonts — their glyph shapes are completely
        // unrelated to the text glyphs in the substitute, so a global width
        // ratio would just stretch the wrong glyphs.
        let is_symbol_font = {
            let lower = clean_name.to_ascii_lowercase();
            lower.contains("wingding") || lower.contains("webding") || lower.contains("dingbat")
        };
        if !is_symbol_font {
            let mut pdf_sum = 0.0;
            let mut sub_sum = 0.0;
            let mut count = 0;
            // Only compare widths within the PDF's /Widths range [FirstChar, LastChar].
            // Characters outside this range may have /MissingWidth values that don't
            // represent real glyph usage and would skew the scaling ratio.
            for code in first_char..=last_char.min(255) {
                let pdf_w = widths[code];
                if pdf_w <= 0.0 {
                    continue;
                }
                let glyph_name = match encoding[code].as_deref() {
                    Some(n) if n != ".notdef" && n != "space" => n,
                    _ => continue,
                };
                if let Some(cs) = font.charstrings.get(glyph_name)
                    && let Ok(result) = execute_charstring(cs, &font.subrs, font.len_iv, false)
                {
                    let sub_w = result.width_x * fm[0];
                    if sub_w > 0.0 {
                        let ratio = pdf_w / sub_w;
                        // Skip mismatched entries (likely unused encoding slots)
                        if ratio > 0.5 && ratio < 2.0 {
                            pdf_sum += pdf_w;
                            sub_sum += sub_w;
                            count += 1;
                        }
                    }
                }
            }
            if count >= 3 && sub_sum > 0.0 && !is_standard_14_alias(clean_name) {
                // Standard 14 fonts (and their `,Bold`/`,Italic` aliases) use
                // metric-compatible URW Nimbus substitutes by design — the
                // substitute's natural glyph widths already track the original
                // closely. Skipping the rescale here matches Acrobat / PDF.js
                // behavior (PDF.js bug 1671312 / PR #12725): PDFs that author
                // `Tc` and `TJ` kerning against the original font's natural
                // widths render correctly only when the substitute is left at
                // its natural metrics. Forcing PDF `/Widths` onto the glyph,
                // either globally via `font_matrix.a` or per-glyph via
                // `per_char_scale`, breaks both the bug-1671312 case (overlaps
                // and gaps in "Purposes") and PDFs whose `/Widths` array is
                // skewed by placeholder values for unused code points.
                let ratio = pdf_sum / sub_sum;
                if (ratio - 1.0).abs() > 0.03 {
                    font_matrix.a *= ratio;
                    // Non-metric-compatible substitute: enable per-character
                    // width scaling (e.g. NimbusSans for LucidaSans).
                    per_char_scale = true;
                }
            }
        }
        widths
    };

    // Substitute fonts don't use Multiple Master blending
    let weight_vector = font.weight_vector.clone();

    Some(PdfFont::Type1(Type1PdfFont {
        font,
        encoding,
        widths,
        font_matrix,
        builtin_fallback: false,
        weight_vector,
        per_char_width_scale: per_char_scale,
    }))
}

/// Returns true if `name` (after normalizing commas to hyphens) is one of the
/// PDF standard 14 base fonts. Used to suppress per-glyph horizontal squashing
/// for substitute fonts (PDF.js bug 1671312 / PR #12725): the standard 14
/// substitutes (URW Nimbus family) are metric-compatible by design, so
/// rescaling glyphs to the PDF's `/Widths` corrupts text whose `Tc` values
/// were calibrated against the original font's natural widths.
///
/// "Narrow" family members (e.g. ArialNarrow) are deliberately excluded —
/// they aren't standard 14, so they retain the squashing path because their
/// substitute (regular-width Arial/Helvetica) genuinely needs to be
/// horizontally compressed.
fn is_standard_14_alias(name: &str) -> bool {
    let normalized = name.replace(',', "-");
    matches!(
        normalized.as_str(),
        "Times-Roman"
            | "Times-Bold"
            | "Times-Italic"
            | "Times-BoldItalic"
            | "Helvetica"
            | "Helvetica-Bold"
            | "Helvetica-Oblique"
            | "Helvetica-BoldOblique"
            | "Courier"
            | "Courier-Bold"
            | "Courier-Oblique"
            | "Courier-BoldOblique"
            | "Symbol"
            | "ZapfDingbats"
    )
}

/// Fuzzy font family matching for names not in the substitution table.
/// Detects common family name patterns and maps to URW equivalents.
fn fuzzy_font_match(name: &str) -> Option<&'static str> {
    let lower = name.to_ascii_lowercase();
    let is_bold = lower.contains("bold") || lower.contains("demi");
    let is_italic = lower.contains("italic") || lower.contains("oblique");

    // Strip trailing PostScript style suffixes so we match the *family*
    // name, not a style word. Without this "MetaPlusMedium-Roman" (a
    // sans-serif) would match the "roman" serif cue below and end up
    // substituted with NimbusRoman. "Roman" in a PS font name normally
    // means "regular upright", not "serif".
    let family = strip_style_suffix(&lower);

    if family.contains("times") || family.contains("serif") {
        return Some(match (is_bold, is_italic) {
            (true, true) => "NimbusRoman-BoldItalic",
            (true, false) => "NimbusRoman-Bold",
            (false, true) => "NimbusRoman-Italic",
            (false, false) => "NimbusRoman-Regular",
        });
    }
    if family.contains("helvetica")
        || family.contains("arial")
        || family.contains("sans")
        || family.contains("calibri")
        || family.contains("verdana")
        || family.contains("tahoma")
    {
        return Some(match (is_bold, is_italic) {
            (true, true) => "NimbusSans-BoldItalic",
            (true, false) => "NimbusSans-Bold",
            (false, true) => "NimbusSans-Italic",
            (false, false) => "NimbusSans-Regular",
        });
    }
    if family.contains("courier") || family.contains("mono") {
        return Some(match (is_bold, is_italic) {
            (true, true) => "NimbusMonoPS-BoldItalic",
            (true, false) => "NimbusMonoPS-Bold",
            (false, true) => "NimbusMonoPS-Italic",
            (false, false) => "NimbusMonoPS-Regular",
        });
    }
    None
}

/// Strip trailing style words (`-Roman`, `-Regular`, etc.) so family-name
/// pattern matching sees the family, not the style. Works on an
/// already-lowercased string. Only touches the very end of the name.
fn strip_style_suffix(lower: &str) -> &str {
    // Order matters: longer variants first so "-bookitalic" doesn't match "italic".
    const SUFFIXES: &[&str] = &[
        "-roman", " roman", "-regular", " regular", "-medium", " medium", "-book", " book",
        "-normal", " normal", "-light", " light",
    ];
    for suffix in SUFFIXES {
        if let Some(prefix) = lower.strip_suffix(suffix) {
            return prefix;
        }
    }
    lower
}

/// Known CID font substitutions for fonts commonly missing on Linux.
const CID_FONT_SUBSTITUTIONS: &[(&str, &str)] = &[
    ("ArialUnicodeMS", "DejaVuSans"),
    ("Arial", "LiberationSans"),
    ("Arial,Bold", "LiberationSans-Bold"),
    ("Arial,BoldItalic", "LiberationSans-BoldItalic"),
    ("Arial,Italic", "LiberationSans-Italic"),
    ("Arial-BoldMT", "LiberationSans-Bold"),
    ("Arial-BoldItalicMT", "LiberationSans-BoldItalic"),
    ("Arial-ItalicMT", "LiberationSans-Italic"),
    ("Arial-ItalicMT,Italic", "LiberationSans-Italic"),
    ("ArialMT", "LiberationSans"),
    // Arial Black is a heavy-weight sans-serif; Liberation Sans Bold is the
    // closest substitute with compatible TrueType glyph ordering.
    ("ArialBlack", "LiberationSans-Bold"),
    ("ArialBlack,Bold", "LiberationSans-Bold"),
    ("ArialBlack,Italic", "LiberationSans-BoldItalic"),
    ("ArialBlack,BoldItalic", "LiberationSans-BoldItalic"),
    ("Arial-BlackMT", "LiberationSans-Bold"),
    ("CourierNew", "LiberationMono"),
    ("CourierNew,Bold", "LiberationMono-Bold"),
    ("CourierNew,BoldItalic", "LiberationMono-BoldItalic"),
    ("CourierNew,Italic", "LiberationMono-Italic"),
    ("CourierNewPS-BoldMT", "LiberationMono-Bold"),
    ("CourierNewPS-BoldItalicMT", "LiberationMono-BoldItalic"),
    ("CourierNewPS-ItalicMT", "LiberationMono-Italic"),
    ("CourierNewPSMT", "LiberationMono"),
    ("LucidaConsole", "LiberationMono"),
    ("LucidaConsole,Bold", "LiberationMono-Bold"),
    ("Calibri", "LiberationSans"),
    ("Calibri,Bold", "LiberationSans-Bold"),
    ("Calibri,BoldItalic", "LiberationSans-BoldItalic"),
    ("Calibri,Italic", "LiberationSans-Italic"),
    ("CenturyGothic", "LiberationSans"),
    ("CenturyGothic,Bold", "LiberationSans-Bold"),
    ("CenturyGothic,BoldItalic", "LiberationSans-BoldItalic"),
    ("CenturyGothic,Italic", "LiberationSans-Italic"),
    ("TimesNewRoman", "LiberationSerif"),
    ("TimesNewRoman,Bold", "LiberationSerif-Bold"),
    ("TimesNewRoman,BoldItalic", "LiberationSerif-BoldItalic"),
    ("TimesNewRoman,Italic", "LiberationSerif-Italic"),
    ("TimesNewRomanPS-BoldMT", "LiberationSerif-Bold"),
    ("TimesNewRomanPS-BoldItalicMT", "LiberationSerif-BoldItalic"),
    ("TimesNewRomanPS-ItalicMT", "LiberationSerif-Italic"),
    ("TimesNewRomanPSMT", "LiberationSerif"),
    // Japanese CJK fonts → NotoSansCJK (OpenType/CFF, has both ASCII and CJK)
    ("HeiseiMin-W3", "NotoSansCJKjp-Regular"),
    ("HeiseiKakuGo-W5", "NotoSansCJKjp-Regular"),
    ("KozMinPr6N-Regular", "NotoSansCJKjp-Regular"),
    ("KozGoPr6N-Medium", "NotoSansCJKjp-Regular"),
    ("MS-Gothic", "NotoSansCJKjp-Regular"),
    ("MS-Gothic,Bold", "NotoSansCJKjp-Bold"),
    ("MS-Gothic,Italic", "NotoSansCJKjp-Regular"),
    ("MS-Gothic,BoldItalic", "NotoSansCJKjp-Bold"),
    ("MS-PGothic", "NotoSansCJKjp-Regular"),
    ("MS-PGothic,Bold", "NotoSansCJKjp-Bold"),
    ("MS-PGothic,Italic", "NotoSansCJKjp-Regular"),
    ("MS-PGothic,BoldItalic", "NotoSansCJKjp-Bold"),
    ("MS-Mincho", "NotoSansCJKjp-Regular"),
    ("MS-Mincho,Bold", "NotoSansCJKjp-Bold"),
    ("MS-Mincho,Italic", "NotoSansCJKjp-Regular"),
    ("MS-Mincho,BoldItalic", "NotoSansCJKjp-Bold"),
    ("MS-PMincho", "NotoSansCJKjp-Regular"),
    ("MS-PMincho,Bold", "NotoSansCJKjp-Bold"),
    ("MS-PMincho,Italic", "NotoSansCJKjp-Regular"),
    ("MS-PMincho,BoldItalic", "NotoSansCJKjp-Bold"),
    ("MSGothic", "NotoSansCJKjp-Regular"),
    ("MSPGothic", "NotoSansCJKjp-Regular"),
    ("MSMincho", "NotoSansCJKjp-Regular"),
    ("MSPMincho", "NotoSansCJKjp-Regular"),
    // Korean CJK fonts
    ("Batang", "NotoSansCJKkr-Regular"),
    ("BatangChe", "NotoSansCJKkr-Regular"),
    ("Dotum", "NotoSansCJKkr-Regular"),
    ("DotumChe", "NotoSansCJKkr-Regular"),
    ("Gulim", "NotoSansCJKkr-Regular"),
    ("GulimChe", "NotoSansCJKkr-Regular"),
    // Chinese Simplified CJK fonts (Adobe standard CID fonts)
    // NotoSerifCJKjp contains all CJK glyphs including SC/TC
    ("STSongStd-Light", "NotoSerifCJKjp-Regular"),
    ("STSong-Light", "NotoSerifCJKjp-Regular"),
    ("AdobeSongStd-Light", "NotoSerifCJKjp-Regular"),
    ("STFangsong-Light", "NotoSerifCJKjp-Regular"),
    ("STHeiti-Regular", "NotoSansCJKjp-Regular"),
    ("STKaiti-Regular", "NotoSansCJKjp-Regular"),
    ("SimSun", "NotoSerifCJKjp-Regular"),
    ("SimSunBold", "NotoSerifCJKjp-Bold"),
    ("SimHei", "NotoSansCJKjp-Regular"),
    ("FangSong", "NotoSerifCJKjp-Regular"),
    ("KaiTi", "NotoSansCJKjp-Regular"),
    // Chinese Traditional CJK fonts (Adobe standard CID fonts)
    ("MSungStd-Light", "NotoSerifCJKjp-Regular"),
    ("MSung-Light", "NotoSerifCJKjp-Regular"),
    ("AdobeMingStd-Light", "NotoSerifCJKjp-Regular"),
    ("MHei-Medium", "NotoSansCJKjp-Regular"),
    ("MingLiU", "NotoSerifCJKjp-Regular"),
    ("PMingLiU", "NotoSerifCJKjp-Regular"),
];

/// Map proportional Unicode code points to CJK full-width variants.
///
/// Substitute fonts (e.g. NotoSansCJK) may render certain characters as
/// proportional (narrow) glyphs, but the original CJK font used full-width
/// versions. Return the full-width alternative if one exists.
fn cjk_fullwidth_alternative(unicode: u32) -> Option<u32> {
    match unicode {
        // MIDDLE DOT → KATAKANA MIDDLE DOT (full-width, centered in em square)
        0x00B7 => Some(0x30FB),
        _ => None,
    }
}

/// Check if an OpenType/CFF font contains a CID-keyed CFF (has ROS operator).
fn is_cff_cid_keyed(otf_data: &[u8]) -> bool {
    use stet_fonts::truetype::find_table;
    let Some((cff_off, cff_len)) = find_table(otf_data, b"CFF ") else {
        return false;
    };
    let cff_data = &otf_data[cff_off..cff_off + cff_len];
    match parse_cff(cff_data) {
        Ok(fonts) => fonts.first().map_or(false, |f| f.is_cid),
        Err(_) => false,
    }
}

/// Create a CidCff font from an OpenType/CFF system font (OTTO magic).
/// Extracts the CFF table and builds a CidCffPdfFont.
fn create_cid_cff_from_otf(
    otf_data: &[u8],
    default_width: f64,
    cid_widths: HashMap<u16, f64>,
    ordering: &[u8],
    pdf_cid_to_gid: Option<Vec<u16>>,
    identity_cid_to_gid: bool,
    code_lengths: [u8; 256],
    code_to_cid: HashMap<u32, u32>,
    wmode: u8,
    dw2: [f64; 2],
    w2: HashMap<u16, [f64; 3]>,
) -> Result<PdfFont, PdfError> {
    use stet_fonts::truetype::find_table;

    // Extract CFF table from OpenType font
    let (cff_off, cff_len) = find_table(otf_data, b"CFF ")
        .ok_or(PdfError::Other("OpenType font has no CFF table".into()))?;
    let cff_data = &otf_data[cff_off..cff_off + cff_len];
    let fonts =
        parse_cff(cff_data).map_err(|e| PdfError::Other(format!("CFF parse error: {e}")))?;
    let font = fonts
        .into_iter()
        .next()
        .ok_or(PdfError::Other("CFF contains no fonts".into()))?;
    let fm = font.font_matrix;
    let font_matrix = Matrix::new(fm[0], fm[1], fm[2], fm[3], fm[4], fm[5]);

    // Parse cmap from OTF for Unicode→GID lookup (substitute fonts)
    let otf_cmap = parse_cmap(otf_data);
    let cmap = if otf_cmap.is_empty() {
        None
    } else {
        Some(otf_cmap)
    };

    Ok(PdfFont::CidCff(CidCffPdfFont {
        font,
        default_width,
        cid_widths,
        font_matrix,
        cmap,
        pdf_cid_to_gid,
        identity_cid_to_gid,
        ordering: ordering.to_vec(),
        code_lengths,
        code_to_cid,
        wmode,
        dw2,
        w2,
        type1_paths: None,
    }))
}

/// Detect raw CFF font data (not wrapped in an OpenType container).
/// CFF starts with: major=1, minor=0, hdrSize>=4, offSize in 1..=4.
fn is_raw_cff(data: &[u8]) -> bool {
    data.len() > 4 && data[0] == 1 && data[1] == 0 && data[2] >= 4 && (1..=4).contains(&data[3])
}

/// Create a CidCff font from raw CFF data (no OpenType wrapper).
fn create_cid_cff_from_raw(
    cff_data: &[u8],
    default_width: f64,
    cid_widths: HashMap<u16, f64>,
    ordering: &[u8],
    pdf_cid_to_gid: Option<Vec<u16>>,
    identity_cid_to_gid: bool,
    code_lengths: [u8; 256],
    code_to_cid: HashMap<u32, u32>,
    wmode: u8,
    dw2: [f64; 2],
    w2: HashMap<u16, [f64; 3]>,
) -> Result<PdfFont, PdfError> {
    let fonts =
        parse_cff(cff_data).map_err(|e| PdfError::Other(format!("CFF parse error: {e}")))?;
    let font = fonts
        .into_iter()
        .next()
        .ok_or(PdfError::Other("CFF contains no fonts".into()))?;
    let fm = font.font_matrix;
    let font_matrix = Matrix::new(fm[0], fm[1], fm[2], fm[3], fm[4], fm[5]);

    Ok(PdfFont::CidCff(CidCffPdfFont {
        font,
        default_width,
        cid_widths,
        font_matrix,
        cmap: None, // Raw CFF has no OTF cmap table
        pdf_cid_to_gid,
        identity_cid_to_gid,
        ordering: ordering.to_vec(),
        code_lengths,
        code_to_cid,
        wmode,
        dw2,
        w2,
        type1_paths: None,
    }))
}

/// Largest plausible byte-width for an offset field in a PS CIDFont header
/// (`/FDBytes`, `/GDBytes`, `/SDBytes`).
///
/// These state how many bytes each entry of the CID map and subroutine map
/// occupies, so they index into the font's binary segment. Eight bytes is
/// already a 64-bit offset; anything larger is a malformed header, and left
/// unchecked it overflows the `entry_size` and map-size products computed
/// from it.
const MAX_OFFSET_BYTES: usize = 8;

/// Create a CID font from a PostScript CIDFont program (Resource-CIDFont).
///
/// These contain CIDFontType 0 definitions with binary charstring data after
/// `StartData`. The binary data layout: CID map (GDBytes×CIDCount) followed
/// by subroutines and charstring data indexed by offsets in the CID map.
fn create_cid_from_ps_cidfont(
    font_data: &[u8],
    default_width: f64,
    cid_widths: HashMap<u16, f64>,
    code_lengths: [u8; 256],
    code_to_cid: HashMap<u32, u32>,
    wmode: u8,
    dw2: [f64; 2],
    w2: HashMap<u16, [f64; 3]>,
) -> Result<PdfFont, PdfError> {
    let text = String::from_utf8_lossy(font_data);

    // Extract key parameters from the PS header
    let get_int = |key: &str| -> Option<usize> {
        let pat = format!("/{key}");
        let idx = text.find(&pat)?;
        let rest = &text[idx + pat.len()..];
        rest.split_whitespace().next()?.parse().ok()
    };

    // These six drive every allocation and offset below, and all six come
    // from the font program's own text header. `get_int` parses into `usize`,
    // so a negative is already rejected — but a value like 2^64-1 parses
    // fine, and the products it forms overflow. The byte-width fields are
    // held to `MAX_OFFSET_BYTES` (they index into the binary segment, so a
    // width past 8 is meaningless), and the counts are bounded below against
    // the data actually present rather than against a made-up ceiling.
    let cid_count = get_int("CIDCount").unwrap_or(0);
    let fd_bytes = get_int("FDBytes").unwrap_or(0);
    let gd_bytes = get_int("GDBytes").unwrap_or(4);
    let subr_map_offset = get_int("SubrMapOffset").unwrap_or(0);
    let sd_bytes = get_int("SDBytes").unwrap_or(4);
    let subr_count = get_int("SubrCount").unwrap_or(0);
    if fd_bytes > MAX_OFFSET_BYTES || gd_bytes > MAX_OFFSET_BYTES || sd_bytes > MAX_OFFSET_BYTES {
        return Err(PdfError::Other(
            "PS CIDFont: implausible FDBytes/GDBytes/SDBytes".into(),
        ));
    }

    let len_iv = get_int("lenIV").unwrap_or(4) as u16;

    // Extract FontMatrix from the FDArray Private dict
    let font_matrix = if let Some(fm_idx) = text.find("/FontMatrix") {
        let rest = &text[fm_idx..];
        if let Some(start) = rest.find('[') {
            let end_bracket = rest[start..].find(']').unwrap_or(50) + start;
            let vals: Vec<f64> = rest[start + 1..end_bracket]
                .split_whitespace()
                .filter_map(|s| s.parse().ok())
                .collect();
            if vals.len() == 6 {
                Matrix::new(vals[0], vals[1], vals[2], vals[3], vals[4], vals[5])
            } else {
                Matrix::new(0.001, 0.0, 0.0, 0.001, 0.0, 0.0)
            }
        } else {
            Matrix::new(0.001, 0.0, 0.0, 0.001, 0.0, 0.0)
        }
    } else {
        Matrix::new(0.001, 0.0, 0.0, 0.001, 0.0, 0.0)
    };

    // Extract subrs from the Private dict (OtherSubrs / Subrs style)
    // For PS CIDFonts, subroutines are in the binary data, not in the PS text.

    // Find the binary data after "StartData"
    // Format: "(Binary) NNNN StartData<whitespace><binary data>"
    // The binary data begins after "StartData" + one whitespace byte.
    // We must NOT skip \x00 bytes — they are part of the binary CID map.
    let binary_data = {
        let sd_marker = b"StartData";
        let pos = font_data
            .windows(sd_marker.len())
            .position(|w| w == sd_marker)
            .ok_or(PdfError::Other("PS CIDFont: no StartData found".into()))?;
        let after = &font_data[pos + sd_marker.len()..];
        // Skip only ASCII whitespace (space, tab, CR, LF) — NOT null bytes
        let skip = after
            .iter()
            .position(|&b| !matches!(b, b' ' | b'\t' | b'\r' | b'\n'))
            .unwrap_or(0);
        &font_data[pos + sd_marker.len() + skip..]
    };

    // Parse CID map: CIDCount × (FDBytes + GDBytes) bytes.
    //
    // `entry_size` must be at least 1. At zero, `cid_map_size` is zero for any
    // `cid_count`, so the length check below passes and `CIDCount` stays
    // completely unbounded — the reservation that follows then tries to
    // allocate terabytes from a 700-byte file.
    let entry_size = fd_bytes + gd_bytes;
    if entry_size == 0 {
        return Err(PdfError::Other(
            "PS CIDFont: FDBytes + GDBytes is zero".into(),
        ));
    }
    let Some(cid_map_size) = cid_count.checked_mul(entry_size) else {
        return Err(PdfError::Other("PS CIDFont: CID map size overflows".into()));
    };
    if binary_data.len() < cid_map_size {
        return Err(PdfError::Other(
            "PS CIDFont: binary data too short for CID map".into(),
        ));
    }
    // With `entry_size >= 1`, the check above bounds `cid_count` by the length
    // of the binary segment, so the reservation below is bounded by the file.

    // Read charstring offsets for each CID
    let read_be = |data: &[u8], off: usize, n: usize| -> usize {
        let mut val = 0usize;
        for i in 0..n {
            if off + i < data.len() {
                val = (val << 8) | data[off + i] as usize;
            }
        }
        val
    };

    let mut cid_offsets: Vec<usize> = Vec::with_capacity(cid_count + 1);
    for c in 0..cid_count {
        let entry_off = c * entry_size + fd_bytes;
        let offset = read_be(binary_data, entry_off, gd_bytes);
        cid_offsets.push(offset);
    }
    // Sentinel: end of last charstring = start of subroutine map
    cid_offsets.push(subr_map_offset);

    // Parse subroutine offsets.
    //
    // The bounds check has to happen *before* the reservation, not after:
    // reserving `subr_count` entries up front is what turns a bogus
    // `/SubrCount` into a "capacity overflow" panic (in release as well as
    // debug) or a multi-exabyte allocation, and the check below never gets the
    // chance to reject it. The arithmetic is checked for the same reason —
    // `subr_map_offset + (subr_count + 1) * sd_bytes` overflows to a small
    // number for large inputs, which would make the check *pass*.
    let subr_map_fits = sd_bytes > 0
        && subr_count
            .checked_add(1)
            .and_then(|n| n.checked_mul(sd_bytes))
            .and_then(|n| n.checked_add(subr_map_offset))
            .is_some_and(|end| end <= binary_data.len());

    let mut subrs: Vec<Vec<u8>> = Vec::new();
    if subr_count > 0 && subr_map_fits {
        subrs.reserve(subr_count);
        let mut sub_offsets: Vec<usize> = Vec::with_capacity(subr_count + 1);
        for i in 0..=subr_count {
            let off = read_be(binary_data, subr_map_offset + i * sd_bytes, sd_bytes);
            sub_offsets.push(off);
        }
        for i in 0..subr_count {
            let start = sub_offsets[i];
            let end = sub_offsets[i + 1];
            if start < end && end <= binary_data.len() {
                subrs.push(binary_data[start..end].to_vec());
            } else {
                subrs.push(Vec::new());
            }
        }
    }

    // Execute charstrings for each CID that has a width entry
    let mut paths = HashMap::new();
    for &cid in cid_widths.keys() {
        let c = cid as usize;
        if c >= cid_count {
            continue;
        }
        let cs_start = cid_offsets[c];
        let cs_end = cid_offsets[c + 1];
        if cs_start >= cs_end || cs_end > binary_data.len() {
            continue;
        }
        let charstring = &binary_data[cs_start..cs_end];
        if let Ok(result) = execute_charstring(charstring, &subrs, len_iv.into(), false) {
            let path = result.path.transform(&font_matrix);
            paths.insert(cid, path);
        }
    }

    // Create dummy CffFont with pre-computed paths
    let dummy_cff = stet_fonts::cff_parser::CffFont {
        name: String::new(),
        font_matrix: [
            font_matrix.a,
            font_matrix.b,
            font_matrix.c,
            font_matrix.d,
            font_matrix.tx,
            font_matrix.ty,
        ],
        font_bbox: [0.0; 4],
        char_strings: Vec::new(),
        global_subrs: Vec::new(),
        local_subrs: Vec::new(),
        charset: Vec::new(),
        encoding: Vec::new(),
        default_width_x: 0.0,
        nominal_width_x: 0.0,
        is_cid: true,
        fd_array: Vec::new(),
        fd_select: Vec::new(),
        ros: None,
        cid_to_gid: Vec::new(),
    };

    Ok(PdfFont::CidCff(CidCffPdfFont {
        font: dummy_cff,
        default_width,
        cid_widths,
        font_matrix,
        cmap: None,
        pdf_cid_to_gid: None,
        identity_cid_to_gid: true,
        ordering: Vec::new(),
        code_lengths,
        code_to_cid,
        wmode,
        dw2,
        w2,
        type1_paths: Some(paths),
    }))
}

/// Create a CID font from Type 1 font data mislabeled as CIDFontType0.
///
/// Parses the Type 1 font, maps each CID to a glyph name via ToUnicode + AGL,
/// executes the charstring, and stores pre-computed paths in a CidCffPdfFont.
fn create_cid_from_type1(
    font_data: &[u8],
    default_width: f64,
    cid_widths: HashMap<u16, f64>,
    _to_unicode: &HashMap<u16, u32>,
    code_lengths: [u8; 256],
    code_to_cid: HashMap<u32, u32>,
    wmode: u8,
    dw2: [f64; 2],
    w2: HashMap<u16, [f64; 3]>,
) -> Result<PdfFont, PdfError> {
    let font =
        parse_type1(font_data).map_err(|e| PdfError::Other(format!("Type1 parse error: {e}")))?;
    let fm = font.font_matrix;
    let font_matrix = Matrix::new(fm[0], fm[1], fm[2], fm[3], fm[4], fm[5]);

    // Build CID → glyph path mapping.
    // The CID directly indexes the Type 1 font's built-in encoding:
    // CID N → encoding[N] → glyph name → charstring → path.
    let mut paths = HashMap::new();
    for (&cid, _) in &cid_widths {
        let glyph_name = if (cid as usize) < font.encoding.len() {
            font.encoding[cid as usize].as_str()
        } else {
            ".notdef"
        };
        if let Some(cs) = font.charstrings.get(glyph_name) {
            if let Ok(result) = execute_charstring(cs, &font.subrs, font.len_iv, false) {
                let path = result.path.transform(&font_matrix);
                paths.insert(cid, path);
            }
        }
    }
    // Also map CIDs that are in the encoding but not in /W
    for (code, name) in font.encoding.iter().enumerate() {
        let cid = code as u16;
        if paths.contains_key(&cid) {
            continue;
        }
        {
            let name = name.as_str();
            if name != ".notdef" {
                if let Some(cs) = font.charstrings.get(name) {
                    if let Ok(result) = execute_charstring(cs, &font.subrs, font.len_iv, false) {
                        let path = result.path.transform(&font_matrix);
                        paths.insert(cid, path);
                    }
                }
            }
        }
    }

    // Create a dummy CffFont — the type1_paths field will be used instead
    let dummy_cff = stet_fonts::cff_parser::CffFont {
        name: font.font_name.clone(),
        font_matrix: fm,
        font_bbox: [0.0; 4],
        char_strings: Vec::new(),
        global_subrs: Vec::new(),
        local_subrs: Vec::new(),
        charset: Vec::new(),
        encoding: Vec::new(),
        default_width_x: 0.0,
        nominal_width_x: 0.0,
        is_cid: false,
        fd_array: Vec::new(),
        fd_select: Vec::new(),
        ros: None,
        cid_to_gid: Vec::new(),
    };

    Ok(PdfFont::CidCff(CidCffPdfFont {
        font: dummy_cff,
        default_width,
        cid_widths,
        font_matrix,
        cmap: None,
        pdf_cid_to_gid: None,
        identity_cid_to_gid: true,
        ordering: Vec::new(),
        code_lengths,
        code_to_cid,
        wmode,
        dw2,
        w2,
        type1_paths: Some(paths),
    }))
}

/// Fix malformed `head.indexToLocFormat` in embedded TrueType fonts.
///
/// Some PDF generators write invalid values (e.g. 256 instead of 0 or 1).
/// Skrifa checks `== 1` for long format, so any value other than 0 or 1
/// causes it to use short format incorrectly. Determine the correct format
/// from the loca table size and patch the head table in-place.
fn sanitize_index_to_loc_format(font_data: &mut [u8]) {
    use stet_fonts::truetype::{find_table, read_i16, read_u16};

    let head = find_table(font_data, b"head");
    let loca = find_table(font_data, b"loca");
    let maxp = find_table(font_data, b"maxp");
    let (head_off, _) = match head {
        Some(h) => h,
        None => return,
    };
    if head_off + 52 > font_data.len() {
        return;
    }
    let format = read_i16(font_data, head_off + 50);
    if format == 0 || format == 1 {
        return; // already valid
    }
    // Determine correct format from loca table size vs numGlyphs
    let correct = if let (Some((_, loca_len)), Some((maxp_off, _))) = (loca, maxp) {
        if maxp_off + 6 <= font_data.len() {
            let num_glyphs = read_u16(font_data, maxp_off + 4) as usize;
            // Long format: (numGlyphs + 1) * 4 bytes
            // Short format: (numGlyphs + 1) * 2 bytes
            if loca_len == (num_glyphs + 1) * 4 {
                1i16 // long
            } else {
                0i16 // short
            }
        } else {
            if format != 0 { 1 } else { 0 }
        }
    } else {
        if format != 0 { 1 } else { 0 }
    };
    font_data[head_off + 50] = (correct >> 8) as u8;
    font_data[head_off + 51] = correct as u8;
}

/// Try to load a TrueType font from the system font cache.
///
/// Used when a CIDFontType2 font is not embedded in the PDF (missing FontFile2).
/// Falls back to substitution table and fuzzy name matching.
fn load_system_truetype_font(base_font: &str) -> Result<Vec<u8>, PdfError> {
    use stet_fonts::system_fonts::get_system_font_cache;

    let cache = get_system_font_cache();

    // Strip subset prefix (e.g. "ABCDEF+Calibri,Bold" → "Calibri,Bold")
    let mut clean_name = base_font;
    if clean_name.len() > 7 && clean_name.as_bytes().get(6) == Some(&b'+') {
        clean_name = &clean_name[7..];
    }

    // Try exact match first
    if let Some(path) = cache.get_font_path(clean_name)
        && let Ok(data) = read_font_file(path, clean_name)
    {
        return Ok(data);
    }

    // Try known substitutions
    for &(from, to) in CID_FONT_SUBSTITUTIONS {
        if from == clean_name
            && let Some(path) = cache.get_font_path(to)
            && let Ok(data) = read_font_file(path, to)
        {
            return Ok(data);
        }
    }

    // Fuzzy family match — split on '-' or ',' to extract family name
    let lower = clean_name.to_ascii_lowercase();
    let is_bold = lower.contains("bold") || lower.contains("demi");
    let is_italic = lower.contains("italic") || lower.contains("oblique");

    for (ps_name, path) in cache.iter() {
        let ps_lower = ps_name.to_ascii_lowercase();
        let family = lower.split(&['-', ','][..]).next().unwrap_or(&lower);
        if ps_lower.contains(family) || family.contains(ps_lower.split('-').next().unwrap_or("")) {
            let name_bold = ps_lower.contains("bold") || ps_lower.contains("demi");
            let name_italic = ps_lower.contains("italic") || ps_lower.contains("oblique");
            if name_bold == is_bold
                && name_italic == is_italic
                && let Ok(data) = read_font_file(path, ps_name)
            {
                return Ok(data);
            }
        }
    }

    Err(PdfError::Other(format!(
        "font '{}' not found on system",
        clean_name
    )))
}

/// Fallback for CID fonts whose names can't be resolved (e.g. GBK-encoded
/// native names like 黑体). Uses the CIDSystemInfo Ordering to select
/// the appropriate Noto CJK regional variant. For non-CJK orderings
/// (Identity), falls back to a Latin sans-serif font instead.
fn load_cjk_fallback_font(ordering: &[u8], base_font: &str) -> Result<Vec<u8>, PdfError> {
    use stet_fonts::system_fonts::get_system_font_cache;

    if ordering.is_empty() {
        return Err(PdfError::Other("no CJK ordering for fallback".into()));
    }

    let cache = get_system_font_cache();
    let lower = base_font.to_ascii_lowercase();
    let is_bold = lower.contains("bold") || lower.contains("demi") || lower.contains("black");

    // For "Identity" ordering, check whether the font name indicates a CJK
    // font. If so, fall through to the CJK lookup path instead of using a
    // Latin fallback that can't render CJK characters.
    // Note: "gothic" needs special handling — it appears in CJK fonts
    // (MSGothic, MS-Gothic, IPAGothic) but also Western fonts (CenturyGothic,
    // FranklinGothic). Only match when preceded by a non-letter (word boundary).
    let has_cjk_gothic = {
        if let Some(pos) = lower.find("gothic") {
            pos == 0 || !lower.as_bytes()[pos - 1].is_ascii_alphabetic()
        } else {
            false
        }
    };
    let is_cjk_name = has_cjk_gothic
        || [
            "cn", "sc", "jp", "kr", "tc", "hk", "cjk", "ming", "song", "hei", "kai", "fang", "han",
        ]
        .iter()
        .any(|kw| lower.contains(kw));
    if ordering == b"Identity" && !is_cjk_name {
        let latin_targets: &[&str] = if is_bold {
            &["LiberationSans-Bold", "DejaVuSans-Bold"]
        } else {
            &["LiberationSans", "DejaVuSans"]
        };
        for &target in latin_targets {
            if let Some(path) = cache.get_font_path(target)
                && let Ok(data) = read_font_file(path, target)
            {
                return Ok(data);
            }
        }
        return Err(PdfError::Other(format!(
            "Latin fallback font not found for '{}'",
            base_font
        )));
    }

    // Noto CJK .ttc files contain JP/SC/TC/HK/KR sub-fonts with different
    // GID orderings. Select the variant matching the font name or ordering
    // so GIDs are compatible with the original font.
    let lang = if lower.contains("cn") || lower.contains("sc") || ordering == b"GB1" {
        "sc"
    } else if lower.contains("tw") || lower.contains("tc") || ordering == b"CNS1" {
        "tc"
    } else if lower.contains("kr") || ordering == b"Korea1" {
        "kr"
    } else if lower.contains("hk") {
        "hk"
    } else {
        "jp" // default: Japan1 or unknown
    };
    let heavy = lower.contains("heavy") || lower.contains("black");
    // Try weight-matched variant first, then regular/bold fallback
    let weight_suffix = if heavy {
        "Black"
    } else if is_bold {
        "Bold"
    } else {
        "Regular"
    };
    let targets = [
        format!("NotoSansCJK{lang}-{weight_suffix}"),
        if is_bold || heavy {
            format!("NotoSansCJK{lang}-Bold")
        } else {
            format!("NotoSansCJK{lang}-Regular")
        },
        format!("NotoSansCJKjp-{weight_suffix}"),
    ];
    for target in &targets {
        if let Some(path) = cache.get_font_path(target)
            && let Ok(data) = read_font_file(path, target)
        {
            return Ok(data);
        }
    }

    Err(PdfError::Other(format!(
        "CJK fallback font not found on system for '{}'",
        base_font
    )))
}

/// Embedded Type 1 substitute fonts (URW families).
/// Compiled into the binary so the PDF reader works from any directory.
const EMBEDDED_FONTS: &[(&str, &[u8])] = &[
    // NimbusRoman (Times)
    (
        "NimbusRoman-Regular",
        include_bytes!("../../fonts/NimbusRoman-Regular.t1"),
    ),
    (
        "NimbusRoman-Bold",
        include_bytes!("../../fonts/NimbusRoman-Bold.t1"),
    ),
    (
        "NimbusRoman-Italic",
        include_bytes!("../../fonts/NimbusRoman-Italic.t1"),
    ),
    (
        "NimbusRoman-BoldItalic",
        include_bytes!("../../fonts/NimbusRoman-BoldItalic.t1"),
    ),
    // NimbusSans (Helvetica/Arial)
    (
        "NimbusSans-Regular",
        include_bytes!("../../fonts/NimbusSans-Regular.t1"),
    ),
    (
        "NimbusSans-Bold",
        include_bytes!("../../fonts/NimbusSans-Bold.t1"),
    ),
    (
        "NimbusSans-Italic",
        include_bytes!("../../fonts/NimbusSans-Italic.t1"),
    ),
    (
        "NimbusSans-BoldItalic",
        include_bytes!("../../fonts/NimbusSans-BoldItalic.t1"),
    ),
    // NimbusSansNarrow (Helvetica Narrow)
    (
        "NimbusSansNarrow-Regular",
        include_bytes!("../../fonts/NimbusSansNarrow-Regular.t1"),
    ),
    (
        "NimbusSansNarrow-Bold",
        include_bytes!("../../fonts/NimbusSansNarrow-Bold.t1"),
    ),
    (
        "NimbusSansNarrow-Oblique",
        include_bytes!("../../fonts/NimbusSansNarrow-Oblique.t1"),
    ),
    (
        "NimbusSansNarrow-BoldOblique",
        include_bytes!("../../fonts/NimbusSansNarrow-BoldOblique.t1"),
    ),
    // NimbusMonoPS (Courier)
    (
        "NimbusMonoPS-Regular",
        include_bytes!("../../fonts/NimbusMonoPS-Regular.t1"),
    ),
    (
        "NimbusMonoPS-Bold",
        include_bytes!("../../fonts/NimbusMonoPS-Bold.t1"),
    ),
    (
        "NimbusMonoPS-Italic",
        include_bytes!("../../fonts/NimbusMonoPS-Italic.t1"),
    ),
    (
        "NimbusMonoPS-BoldItalic",
        include_bytes!("../../fonts/NimbusMonoPS-BoldItalic.t1"),
    ),
    // P052 (Palatino)
    ("P052-Roman", include_bytes!("../../fonts/P052-Roman.t1")),
    ("P052-Bold", include_bytes!("../../fonts/P052-Bold.t1")),
    ("P052-Italic", include_bytes!("../../fonts/P052-Italic.t1")),
    (
        "P052-BoldItalic",
        include_bytes!("../../fonts/P052-BoldItalic.t1"),
    ),
    // C059 (New Century Schoolbook)
    ("C059-Roman", include_bytes!("../../fonts/C059-Roman.t1")),
    ("C059-Bold", include_bytes!("../../fonts/C059-Bold.t1")),
    ("C059-Italic", include_bytes!("../../fonts/C059-Italic.t1")),
    ("C059-BdIta", include_bytes!("../../fonts/C059-BdIta.t1")),
    // URWBookman (Bookman)
    (
        "URWBookman-Light",
        include_bytes!("../../fonts/URWBookman-Light.t1"),
    ),
    (
        "URWBookman-Demi",
        include_bytes!("../../fonts/URWBookman-Demi.t1"),
    ),
    (
        "URWBookman-LightItalic",
        include_bytes!("../../fonts/URWBookman-LightItalic.t1"),
    ),
    (
        "URWBookman-DemiItalic",
        include_bytes!("../../fonts/URWBookman-DemiItalic.t1"),
    ),
    // URWGothic (AvantGarde)
    (
        "URWGothic-Book",
        include_bytes!("../../fonts/URWGothic-Book.t1"),
    ),
    (
        "URWGothic-Demi",
        include_bytes!("../../fonts/URWGothic-Demi.t1"),
    ),
    (
        "URWGothic-BookOblique",
        include_bytes!("../../fonts/URWGothic-BookOblique.t1"),
    ),
    (
        "URWGothic-DemiOblique",
        include_bytes!("../../fonts/URWGothic-DemiOblique.t1"),
    ),
    // Symbol fonts
    (
        "StandardSymbolsPS",
        include_bytes!("../../fonts/StandardSymbolsPS.t1"),
    ),
    ("D050000L", include_bytes!("../../fonts/D050000L.t1")),
    (
        "Z003-MediumItalic",
        include_bytes!("../../fonts/Z003-MediumItalic.t1"),
    ),
];

/// Look up an embedded Type 1 substitute font by name.
fn embedded_font(name: &str) -> Option<Vec<u8>> {
    EMBEDDED_FONTS
        .iter()
        .find(|(n, _)| *n == name)
        .map(|(_, data)| data.to_vec())
}

/// Read a font file, handling TrueType Collection (.ttc) files by extracting
/// the sub-font matching `ps_name` (or the first font if no match found).
fn read_font_file(path: &std::path::Path, ps_name: &str) -> std::io::Result<Vec<u8>> {
    let data = std::fs::read(path)?;
    if data.len() > 12 && &data[0..4] == b"ttcf" {
        // TTC: extract the sub-font at the correct offset
        let num_fonts = u32::from_be_bytes([data[8], data[9], data[10], data[11]]) as usize;
        // Try to find the font matching ps_name by checking each font's name table
        let mut best_offset = if num_fonts > 0 {
            u32::from_be_bytes([data[12], data[13], data[14], data[15]]) as usize
        } else {
            0
        };
        for i in 0..num_fonts {
            let off_pos = 12 + i * 4;
            if off_pos + 4 > data.len() {
                break;
            }
            let font_offset = u32::from_be_bytes([
                data[off_pos],
                data[off_pos + 1],
                data[off_pos + 2],
                data[off_pos + 3],
            ]) as usize;
            // Check PostScript name in the name table of this sub-font
            if let Some(name) = extract_ps_name_at_offset(&data, font_offset)
                && name == ps_name
            {
                best_offset = font_offset;
                break;
            }
        }
        // Build a standalone TTF by rewriting the header to point to tables
        // at their absolute offsets within the TTC
        extract_ttf_from_ttc(&data, best_offset)
    } else {
        Ok(data)
    }
}

/// Extract the PostScript name from a font at a given offset within TTC data.
fn extract_ps_name_at_offset(data: &[u8], offset: usize) -> Option<String> {
    use stet_fonts::truetype::read_u16;
    // Manually find the 'name' table from the sub-font's table directory
    if offset + 12 > data.len() {
        return None;
    }
    let num_tables = read_u16(data, offset + 4) as usize;
    let mut name_off = 0usize;
    let mut name_len = 0usize;
    for i in 0..num_tables {
        let entry = offset + 12 + i * 16;
        if entry + 16 > data.len() {
            break;
        }
        if &data[entry..entry + 4] == b"name" {
            name_off = u32::from_be_bytes([
                data[entry + 8],
                data[entry + 9],
                data[entry + 10],
                data[entry + 11],
            ]) as usize;
            name_len = u32::from_be_bytes([
                data[entry + 12],
                data[entry + 13],
                data[entry + 14],
                data[entry + 15],
            ]) as usize;
            break;
        }
    }
    if name_off == 0 || name_off + name_len > data.len() {
        return None;
    }
    let nd = &data[name_off..name_off + name_len];
    let count = read_u16(nd, 2) as usize;
    let string_offset = read_u16(nd, 4) as usize;
    for i in 0..count {
        let rec = 6 + i * 12;
        if rec + 12 > nd.len() {
            break;
        }
        let pid = read_u16(nd, rec);
        let name_id = read_u16(nd, rec + 6);
        let length = read_u16(nd, rec + 8) as usize;
        let str_off = read_u16(nd, rec + 10) as usize;
        if name_id == 6 {
            let start = string_offset + str_off;
            if start + length <= nd.len() {
                let raw = &nd[start..start + length];
                if pid == 3 {
                    let s: String = raw
                        .chunks(2)
                        .filter_map(|c| {
                            if c.len() == 2 {
                                Some(u16::from_be_bytes([c[0], c[1]]) as u8 as char)
                            } else {
                                None
                            }
                        })
                        .collect();
                    return Some(s);
                } else {
                    return Some(String::from_utf8_lossy(raw).to_string());
                }
            }
        }
    }
    None
}

/// Extract a single TTF from a TTC by building a standalone font file.
/// The sub-font header at `font_offset` contains a table directory with
/// offsets that are absolute within the TTC. We copy the header + directory
/// and then append all referenced table data, adjusting offsets accordingly.
fn extract_ttf_from_ttc(ttc_data: &[u8], font_offset: usize) -> std::io::Result<Vec<u8>> {
    use stet_fonts::truetype::{read_u16, read_u32};

    if font_offset + 12 > ttc_data.len() {
        return Err(std::io::Error::other("TTC font offset out of range"));
    }

    let num_tables = read_u16(ttc_data, font_offset + 4) as usize;
    let header_size = 12 + num_tables * 16;

    // Collect table info: (tag, ttc_offset, length)
    let mut tables = Vec::with_capacity(num_tables);
    for i in 0..num_tables {
        let entry = font_offset + 12 + i * 16;
        if entry + 16 > ttc_data.len() {
            break;
        }
        let tag = &ttc_data[entry..entry + 4];
        let offset = read_u32(ttc_data, entry + 8) as usize;
        let length = read_u32(ttc_data, entry + 12) as usize;
        tables.push((tag.to_vec(), offset, length));
    }

    // Build standalone TTF: header + directory + table data
    let mut result = Vec::with_capacity(
        header_size + tables.iter().map(|(_, _, l)| (l + 3) & !3).sum::<usize>(),
    );

    // Copy the 12-byte sfnt header
    result.extend_from_slice(&ttc_data[font_offset..font_offset + 12]);

    // First pass: compute new offsets (tables follow directory)
    let mut data_offset = header_size as u32;
    let mut new_offsets = Vec::with_capacity(num_tables);
    for (_, _, length) in &tables {
        new_offsets.push(data_offset);
        data_offset += ((*length as u32) + 3) & !3; // 4-byte aligned
    }

    // Write table directory with new offsets
    for (i, (tag, _, length)) in tables.iter().enumerate() {
        let entry = font_offset + 12 + i * 16;
        result.extend_from_slice(tag); // tag
        result.extend_from_slice(&ttc_data[entry + 4..entry + 8]); // checksum
        result.extend_from_slice(&new_offsets[i].to_be_bytes()); // new offset
        result.extend_from_slice(&(*length as u32).to_be_bytes()); // length
    }

    // Copy table data
    for (_, ttc_offset, length) in &tables {
        let end = (*ttc_offset + *length).min(ttc_data.len());
        if *ttc_offset < ttc_data.len() {
            result.extend_from_slice(&ttc_data[*ttc_offset..end]);
            // Pad to 4-byte alignment
            let pad = (4 - (length % 4)) % 4;
            result.extend(std::iter::repeat_n(0u8, pad));
        }
    }

    Ok(result)
}

/// Resolve a Type 3 font: glyphs defined as content streams.
fn resolve_type3(resolver: &Resolver, font_dict: &PdfDict) -> Result<PdfFont, PdfError> {
    let first_char = font_dict.get_int(b"FirstChar").unwrap_or(0) as usize;

    // Parse widths array (already in glyph space — Type 3 FontMatrix maps to text space).
    // /Widths may be an indirect reference — resolve before accessing.
    let mut widths = [0.0f64; 256];
    let widths_resolved = font_dict
        .get(b"Widths")
        .and_then(|obj| resolver.deref(obj).ok());
    if let Some(ref w_obj) = widths_resolved
        && let Some(w_arr) = w_obj.as_array()
    {
        for (i, obj) in w_arr.iter().enumerate() {
            let code = first_char + i;
            if code < 256 {
                // Width entries may be indirect references
                let val = if obj.as_f64().is_some() {
                    obj.as_f64().unwrap()
                } else if let Ok(resolved) = resolver.deref(obj) {
                    resolved.as_f64().unwrap_or(0.0)
                } else {
                    0.0
                };
                widths[code] = val;
            }
        }
    }

    // FontMatrix (typically something like [0.01 0 0 0.01 0 0] for 100-unit glyph space)
    let font_matrix = font_dict
        .get_array(b"FontMatrix")
        .map(|a| {
            let v: Vec<f64> = a.iter().filter_map(|o| o.as_f64()).collect();
            if v.len() >= 6 {
                Matrix::new(v[0], v[1], v[2], v[3], v[4], v[5])
            } else {
                Matrix::new(0.001, 0.0, 0.0, 0.001, 0.0, 0.0)
            }
        })
        .unwrap_or_else(|| Matrix::new(0.001, 0.0, 0.0, 0.001, 0.0, 0.0));

    let font_bbox = font_dict
        .get_array(b"FontBBox")
        .map(|a| {
            let v: Vec<f64> = a.iter().filter_map(|o| o.as_f64()).collect();
            if v.len() >= 4 {
                [v[0], v[1], v[2], v[3]]
            } else {
                [0.0, 0.0, 1.0, 1.0]
            }
        })
        .unwrap_or([0.0, 0.0, 1.0, 1.0]);

    // Resolve encoding: maps char codes → glyph names in CharProcs
    let (encoding, _, _, _) = resolve_encoding(font_dict, resolver)?;

    // Get CharProcs dict: maps glyph names → content streams
    // May be a direct dict or an indirect reference
    let char_procs_dict = if let Some(obj) = font_dict.get(b"CharProcs") {
        match resolver.deref(obj)? {
            PdfObj::Dict(d) => d,
            _ => return Err(PdfError::Other("Type3 CharProcs is not a dict".into())),
        }
    } else {
        return Err(PdfError::Other("Type3 font missing CharProcs".into()));
    };

    // Resources for interpreting CharProc streams
    let resources = if let Some(res_ref) = font_dict.get(b"Resources") {
        match resolver.deref(res_ref)? {
            PdfObj::Dict(d) => d,
            _ => PdfDict::new(),
        }
    } else {
        PdfDict::new()
    };

    // Pre-decode all CharProc streams: encoding[code] → stream bytes
    let mut char_procs = HashMap::new();
    for code in 0..256u16 {
        if let Some(glyph_name) = &encoding[code as usize]
            && let Some(proc_ref) = char_procs_dict.get(glyph_name.as_bytes())
            && let Ok(data) = resolver.stream_data_from_obj(proc_ref)
        {
            char_procs.insert(code as u8, data);
        }
    }
    Ok(PdfFont::Type3(Type3PdfFont {
        char_procs,
        resources,
        widths,
        font_matrix,
        font_bbox,
    }))
}

fn resolve_type1(
    resolver: &Resolver,
    descriptor: &Option<PdfDict>,
    encoding: [Option<String>; 256],
    widths: [f64; 256],
    has_explicit_encoding: bool,
    has_pdf_widths: bool,
    differences: &[(usize, String)],
    no_base_encoding: bool,
) -> Result<PdfFont, PdfError> {
    let desc = descriptor
        .as_ref()
        .ok_or(PdfError::Other("Type1 font missing FontDescriptor".into()))?;
    // Check FontFile first (traditional Type 1), then FontFile3 (CFF or Type1C)
    if let Some(ff3_ref) = desc.get(b"FontFile3") {
        // FontFile3 may contain CFF (Type1C) data — handle via CFF parser
        let ff3_obj = resolver.deref(ff3_ref)?;
        let ff3_dict = ff3_obj.as_dict();
        let subtype = ff3_dict.and_then(|d| d.get_name(b"Subtype")).unwrap_or(b"");
        if subtype == b"Type1C" || subtype == b"CIDFontType0C" || subtype == b"OpenType" {
            let raw_data = resolver.stream_data_from_obj(ff3_ref)?;
            // If data starts with "OTTO" it's an OpenType container — extract CFF table
            let font_data = if raw_data.starts_with(b"OTTO") {
                use stet_fonts::truetype::find_table;
                let (offset, length) = find_table(&raw_data, b"CFF ")
                    .ok_or(PdfError::Other("OpenType font has no CFF table".into()))?;
                raw_data[offset..offset + length].to_vec()
            } else {
                raw_data
            };
            let fonts = parse_cff(&font_data)
                .map_err(|e| PdfError::Other(format!("CFF parse error: {e}")))?;
            let font = fonts
                .into_iter()
                .next()
                .ok_or(PdfError::Other("CFF contains no fonts".into()))?;

            let fm = font.font_matrix;
            let font_matrix = Matrix::new(fm[0], fm[1], fm[2], fm[3], fm[4], fm[5]);

            return Ok(PdfFont::Cff(CffPdfFont {
                font,
                encoding,
                widths,
                font_matrix,
            }));
        }
    }

    let ff_ref = desc
        .get(b"FontFile")
        .or_else(|| desc.get(b"FontFile3"))
        .ok_or(PdfError::Other("Type1 font missing FontFile".into()))?;
    let font_data = resolver.stream_data_from_obj(ff_ref)?;

    // Strip PFB (Printer Font Binary) headers if present
    let font_data = strip_pfb(&font_data);

    let font =
        parse_type1(&font_data).map_err(|e| PdfError::Other(format!("Type1 parse error: {e}")))?;

    // PDF spec 9.6.6.1: encoding base depends on whether the font is embedded.
    // When the /Encoding dict has no /BaseEncoding, the base for embedded fonts
    // is the font's built-in encoding (not StandardEncoding). This matters for
    // expert fonts where e.g. code 97 = "Asmall", not "a".
    let encoding = if no_base_encoding && font.encoding.len() == 256 {
        // Encoding dict had no BaseEncoding. For embedded fonts,
        // the base is the font's built-in encoding, not StandardEncoding.
        let mut builtin: [Option<String>; 256] = std::array::from_fn(|_| None);
        for (i, name) in font.encoding.iter().enumerate() {
            if name != ".notdef" {
                builtin[i] = Some(name.clone());
            }
        }
        for (code, name) in differences {
            if *code < 256 {
                builtin[*code] = Some(name.clone());
            }
        }
        builtin
    } else if !has_explicit_encoding {
        let flags = desc.get_int(b"Flags").unwrap_or(0) as u32;
        let is_symbolic = flags & 4 != 0;
        if is_symbolic && font.encoding.len() == 256 {
            let mut builtin: [Option<String>; 256] = std::array::from_fn(|_| None);
            for (i, name) in font.encoding.iter().enumerate() {
                if name != ".notdef" {
                    builtin[i] = Some(name.clone());
                }
            }
            builtin
        } else {
            encoding
        }
    } else {
        encoding
    };

    // Check if the encoding's glyph names are completely incompatible with the
    // font's CharStrings (e.g. StandardEncoding "A","B" vs custom "G41","G42").
    // If so, enable fallback to the font's built-in encoding at glyph lookup.
    let builtin_fallback = {
        let flags = desc.get_int(b"Flags").unwrap_or(0) as u32;
        let is_sym = flags & 4 != 0;
        let builtin_useful =
            is_sym && font.encoding.len() == 256 && font.encoding.iter().any(|n| n != ".notdef");
        if builtin_useful {
            !encoding[32..127].iter().any(|slot| {
                slot.as_ref()
                    .is_some_and(|name| font.charstrings.contains_key(name.as_str()))
            })
        } else {
            false
        }
    };

    let fm = font.font_matrix;
    let font_matrix = Matrix::new(fm[0], fm[1], fm[2], fm[3], fm[4], fm[5]);

    // When the PDF has no /Widths array, derive widths from the Type 1 charstrings.
    let widths = if !has_pdf_widths {
        let mut derived = [0.0f64; 256];
        for code in 0..256usize {
            let glyph_name = encoding[code].as_deref().unwrap_or(".notdef");
            if glyph_name == ".notdef" {
                continue;
            }
            if let Some(charstring) = font.charstrings.get(glyph_name) {
                let cs_lookup =
                    |name: &str| -> Option<Vec<u8>> { font.charstrings.get(name).cloned() };
                if let Ok(result) = execute_charstring_mm(
                    charstring,
                    &font.subrs,
                    font.len_iv,
                    false,
                    Some(&cs_lookup),
                    font.weight_vector.as_deref(),
                ) {
                    derived[code] = result.width_x * fm[0];
                }
            }
        }
        derived
    } else {
        widths
    };

    let weight_vector = font.weight_vector.clone();
    Ok(PdfFont::Type1(Type1PdfFont {
        font,
        encoding,
        widths,
        font_matrix,
        weight_vector,
        builtin_fallback,
        per_char_width_scale: false,
    }))
}

/// Resolve a TrueType font from its FontDescriptor.
/// If the font data has table directory entries pointing past the data,
/// try re-decompressing with raw deflate (skipping the zlib header).
/// Some fonts have corrupt zlib headers (CINFO < 7) that cause truncation.
fn try_raw_deflate_if_truncated(resolver: &Resolver, ff_ref: &PdfObj, data: Vec<u8>) -> Vec<u8> {
    // Check if any table extends past the data
    if data.len() < 12 {
        return data;
    }
    let num_tables = u16::from_be_bytes([data[4], data[5]]) as usize;
    let mut max_end = 0usize;
    for i in 0..num_tables {
        let e = 12 + i * 16;
        if e + 16 > data.len() {
            break;
        }
        let off =
            u32::from_be_bytes([data[e + 8], data[e + 9], data[e + 10], data[e + 11]]) as usize;
        let len =
            u32::from_be_bytes([data[e + 12], data[e + 13], data[e + 14], data[e + 15]]) as usize;
        max_end = max_end.max(off.saturating_add(len));
    }
    if max_end <= data.len() {
        return data; // all tables fit, no truncation
    }
    // Tables extend past the data — try raw deflate on the stream
    let raw_bytes = match resolver.raw_stream_bytes(ff_ref) {
        Some(b) if b.len() > 2 => b,
        _ => return data,
    };
    // Only retry if the zlib header has CINFO < 7 (suspect window size)
    let cinfo = raw_bytes[0] >> 4;
    let cm = raw_bytes[0] & 0xF;
    if cm != 8 || cinfo >= 7 {
        return data;
    }
    // Decompress with raw deflate (skip 2-byte zlib header)
    let mut decoder = flate2::Decompress::new(false);
    let mut output = Vec::with_capacity(data.len() * 2);
    let mut buf = [0u8; 8192];
    let input = &raw_bytes[2..];
    let mut input_offset = 0;
    loop {
        let before_in = decoder.total_in() as usize;
        let before_out = decoder.total_out() as usize;
        let result = decoder.decompress(
            &input[input_offset..],
            &mut buf,
            flate2::FlushDecompress::None,
        );
        let consumed = decoder.total_in() as usize - before_in;
        let produced = decoder.total_out() as usize - before_out;
        input_offset += consumed;
        output.extend_from_slice(&buf[..produced]);
        match result {
            Ok(flate2::Status::StreamEnd) => break,
            Ok(_) => {
                if consumed == 0 && produced == 0 {
                    break;
                }
            }
            Err(_) => break,
        }
    }
    if output.len() <= data.len() {
        return data;
    }
    // Verify ALL tables fit in the raw output (reject if still truncated)
    let mut raw_max_end = 0usize;
    for i in 0..num_tables {
        let e = 12 + i * 16;
        if e + 16 > output.len() {
            return data;
        }
        let off = u32::from_be_bytes([output[e + 8], output[e + 9], output[e + 10], output[e + 11]])
            as usize;
        let len = u32::from_be_bytes([
            output[e + 12],
            output[e + 13],
            output[e + 14],
            output[e + 15],
        ]) as usize;
        raw_max_end = raw_max_end.max(off.saturating_add(len));
    }
    if raw_max_end > output.len() {
        return data; // raw output still truncated, don't use it
    }
    // Validate the head table has a plausible unitsPerEm (detects shifted data
    // where the head bytes are misaligned and read as zero)
    if stet_fonts::truetype::get_units_per_em(&output) == 0 {
        return data;
    }
    output
}

fn resolve_truetype(
    resolver: &Resolver,
    descriptor: &Option<PdfDict>,
    encoding: [Option<String>; 256],
    widths: [f64; 256],
    font_dict: &PdfDict,
) -> Result<PdfFont, PdfError> {
    let desc = descriptor.as_ref().ok_or(PdfError::Other(
        "TrueType font missing FontDescriptor".into(),
    ))?;
    let ff_ref = desc
        .get(b"FontFile2")
        .ok_or(PdfError::Other("TrueType font missing FontFile2".into()))?;
    let data = resolver.stream_data_from_obj(ff_ref)?;

    // Some fonts have corrupt zlib headers (CINFO < 7) that cause the zlib
    // decompressor to truncate. If key tables are out of bounds, try raw
    // deflate decompression which ignores the header.
    let data = try_raw_deflate_if_truncated(resolver, ff_ref, data);

    // Validate that glyph outline data is actually present
    use stet_fonts::truetype::find_table;
    let has_glyf = find_table(&data, b"glyf").is_some();
    let has_usable_glyx = if let Some((off, len)) = find_table(&data, b"glyx") {
        off + len <= data.len()
    } else {
        false
    };
    if !has_glyf && !has_usable_glyx {
        // Some PDFs store CFF/OpenType fonts as FontFile2 (malformed but common).
        // Detect and route to CFF parsing instead of failing.
        let is_otf = data.starts_with(b"OTTO");
        let is_cff = is_raw_cff(&data);
        if is_otf || is_cff {
            let has_explicit_encoding = font_dict.get(b"Encoding").is_some();
            let has_pdf_widths = font_dict.get(b"Widths").is_some();
            return build_cff_font(
                data,
                encoding,
                widths,
                has_explicit_encoding,
                has_pdf_widths,
                &[],
                false,
            );
        }
        return Err(PdfError::Other(
            "TrueType font has no usable glyph outline data".into(),
        ));
    }

    // Validate essential tables are within bounds. Truncated font data
    // (e.g. from corrupt zlib headers) may have table directory entries
    // pointing past the decompressed data.
    if let Some((off, _)) = find_table(&data, b"head") {
        if off + 54 > data.len() {
            return Err(PdfError::Other(
                "TrueType font head table is out of bounds (truncated data)".into(),
            ));
        }
    }

    let units_per_em = get_units_per_em(&data) as f64;

    // Reject fonts with degenerate unitsPerEm (< 16). These are dummy subsets
    // with placeholder rectangle "glyphs" that produce enormous shapes when
    // normalized. Fall through to the substitute font path instead.
    if units_per_em < 16.0 {
        return Err(PdfError::Other(
            "TrueType font has degenerate unitsPerEm (placeholder outlines)".into(),
        ));
    }

    let (cmap, cmap_is_unicode) = parse_cmap_with_info(&data);

    // Parse post table (GID → name) and invert to name → GID for fallback lookup
    let post_name_to_gid = stet_fonts::system_fonts::parse_post_table(&data)
        .map(|gid_to_name| {
            gid_to_name
                .into_iter()
                .map(|(gid, name)| (name, gid))
                .collect()
        })
        .unwrap_or_default();

    // Symbolic TrueType fonts without explicit /Encoding use identity mapping
    // (char_code = GID). The cmap is often misleading for re-encoded fonts
    // (e.g. Tamil glyphs at Latin cmap positions).
    let flags = desc.get_int(b"Flags").unwrap_or(0) as u32;
    let is_symbolic = flags & 4 != 0;
    let has_encoding = font_dict.get(b"Encoding").is_some();
    let identity_gid = is_symbolic && !has_encoding && cmap_is_unicode;
    let gid_hex = TrueTypePdfFont::detect_gid_hex(&encoding);

    Ok(PdfFont::TrueType(TrueTypePdfFont {
        data,
        encoding,
        widths,
        cmap,
        cmap_is_unicode,
        post_name_to_gid,
        units_per_em,
        to_unicode: if let Some(tu_obj) = font_dict.get(b"ToUnicode") {
            resolver
                .stream_data_from_obj(tu_obj)
                .map(|d| parse_to_unicode(&d))
                .unwrap_or_default()
        } else {
            HashMap::new()
        },
        identity_gid,
        gid_hex,
    }))
}

/// Resolve a CFF (Type1C) font from its FontDescriptor.
fn resolve_cff(
    resolver: &Resolver,
    descriptor: &Option<PdfDict>,
    encoding: [Option<String>; 256],
    widths: [f64; 256],
    has_explicit_encoding: bool,
    has_pdf_widths: bool,
    differences: &[(usize, String)],
    no_base_encoding: bool,
) -> Result<PdfFont, PdfError> {
    let desc = descriptor
        .as_ref()
        .ok_or(PdfError::Other("CFF font missing FontDescriptor".into()))?;
    let ff_ref = desc
        .get(b"FontFile3")
        .ok_or(PdfError::Other("CFF font missing FontFile3".into()))?;
    let raw_data = resolver.stream_data_from_obj(ff_ref)?;
    build_cff_font(
        raw_data,
        encoding,
        widths,
        has_explicit_encoding,
        has_pdf_widths,
        differences,
        no_base_encoding,
    )
}

/// Build a CFF font from raw font data (may be OpenType/CFF or raw CFF).
fn build_cff_font(
    raw_data: Vec<u8>,
    encoding: [Option<String>; 256],
    widths: [f64; 256],
    has_explicit_encoding: bool,
    has_pdf_widths: bool,
    differences: &[(usize, String)],
    no_base_encoding: bool,
) -> Result<PdfFont, PdfError> {
    // If data starts with "OTTO" it's an OpenType container — extract CFF table
    let font_data = if raw_data.starts_with(b"OTTO") {
        use stet_fonts::truetype::find_table;
        let (offset, length) = find_table(&raw_data, b"CFF ")
            .ok_or(PdfError::Other("OpenType font has no CFF table".into()))?;
        raw_data[offset..offset + length].to_vec()
    } else {
        raw_data
    };

    let fonts =
        parse_cff(&font_data).map_err(|e| PdfError::Other(format!("CFF parse error: {e}")))?;
    let font = fonts
        .into_iter()
        .next()
        .ok_or(PdfError::Other("CFF contains no fonts".into()))?;

    // PDF spec 9.6.6.1: encoding base depends on whether the font is embedded.
    // When the /Encoding dict has no /BaseEncoding, the base for embedded fonts
    // is the font's built-in encoding (not StandardEncoding).
    // Helper: build encoding from the CFF's built-in encoding table.
    // For codes where the CFF encoding maps to a valid GID, use that name.
    // For unmapped codes in fonts with Expert charset names (Asmall, etc.),
    // fill in from the Expert encoding table — handles buggy subset fonts that
    // claim Standard encoding but have Expert glyph names.
    let build_cff_encoding = |font: &stet_fonts::cff_parser::CffFont| -> [Option<String>; 256] {
        let mut enc: [Option<String>; 256] = std::array::from_fn(|_| None);
        let name_to_gid: std::collections::HashMap<&str, u16> = font
            .charset
            .iter()
            .enumerate()
            .map(|(gid, name)| (name.as_str(), gid as u16))
            .collect();
        #[allow(clippy::needless_range_loop)]
        for code in 0..256 {
            let gid = font.encoding[code] as usize;
            if gid > 0 && gid < font.charset.len() && font.charset[gid] != ".notdef" {
                enc[code] = Some(font.charset[gid].clone());
            }
        }
        // Fill gaps from Expert encoding for fonts with Expert glyph names.
        if name_to_gid.contains_key("Asmall") {
            for &(code, sid) in &stet_fonts::cff_parser::EXPERT_ENCODING_MAP {
                if enc[code as usize].is_none() {
                    let name = stet_fonts::cff_parser::get_sid_string(sid, &[]);
                    if let Some(&gid) = name_to_gid.get(name.as_str()) {
                        if gid > 0 {
                            enc[code as usize] = Some(font.charset[gid as usize].clone());
                        }
                    }
                }
            }
            // Map lowercase a-z to XYZsmall names for broken Expert subsets
            // where the CFF encoding doesn't cover all used codes.
            for code in b'a'..=b'z' {
                if enc[code as usize].is_none() {
                    let small_name = format!("{}small", (code - b'a' + b'A') as char);
                    if name_to_gid.contains_key(small_name.as_str()) {
                        enc[code as usize] = Some(small_name);
                    }
                }
            }
        }
        enc
    };

    let encoding = if no_base_encoding || !differences.is_empty() {
        // Encoding dict had no BaseEncoding — use CFF built-in
        // encoding as base, then apply Differences.
        let mut enc = build_cff_encoding(&font);
        for (code, name) in differences {
            if *code < 256 {
                enc[*code] = Some(name.clone());
            }
        }
        enc
    } else if !has_explicit_encoding {
        // No /Encoding at all — use CFF built-in encoding directly.
        build_cff_encoding(&font)
    } else {
        encoding
    };

    let fm = font.font_matrix;
    let font_matrix = Matrix::new(fm[0], fm[1], fm[2], fm[3], fm[4], fm[5]);

    // When the PDF has no /Widths array, derive widths from the CFF charstrings.
    let widths = if !has_pdf_widths {
        use stet_fonts::type2_charstring::execute_type2_charstring;
        let mut derived = [0.0f64; 256];
        for code in 0..256usize {
            let glyph_name = encoding[code].as_deref().unwrap_or(".notdef");
            let gid = font
                .charset
                .iter()
                .position(|name| name == glyph_name)
                .unwrap_or(0);
            if gid > 0 && gid < font.char_strings.len() {
                if let Ok(result) = execute_type2_charstring(
                    &font.char_strings[gid],
                    &font.local_subrs,
                    &font.global_subrs,
                    font.default_width_x,
                    font.nominal_width_x,
                    true, // width_only
                ) {
                    derived[code] = result.width_x * fm[0];
                }
            }
        }
        derived
    } else {
        widths
    };

    Ok(PdfFont::Cff(CffPdfFont {
        font,
        encoding,
        widths,
        font_matrix,
    }))
}

/// Resolve a Type 0 composite font (CIDFontType2 descendant with TrueType outlines).
fn resolve_type0(resolver: &Resolver, font_dict: &PdfDict) -> Result<PdfFont, PdfError> {
    // Check if encoding is UCS2-based (character codes are Unicode, not CIDs).
    let encoding_obj = font_dict.get(b"Encoding");
    let encoding_name = font_dict.get_name(b"Encoding").unwrap_or(b"");
    let ucs2_encoding = encoding_name.windows(4).any(|w| w == b"UCS2");

    // Parse the encoding CMap's codespace ranges to determine byte widths,
    // and the code-to-CID mapping for non-identity encodings.
    // The encoding can be:
    //   - a stream containing a custom CMap
    //   - a name like "Identity-H" (identity mapping, 2-byte codes)
    //   - a predefined CMap name like "GBK-EUC-H" (load from system)
    let (code_lengths, code_to_cid, mut wmode) = if let Some(enc_obj) = encoding_obj {
        if let Ok(cmap_data) = resolver.stream_data_from_obj(enc_obj) {
            // Embedded CMap stream
            let cmap = super::cmap::CMap::parse_with_loader(
                &cmap_data,
                Some(&|name| load_predefined_cmap(name)),
            );
            (cmap.code_lengths, cmap.code_to_cid, cmap.wmode)
        } else if !encoding_name.is_empty() && !encoding_name.starts_with(b"Identity") {
            // Predefined CMap name (e.g. GBK-EUC-H) — load from system
            if let Some(cmap_data) = load_predefined_cmap(encoding_name) {
                let cmap = super::cmap::CMap::parse_with_loader(
                    &cmap_data,
                    Some(&|name| load_predefined_cmap(name)),
                );
                (cmap.code_lengths, cmap.code_to_cid, cmap.wmode)
            } else {
                eprintln!(
                    "warning: predefined CMap '{}' not found; \
                     set STET_CMAP_DIR or install poppler-data for CJK support",
                    String::from_utf8_lossy(encoding_name)
                );
                ([2u8; 256], HashMap::new(), 0)
            }
        } else {
            ([2u8; 256], HashMap::new(), 0) // Identity-H/V or fallback
        }
    } else {
        ([2u8; 256], HashMap::new(), 0)
    };
    // Encoding name suffix overrides CMap WMode: -V = vertical, -H = horizontal
    if encoding_name.ends_with(b"-V") {
        wmode = 1;
    } else if encoding_name.ends_with(b"-H") {
        wmode = 0;
    }

    // Get DescendantFonts array (must have exactly one entry).
    // May be a direct array or an indirect reference to one.
    let descendants_obj = font_dict
        .get(b"DescendantFonts")
        .ok_or(PdfError::Other("Type0 font missing DescendantFonts".into()))?;
    let descendants_resolved = resolver.deref(descendants_obj)?;
    let descendants = descendants_resolved
        .as_array()
        .ok_or(PdfError::Other("DescendantFonts is not an array".into()))?;
    let cid_font_ref = descendants
        .first()
        .ok_or(PdfError::Other("DescendantFonts is empty".into()))?;
    let cid_font_obj = resolver.deref(cid_font_ref)?;
    let cid_font_dict = cid_font_obj
        .as_dict()
        .ok_or(PdfError::Other("CIDFont is not a dict".into()))?;

    let cid_subtype = cid_font_dict.get_name(b"Subtype").unwrap_or(b"");

    // Get FontDescriptor from the CIDFont
    let descriptor = get_font_descriptor(cid_font_dict, resolver)?;
    let desc = descriptor
        .as_ref()
        .ok_or(PdfError::Other("CIDFont missing FontDescriptor".into()))?;

    // Parse /DW (default width) — may be int or real
    let default_width = cid_font_dict.get_f64(b"DW").unwrap_or(1000.0) / 1000.0;

    // Parse /DW2 (default vertical metrics: [v_y w1])
    // Default: [880, -1000] per PDF spec Table 117
    let dw2 = cid_font_dict
        .get_array(b"DW2")
        .and_then(|arr| {
            let v: Vec<f64> = arr.iter().filter_map(|o| o.as_f64()).collect();
            if v.len() >= 2 {
                Some([v[0], v[1]])
            } else {
                None
            }
        })
        .unwrap_or([880.0, -1000.0]);

    // Parse /W array (CID-specific widths)
    let cid_widths = parse_cid_widths(cid_font_dict, resolver);

    // Parse /W2 array (per-CID vertical metrics)
    let w2 = parse_cid_w2(cid_font_dict, resolver);

    // When a UCS2-based CMap (e.g. UniJIS-UCS2-H) couldn't be loaded from
    // disk, build a basic Latin fallback mapping. All Adobe CID collections
    // (Japan1, GB1, CNS1, Korea1) map Unicode basic Latin to:
    //   CID 1 = U+0020 (space), CID 2..95 = U+0021..U+007E
    // This handles the common case of CJK-font PDFs containing English text
    // when CMap resource files aren't installed.
    let code_to_cid = if code_to_cid.is_empty()
        && code_lengths[0] == 2
        && encoding_name.windows(4).any(|w| w == b"UCS2")
    {
        let mut map = HashMap::new();
        for unicode in 0x0020u32..=0x007Eu32 {
            let cid = unicode - 0x001F;
            map.insert(unicode, cid);
        }
        map
    } else {
        code_to_cid
    };

    // Parse /ToUnicode CMap from the parent Type 0 font dict
    let to_unicode = if let Some(tu_obj) = font_dict.get(b"ToUnicode") {
        match resolver.stream_data_from_obj(tu_obj) {
            Ok(data) => parse_to_unicode(&data),
            Err(_) => HashMap::new(),
        }
    } else {
        HashMap::new()
    };

    // Extract CIDSystemInfo /Ordering for CID→Unicode fallback lookup.
    // /Ordering is a string (parenthesized), not a name.
    let ordering = {
        let si_dict = cid_font_dict
            .get_dict(b"CIDSystemInfo")
            .cloned()
            .or_else(|| {
                cid_font_dict
                    .get(b"CIDSystemInfo")
                    .and_then(|obj| resolver.deref(obj).ok())
                    .and_then(|obj| obj.as_dict().cloned())
            });
        si_dict
            .and_then(|d| {
                d.get(b"Ordering").and_then(|v| match v {
                    PdfObj::Str(s) => Some(s.clone()),
                    PdfObj::Name(n) => Some(n.clone()),
                    _ => None,
                })
            })
            .unwrap_or_default()
    };

    match cid_subtype {
        b"CIDFontType2" => {
            let mut substituted;
            let mut data = if let Some(ff_ref) = desc
                .get(b"FontFile2")
                // Some PDFs store TrueType data under /FontFile instead
                // of the correct /FontFile2 — accept it as a fallback.
                .or_else(|| {
                    desc.get(b"FontFile").filter(|obj| {
                        resolver
                            .stream_data_from_obj(obj)
                            .ok()
                            .is_some_and(|d| d.len() > 4 && d[..4] == [0, 1, 0, 0])
                    })
                })
                // PDF/X-4 and others embed CIDFontType2 outlines via
                // /FontFile3 with /Subtype /OpenType. The wrapped sfnt may
                // be TrueType-flavored (glyf/loca) or CFF-flavored (OTTO);
                // downstream OTTO/raw-CFF detection routes either correctly.
                .or_else(|| {
                    desc.get(b"FontFile3").filter(|obj| {
                        resolver.stream_data_from_obj(obj).ok().is_some_and(|d| {
                            d.len() > 4
                                && (d[..4] == [0, 1, 0, 0]
                                    || &d[..4] == b"true"
                                    || &d[..4] == b"OTTO")
                        })
                    })
                }) {
                substituted = false;
                let mut font_data = resolver.stream_data_from_obj(ff_ref)?;
                sanitize_index_to_loc_format(&mut font_data);
                // Some PDFs store CFF fonts as FontFile2 instead of FontFile3.
                // Detect OpenType/CFF (OTTO magic) or raw CFF and route accordingly.
                let is_otf_cff = font_data.len() > 4 && &font_data[0..4] == b"OTTO";
                let is_raw = is_raw_cff(&font_data);
                if is_otf_cff || is_raw {
                    // Parse CIDToGIDMap from the PDF
                    let cid_to_gid_map = if let Some(map_obj) = cid_font_dict.get(b"CIDToGIDMap") {
                        if cid_font_dict.get_name(b"CIDToGIDMap") != Some(b"Identity") {
                            resolver.stream_data_from_obj(map_obj).ok().map(|d| {
                                d.chunks_exact(2)
                                    .map(|p| u16::from_be_bytes([p[0], p[1]]))
                                    .collect()
                            })
                        } else {
                            None
                        }
                    } else {
                        None
                    };
                    // For CID-keyed CFF fonts, the CFF handles CID→charstring
                    // mapping internally. The PDF's CIDToGIDMap is a sparse subset
                    // artifact that maps most CIDs to GID 0 — ignore it.
                    // For non-CID CFF fonts, the CIDToGIDMap provides the actual
                    // CID→GID mapping and must be used.
                    let is_cid_keyed = {
                        use stet_fonts::truetype::find_table;
                        let cff_range = if is_otf_cff {
                            find_table(&font_data, b"CFF ")
                        } else {
                            Some((0, font_data.len()))
                        };
                        cff_range
                            .and_then(|(off, len)| parse_cff(&font_data[off..off + len]).ok())
                            .and_then(|fonts| fonts.into_iter().next())
                            .is_some_and(|f| f.is_cid)
                    };
                    let (cid_to_gid_map, identity) = if is_cid_keyed {
                        (None, true) // CFF handles CID mapping
                    } else {
                        let id = cid_to_gid_map.is_none();
                        (cid_to_gid_map, id)
                    };
                    if is_otf_cff {
                        return create_cid_cff_from_otf(
                            &font_data,
                            default_width,
                            cid_widths,
                            &ordering,
                            cid_to_gid_map,
                            identity,
                            code_lengths,
                            code_to_cid.clone(),
                            wmode,
                            dw2,
                            w2.clone(),
                        );
                    } else {
                        return create_cid_cff_from_raw(
                            &font_data,
                            default_width,
                            cid_widths,
                            &ordering,
                            cid_to_gid_map,
                            identity,
                            code_lengths,
                            code_to_cid.clone(),
                            wmode,
                            dw2,
                            w2.clone(),
                        );
                    }
                }
                font_data
            } else {
                // Font not embedded — try system font lookup
                substituted = true;
                let base_font = cid_font_dict
                    .get_name(b"BaseFont")
                    .map(|n| {
                        let s = String::from_utf8_lossy(n);
                        if s.len() > 7 && s.as_bytes().get(6) == Some(&b'+') {
                            s[7..].to_string()
                        } else {
                            s.to_string()
                        }
                    })
                    .unwrap_or_default();
                let sys_data = load_system_truetype_font(&base_font)
                    .or_else(|_| load_cjk_fallback_font(&ordering, &base_font))?;
                // If the system font is OpenType/CFF, use CFF rendering path
                if sys_data.len() > 4 && &sys_data[0..4] == b"OTTO" {
                    return create_cid_cff_from_otf(
                        &sys_data,
                        default_width,
                        cid_widths,
                        &ordering,
                        None,
                        false, // substituted: use cmap, not identity
                        code_lengths,
                        code_to_cid.clone(),
                        wmode,
                        dw2,
                        w2.clone(),
                    );
                }
                sys_data
            };

            // Detect corrupted font data: check whether ANY CID in the /W
            // table produces a valid glyph outline.  If none do, the font data
            // is likely damaged (e.g. from a broken/truncated zlib stream) and
            // we should fall back to the system font.
            // Only check when identity CID→GID is in effect (no explicit
            // CIDToGIDMap stream), since we test CIDs directly as GIDs.
            let has_cid_to_gid_map = cid_font_dict
                .get(b"CIDToGIDMap")
                .is_some_and(|v| v.as_name().is_none_or(|n| n != b"Identity"));
            if !substituted && !cid_widths.is_empty() && !has_cid_to_gid_map {
                let upm_f = get_units_per_em(&data) as f64;
                let any_glyph = cid_widths
                    .keys()
                    .any(|&cid| skrifa_glyph_path(&data, cid, upm_f).is_some());
                if !any_glyph {
                    let base_font = cid_font_dict
                        .get_name(b"BaseFont")
                        .map(|n| {
                            let s = String::from_utf8_lossy(n);
                            if s.len() > 7 && s.as_bytes().get(6) == Some(&b'+') {
                                s[7..].to_string()
                            } else {
                                s.to_string()
                            }
                        })
                        .unwrap_or_default();
                    if let Ok(sys_data) = load_system_truetype_font(&base_font) {
                        data = sys_data;
                        substituted = true;
                    }
                }
            }
            let units_per_em = get_units_per_em(&data) as f64;
            let cmap = parse_cmap(&data);

            // Parse CIDToGIDMap: either /Identity name or a stream of big-endian u16 pairs
            let (identity_cid_to_gid, cid_to_gid_map) =
                if let Some(name) = cid_font_dict.get_name(b"CIDToGIDMap") {
                    (name == b"Identity", None)
                } else if let Some(map_obj) = cid_font_dict.get(b"CIDToGIDMap") {
                    match resolver.stream_data_from_obj(map_obj) {
                        Ok(stream_data) => {
                            let mut gid_map = Vec::with_capacity(stream_data.len() / 2);
                            for pair in stream_data.chunks_exact(2) {
                                gid_map.push(u16::from_be_bytes([pair[0], pair[1]]));
                            }
                            (false, Some(gid_map))
                        }
                        Err(_) => (true, None), // fallback to identity
                    }
                } else {
                    (true, None) // no CIDToGIDMap → default to identity
                };

            // For substituted fonts, always discard CIDToGIDMap streams.
            // The map encodes GID ordering specific to the original font and
            // is never valid for a different font — even metric-compatible
            // pairs (e.g. TimesNewRoman ↔ LiberationSerif) share ASCII GIDs
            // but diverge for extended characters (ě, í, – etc.).
            let cid_to_gid_map = if substituted && cid_to_gid_map.is_some() {
                None
            } else {
                cid_to_gid_map
            };
            // Don't promote to identity when we discarded an incompatible
            // CIDToGIDMap — the CIDs are Unicode values, not GIDs, so the
            // gid_to_unicode enrichment below must NOT run.

            // For non-embedded fonts with Identity CIDToGIDMap, the CID values
            // are GIDs from the original font. A substitute font has different
            // glyph ordering, so CID-as-GID produces garbled text. Use hardcoded
            // GID-to-Unicode tables (same approach as PDF.js) to map known fonts'
            // GIDs to Unicode, enabling correct rendering with any substitute.
            let to_unicode = if substituted
                && identity_cid_to_gid
                && to_unicode.is_empty()
                && encoding_name.starts_with(b"Identity")
            {
                let base_name = cid_font_dict.get_name(b"BaseFont").unwrap_or(b"");
                let name_str = String::from_utf8_lossy(base_name);
                // Strip subset prefix (e.g. "ABCDEF+Calibri,Bold" → "Calibri,Bold")
                let clean = if name_str.len() > 7 && name_str.as_bytes().get(6) == Some(&b'+') {
                    &name_str[7..]
                } else {
                    &name_str
                };
                // Extract family name before style suffix, stripping
                // PostScript suffixes (MT, PS, PSMT) that don't appear
                // in the GID map keys.
                let mut family = clean
                    .split(&[',', '-'][..])
                    .next()
                    .unwrap_or(clean)
                    .to_ascii_lowercase();
                for suffix in &["psmt", "ps", "mt"] {
                    if family.len() > suffix.len() && family.ends_with(suffix) {
                        family.truncate(family.len() - suffix.len());
                        break;
                    }
                }
                super::gid_maps::get_gid_to_unicode_map(&family).unwrap_or(to_unicode)
            } else {
                to_unicode
            };

            Ok(PdfFont::CidTrueType(CidTrueTypePdfFont {
                data,
                default_width,
                cid_widths,
                cmap,
                units_per_em,
                identity_cid_to_gid,
                substituted,
                cid_to_gid_map,
                to_unicode,
                ordering: ordering.clone(),
                ucs2_encoding,
                code_lengths,
                code_to_cid: code_to_cid.clone(),
                wmode,
                dw2,
                w2: w2.clone(),
            }))
        }
        b"CIDFontType0" => {
            // CFF-based CID font: FontFile3 with /Subtype /CIDFontType0C
            // Some PDFs use /FontFile instead of /FontFile3 — accept both.
            if let Some(ff_ref) = desc.get(b"FontFile3").or_else(|| desc.get(b"FontFile")) {
                let font_data = resolver.stream_data_from_obj(ff_ref)?;
                // Some PDFs mislabel TrueType data as CIDFontType0C. Detect the
                // TrueType magic (\x00\x01\x00\x00) and route to TrueType path.
                let is_truetype = font_data.len() > 4 && &font_data[0..4] == b"\x00\x01\x00\x00";
                if is_truetype {
                    let mut font_data = font_data;
                    sanitize_index_to_loc_format(&mut font_data);
                    let units_per_em = get_units_per_em(&font_data) as f64;
                    let cmap = parse_cmap(&font_data);
                    let (identity_cid_to_gid, cid_to_gid_map) =
                        if let Some(name) = cid_font_dict.get_name(b"CIDToGIDMap") {
                            (name == b"Identity", None)
                        } else {
                            (true, None)
                        };
                    return Ok(PdfFont::CidTrueType(CidTrueTypePdfFont {
                        data: font_data,
                        default_width,
                        cid_widths,
                        cmap,
                        units_per_em,
                        identity_cid_to_gid,
                        substituted: false,
                        cid_to_gid_map,
                        to_unicode,
                        ordering: ordering.clone(),
                        ucs2_encoding,
                        code_lengths,
                        code_to_cid: code_to_cid.clone(),
                        wmode,
                        dw2,
                        w2: w2.clone(),
                    }));
                }
                // FontFile3 may be raw CFF or OpenType/CFF (OTTO wrapper)
                if font_data.len() > 4 && &font_data[0..4] == b"OTTO" {
                    // Parse CIDToGIDMap for OpenType-wrapped CFF
                    let pdf_cid_to_gid = if let Some(map_obj) = cid_font_dict.get(b"CIDToGIDMap") {
                        match resolver.stream_data_from_obj(map_obj) {
                            Ok(stream_data) => {
                                let mut gid_map = Vec::with_capacity(stream_data.len() / 2);
                                for pair in stream_data.chunks_exact(2) {
                                    gid_map.push(u16::from_be_bytes([pair[0], pair[1]]));
                                }
                                Some(gid_map)
                            }
                            Err(_) => None,
                        }
                    } else {
                        None
                    };
                    // For non-CID CFF fonts used as CIDFontType0, the CID IS the
                    // charstring index (identity mapping). For true CID-keyed CFF fonts,
                    // the CFF charset provides the CID→GID mapping, or the OTF cmap is used.
                    let cff_is_cid = is_cff_cid_keyed(&font_data);
                    return create_cid_cff_from_otf(
                        &font_data,
                        default_width,
                        cid_widths,
                        &ordering,
                        pdf_cid_to_gid,
                        !cff_is_cid,
                        code_lengths,
                        code_to_cid.clone(),
                        wmode,
                        dw2,
                        w2.clone(),
                    );
                }
                // PostScript CIDFont programs: "%!PS-Adobe-3.0 Resource-CIDFont"
                // These contain binary charstring data after StartData.
                if font_data.starts_with(b"%!")
                    && font_data.windows(16).any(|w| w == b"Resource-CIDFont")
                {
                    return create_cid_from_ps_cidfont(
                        &font_data,
                        default_width,
                        cid_widths,
                        code_lengths,
                        code_to_cid.clone(),
                        wmode,
                        dw2,
                        w2.clone(),
                    );
                }
                // Detect Type 1 font data (ASCII "%!" or PFB 0x80) mislabeled
                // as CIDFontType0.  Parse as Type 1, pre-compute glyph paths
                // for each CID using ToUnicode → AGL → charstrings.
                let is_type1 = font_data.starts_with(b"%!") || font_data.first() == Some(&0x80);
                if is_type1 {
                    return create_cid_from_type1(
                        &font_data,
                        default_width,
                        cid_widths,
                        &to_unicode,
                        code_lengths,
                        code_to_cid.clone(),
                        wmode,
                        dw2,
                        w2.clone(),
                    );
                }
                let fonts = parse_cff(&font_data)
                    .map_err(|e| PdfError::Other(format!("CFF parse error: {e}")))?;
                let font = fonts
                    .into_iter()
                    .next()
                    .ok_or(PdfError::Other("CFF contains no fonts".into()))?;
                // Detect tiny CFF subsets for CJK fonts. Some PDFs embed a
                // minimal "ghost" CFF (3-4 glyphs) to satisfy spec requirements
                // while expecting the viewer to use the system CJK font (which
                // has matching GID ordering). Only fall through for CJK fonts
                // where the system substitute has compatible glyph indices.
                //
                // Gate this on the Adobe CID registry from CIDSystemInfo
                // /Ordering, *not* on substring matches against the BaseFont
                // name. The 2-letter substrings the old heuristic tested ("sc",
                // "cn", "jp", "kr", "tc", "hk") false-positive on common Latin
                // font names like "BentonSansCond" → "sc", causing the embedded
                // CFF to be discarded and replaced with NotoSansCJK whose GIDs
                // don't match — producing garbled text.
                let cs_count = font.char_strings.len();
                let is_adobe_cjk_registry = matches!(
                    ordering.as_slice(),
                    b"GB1" | b"CNS1" | b"Japan1" | b"Japan2" | b"Korea1" | b"KR"
                );
                if cs_count > 0 && cid_widths.len() > cs_count * 4 && is_adobe_cjk_registry {
                    // Drop the parsed CFF and fall through to the system font path.
                } else {
                    let fm = font.font_matrix;
                    let font_matrix = Matrix::new(fm[0], fm[1], fm[2], fm[3], fm[4], fm[5]);
                    return Ok(PdfFont::CidCff(CidCffPdfFont {
                        font,
                        default_width,
                        cid_widths,
                        font_matrix,
                        cmap: None,
                        pdf_cid_to_gid: None,
                        identity_cid_to_gid: false,
                        ordering: ordering.clone(),
                        code_lengths,
                        code_to_cid: code_to_cid.clone(),
                        wmode,
                        dw2,
                        w2: w2.clone(),
                        type1_paths: None,
                    }));
                }
            }
            // Not embedded or tiny subset — substitute with a system font
            {
                let base_font = cid_font_dict
                    .get_name(b"BaseFont")
                    .map(|n| String::from_utf8_lossy(n).to_string())
                    .unwrap_or_default();
                let sys_data = if ucs2_encoding {
                    // UCS2-encoded CID fonts: use a substitute TrueType font so
                    // the text stays on the composite CID rendering path (correct
                    // code_lengths and CID width advancement). Without this, the
                    // simple fallback font treats 2-byte UCS-2 codes as individual
                    // bytes, producing doubled character spacing.
                    // Try CJK fallback before Latin fallback — UCS2-encoded CJK
                    // fonts (Adobe-Japan1 etc.) need a font with CJK glyphs.
                    load_system_truetype_font(&base_font)
                        .or_else(|_| load_cjk_fallback_font(&ordering, &base_font))
                        .or_else(|_| load_system_truetype_font("DejaVuSans"))
                        .or_else(|_| load_system_truetype_font("LiberationSans"))
                        .or_else(|_| load_system_truetype_font("NimbusSans"))?
                } else {
                    load_system_truetype_font(&base_font)
                        .or_else(|_| load_cjk_fallback_font(&ordering, &base_font))?
                };
                // For Identity ordering, CIDs are GIDs from the original font.
                // When the substitute is the same font family, identity mapping
                // gives correct glyphs. For non-Identity orderings, the cmap
                // path (CID→Unicode→GID) is used instead.
                let identity = ordering == b"Identity";
                // If the system font is OpenType/CFF (or a TTC containing
                // OpenType/CFF sub-fonts), use the CFF rendering path.
                // find_table() handles both plain OTF and TTC files.
                let is_otto = sys_data.len() > 4 && &sys_data[0..4] == b"OTTO";
                let is_ttc_cff = sys_data.len() > 16 && &sys_data[0..4] == b"ttcf" && {
                    let off = u32::from_be_bytes([
                        sys_data[12],
                        sys_data[13],
                        sys_data[14],
                        sys_data[15],
                    ]) as usize;
                    off + 4 <= sys_data.len() && &sys_data[off..off + 4] == b"OTTO"
                };
                if is_otto || is_ttc_cff {
                    return create_cid_cff_from_otf(
                        &sys_data,
                        default_width,
                        cid_widths,
                        &ordering,
                        None,
                        identity,
                        code_lengths,
                        code_to_cid.clone(),
                        wmode,
                        dw2,
                        w2.clone(),
                    );
                }
                let data = sys_data;
                let units_per_em = get_units_per_em(&data) as f64;
                let cmap = parse_cmap(&data);
                Ok(PdfFont::CidTrueType(CidTrueTypePdfFont {
                    data,
                    default_width,
                    cid_widths,
                    cmap,
                    units_per_em,
                    identity_cid_to_gid: false,
                    substituted: true,
                    cid_to_gid_map: None,
                    to_unicode,
                    ordering: ordering.clone(),
                    ucs2_encoding,
                    code_lengths,
                    code_to_cid: code_to_cid.clone(),
                    wmode,
                    dw2,
                    w2,
                }))
            }
        }
        _ => Err(PdfError::Other(format!(
            "Unsupported CIDFont subtype: {}",
            String::from_utf8_lossy(cid_subtype)
        ))),
    }
}

/// Parse /W array from CIDFont dict into CID → width map.
///
/// Format: `[ cid_first [w1 w2 ...] cid_first cid_last w ... ]`
/// Extract `<hex>` tokens from a string, returning raw hex strings.
fn extract_hex_tokens(s: &str) -> Vec<&str> {
    let mut tokens = Vec::new();
    let mut rest = s;
    while let Some(start) = rest.find('<') {
        rest = &rest[start + 1..];
        if let Some(end) = rest.find('>') {
            let hex = rest[..end].trim();
            if !hex.is_empty() {
                tokens.push(hex);
            }
            rest = &rest[end + 1..];
        } else {
            break;
        }
    }
    tokens
}

/// Parse a hex string as a Unicode codepoint.
/// For multi-byte destinations (>4 hex digits), extract just the first codepoint (first 4 digits).
fn hex_to_unicode(hex: &str) -> Option<u32> {
    if hex.len() <= 4 {
        u32::from_str_radix(hex, 16).ok()
    } else {
        // Multi-byte: two or more 16-bit codepoints packed together.
        // Check for common ligature sequences and map to Unicode ligature codepoints.
        match hex {
            "00660066" => Some(0xFB00),     // ff
            "00660069" => Some(0xFB01),     // fi
            "0066006C" => Some(0xFB02),     // fl
            "006600660069" => Some(0xFB03), // ffi
            "00660066006C" => Some(0xFB04), // ffl
            "017F0074" => Some(0xFB05),     // ſt (long s + t)
            "00730074" => Some(0xFB06),     // st
            _ => {
                // Unknown sequence — use first 16-bit codepoint
                u32::from_str_radix(&hex[..hex.len().min(4)], 16).ok()
            }
        }
    }
}

/// Parse a ToUnicode CMap stream into a CID → Unicode mapping.
///
/// Handles `beginbfchar` and `beginbfrange` sections with hex-encoded values.
/// Multi-byte destination values (ligatures etc.) are mapped to their first codepoint.
fn parse_to_unicode(data: &[u8]) -> HashMap<u16, u32> {
    let mut map = HashMap::new();
    let text = String::from_utf8_lossy(data);

    // Parse bfchar entries: <src_cid> <dst_unicode>
    // Process line-by-line to avoid pairing issues with multi-byte destinations
    let mut in_bfchar = false;
    let mut in_bfrange = false;
    let mut range_tokens: Vec<&str> = Vec::new();

    for line in text.lines() {
        let trimmed = line.trim();
        if trimmed.ends_with("beginbfchar") {
            in_bfchar = true;
            continue;
        }
        if trimmed == "endbfchar" {
            in_bfchar = false;
            continue;
        }
        if trimmed.ends_with("beginbfrange") {
            in_bfrange = true;
            range_tokens.clear();
            continue;
        }
        if trimmed == "endbfrange" {
            in_bfrange = false;
            range_tokens.clear();
            continue;
        }

        if in_bfchar {
            let tokens = extract_hex_tokens(trimmed);
            if tokens.len() >= 2
                && let Ok(cid) = u32::from_str_radix(tokens[0], 16)
                && let Some(unicode) = hex_to_unicode(tokens[1])
            {
                map.insert(cid as u16, unicode);
            }
        }

        if in_bfrange {
            let line_tokens = extract_hex_tokens(trimmed);
            // Check for array syntax: <start> <end> [<u1> <u2> ...]
            if trimmed.contains('[') {
                // Collect start/end from previous tokens or this line
                let all_before_bracket: Vec<&str> = {
                    let before = trimmed.split('[').next().unwrap_or("");
                    extract_hex_tokens(before)
                };
                let in_bracket = {
                    let after_open = trimmed.split('[').nth(1).unwrap_or("");
                    let before_close = after_open.split(']').next().unwrap_or(after_open);
                    extract_hex_tokens(before_close)
                };
                if all_before_bracket.len() >= 2
                    && let (Some(start), Some(end)) = (
                        u32::from_str_radix(all_before_bracket[0], 16).ok(),
                        u32::from_str_radix(all_before_bracket[1], 16).ok(),
                    )
                {
                    for (j, cid) in (start..=end).enumerate() {
                        if j < in_bracket.len()
                            && let Some(u) = hex_to_unicode(in_bracket[j])
                        {
                            map.insert(cid as u16, u);
                        }
                    }
                }
            } else if line_tokens.len() >= 3 {
                // <start> <end> <dst_start>
                if let (Some(start), Some(end), Some(mut dst)) = (
                    u32::from_str_radix(line_tokens[0], 16).ok(),
                    u32::from_str_radix(line_tokens[1], 16).ok(),
                    hex_to_unicode(line_tokens[2]),
                ) {
                    for cid in start..=end {
                        map.insert(cid as u16, dst);
                        dst += 1;
                    }
                }
            }
        }
    }

    map
}

fn parse_cid_widths(cid_font_dict: &PdfDict, resolver: &Resolver) -> HashMap<u16, f64> {
    let mut widths = HashMap::new();
    // /W may be an indirect reference — resolve it before accessing as array
    let w_obj = match cid_font_dict.get(b"W") {
        Some(obj) => match resolver.deref(obj) {
            Ok(resolved) => resolved,
            Err(_) => return widths,
        },
        None => return widths,
    };
    let w_arr = match w_obj.as_array() {
        Some(arr) => arr,
        None => return widths,
    };
    let mut i = 0;
    while i < w_arr.len() {
        let first_cid = match &w_arr[i] {
            PdfObj::Int(n) => *n as u16,
            _ => break,
        };
        i += 1;
        if i >= w_arr.len() {
            break;
        }
        // Next element: array (individual widths) or int (range end)
        let next = resolver.deref(&w_arr[i]).unwrap_or(w_arr[i].clone());
        match &next {
            PdfObj::Array(arr) => {
                // [ cid_first [w1 w2 w3 ...] ] — consecutive CID widths
                for (j, w_obj) in arr.iter().enumerate() {
                    // Width entries may be indirect references
                    let w_val = w_obj
                        .as_f64()
                        .or_else(|| resolver.deref(w_obj).ok().and_then(|r| r.as_f64()))
                        .unwrap_or(0.0);
                    widths.insert(first_cid + j as u16, w_val / 1000.0);
                }
                i += 1;
            }
            _ => {
                // [ cid_first cid_last w ] — range with uniform width
                let last_cid = match &next {
                    PdfObj::Int(n) => *n as u16,
                    _ => first_cid,
                };
                i += 1;
                let w = if i < w_arr.len() {
                    let obj = &w_arr[i];
                    obj.as_f64()
                        .or_else(|| resolver.deref(obj).ok().and_then(|r| r.as_f64()))
                        .unwrap_or(0.0)
                        / 1000.0
                } else {
                    0.0
                };
                i += 1;
                for cid in first_cid..=last_cid {
                    widths.insert(cid, w);
                }
            }
        }
    }
    widths
}

/// Parse /W2 array from CIDFont dict into CID → vertical metrics map.
///
/// Format mirrors /W but each entry has 3 values: w1 (vertical advance),
/// v_x and v_y (position vector from horizontal to vertical origin).
/// All values are in 1/1000 em units (NOT divided by 1000).
fn parse_cid_w2(cid_font_dict: &PdfDict, resolver: &Resolver) -> HashMap<u16, [f64; 3]> {
    let mut metrics = HashMap::new();
    let w2_obj = match cid_font_dict.get(b"W2") {
        Some(obj) => match resolver.deref(obj) {
            Ok(resolved) => resolved,
            Err(_) => return metrics,
        },
        None => return metrics,
    };
    let arr = match w2_obj.as_array() {
        Some(a) => a,
        None => return metrics,
    };
    let mut i = 0;
    while i < arr.len() {
        let first_cid = match &arr[i] {
            PdfObj::Int(n) => *n as u16,
            _ => break,
        };
        i += 1;
        if i >= arr.len() {
            break;
        }
        let next = resolver.deref(&arr[i]).unwrap_or(arr[i].clone());
        match &next {
            PdfObj::Array(sub) => {
                // [ cid_first [w1_1 v_x1 v_y1 w1_2 v_x2 v_y2 ...] ]
                let vals: Vec<f64> = sub.iter().filter_map(|o| o.as_f64()).collect();
                for (j, chunk) in vals.chunks(3).enumerate() {
                    if chunk.len() == 3 {
                        metrics.insert(first_cid + j as u16, [chunk[0], chunk[1], chunk[2]]);
                    }
                }
                i += 1;
            }
            _ => {
                // [ cid_first cid_last w1 v_x v_y ]
                let last_cid = match &next {
                    PdfObj::Int(n) => *n as u16,
                    _ => first_cid,
                };
                i += 1;
                if i + 2 < arr.len() {
                    let w1 = arr[i].as_f64().unwrap_or(-1000.0);
                    let vx = arr[i + 1].as_f64().unwrap_or(0.0);
                    let vy = arr[i + 2].as_f64().unwrap_or(880.0);
                    i += 3;
                    for cid in first_cid..=last_cid {
                        metrics.insert(cid, [w1, vx, vy]);
                    }
                } else {
                    break;
                }
            }
        }
    }
    metrics
}

/// Strip PFB (Printer Font Binary) headers from Type 1 font data.
///
/// PFB format wraps ASCII and binary segments with 6-byte headers:
/// [0x80, type, len_lo, len_lo2, len_hi, len_hi2] + segment data
/// Type 1 = ASCII, Type 2 = binary (eexec), Type 3 = EOF.
fn strip_pfb(data: &[u8]) -> Vec<u8> {
    if data.len() < 2 || data[0] != 0x80 {
        return data.to_vec();
    }
    let mut result = Vec::with_capacity(data.len());
    let mut pos = 0;
    while pos + 6 <= data.len() && data[pos] == 0x80 {
        let segment_type = data[pos + 1];
        if segment_type == 3 {
            break; // EOF marker
        }
        let len = u32::from_le_bytes([data[pos + 2], data[pos + 3], data[pos + 4], data[pos + 5]])
            as usize;
        pos += 6;
        let end = (pos + len).min(data.len());
        result.extend_from_slice(&data[pos..end]);
        pos = end;
    }
    result
}

// === Glyph rendering ===

impl PdfFont {
    /// Get glyph outline path for a character code (single-byte fonts).
    /// Returns None for Type 3 fonts (they use content streams, not outlines).
    pub fn glyph_path(&self, char_code: u8) -> Option<PsPath> {
        match self {
            PdfFont::Type1(f) => f.glyph_path(char_code),
            PdfFont::TrueType(f) => f.glyph_path(char_code),
            PdfFont::Cff(f) => f.glyph_path(char_code),
            PdfFont::CidTrueType(f) => f.glyph_path_cid(char_code as u16),
            PdfFont::CidCff(f) => f.glyph_path_cid(char_code as u16),
            PdfFont::Type3(_) => None,
        }
    }

    /// Get glyph outline path for a CID (2-byte composite fonts).
    pub fn glyph_path_cid(&self, cid: u16) -> Option<PsPath> {
        match self {
            PdfFont::CidTrueType(f) => f.glyph_path_cid(cid),
            PdfFont::CidCff(f) => f.glyph_path_cid(cid),
            _ => self.glyph_path(cid as u8),
        }
    }

    /// Get glyph path for a Unicode code point, bypassing CID machinery.
    /// Used for malformed PDFs that mix WinAnsi literal strings in CID fonts.
    pub fn glyph_path_unicode(&self, unicode: u16) -> Option<PsPath> {
        match self {
            PdfFont::CidTrueType(f) => f.glyph_path_unicode(unicode),
            PdfFont::CidCff(f) => f.glyph_path_unicode(unicode),
            _ => None,
        }
    }

    /// Get width for a Unicode code point from hmtx, bypassing CID widths.
    pub fn glyph_width_unicode(&self, unicode: u16) -> f64 {
        match self {
            PdfFont::CidTrueType(f) => f.glyph_width_unicode(unicode),
            _ => 0.0,
        }
    }

    /// Get width for a character code (in text space units, already ÷1000).
    pub fn glyph_width(&self, char_code: u8) -> f64 {
        match self {
            PdfFont::Type1(f) => f.widths[char_code as usize],
            PdfFont::TrueType(f) => f.widths[char_code as usize],
            PdfFont::Cff(f) => f.widths[char_code as usize],
            PdfFont::CidTrueType(f) => f.glyph_width_cid(char_code as u16),
            PdfFont::CidCff(f) => f.glyph_width_cid(char_code as u16),
            PdfFont::Type3(f) => f.widths[char_code as usize],
        }
    }

    /// Get width for a CID (2-byte composite fonts).
    pub fn glyph_width_cid(&self, cid: u16) -> f64 {
        match self {
            PdfFont::CidTrueType(f) => f.glyph_width_cid(cid),
            PdfFont::CidCff(f) => f.glyph_width_cid(cid),
            _ => self.glyph_width(cid as u8),
        }
    }

    /// Font matrix (glyph space → text space).
    ///
    /// Returns identity for CidCff because the full matrix (including per-FD
    /// composition) is applied inside `glyph_path_cid()`.
    pub fn font_matrix(&self) -> Matrix {
        match self {
            PdfFont::Type1(f) => f.font_matrix,
            PdfFont::TrueType(_) | PdfFont::CidTrueType(_) => Matrix::identity(),
            PdfFont::Cff(f) => f.font_matrix,
            PdfFont::CidCff(_) => Matrix::identity(),
            PdfFont::Type3(f) => f.font_matrix,
        }
    }

    /// Whether this is a composite (CID) font that uses multi-byte character codes.
    pub fn is_composite(&self) -> bool {
        matches!(self, PdfFont::CidTrueType(_) | PdfFont::CidCff(_))
    }

    /// Writing mode: 0 = horizontal, 1 = vertical.
    pub fn wmode(&self) -> u8 {
        match self {
            PdfFont::CidTrueType(f) => f.wmode,
            PdfFont::CidCff(f) => f.wmode,
            _ => 0,
        }
    }

    /// Default vertical metrics [v_y, w1] for vertical writing mode.
    /// v_y = vertical origin y offset (in 1/1000 em), w1 = vertical advance.
    pub fn dw2(&self) -> [f64; 2] {
        match self {
            PdfFont::CidTrueType(f) => f.dw2,
            PdfFont::CidCff(f) => f.dw2,
            _ => [880.0, -1000.0],
        }
    }

    /// Get per-CID vertical metrics (w1, v_x, v_y), falling back to DW2.
    /// Returns values in 1/1000 em units.
    pub fn vertical_metrics_cid(&self, cid: u16) -> [f64; 3] {
        match self {
            PdfFont::CidTrueType(f) => {
                if let Some(&m) = f.w2.get(&cid) {
                    m
                } else {
                    // DW2 = [v_y, w1]; v_x defaults to half the horizontal width
                    let w0 = f.cid_widths.get(&cid).copied().unwrap_or(f.default_width) * 1000.0;
                    [f.dw2[1], w0 / 2.0, f.dw2[0]]
                }
            }
            PdfFont::CidCff(f) => {
                if let Some(&m) = f.w2.get(&cid) {
                    m
                } else {
                    let w0 = f.cid_widths.get(&cid).copied().unwrap_or(f.default_width) * 1000.0;
                    [f.dw2[1], w0 / 2.0, f.dw2[0]]
                }
            }
            _ => [-1000.0, 500.0, 880.0],
        }
    }

    /// Whether a CID maps to a GID that exists in the font.
    /// Used to distinguish valid 2-byte CID codes from misinterpreted WinAnsi
    /// bytes in malformed PDFs that mix 1-byte literal text with CID fonts.
    pub fn has_cid_glyph(&self, cid: u16) -> bool {
        match self {
            PdfFont::CidTrueType(f) => f.has_glyph(cid),
            PdfFont::CidCff(_) => true, // CFF handles this differently
            _ => false,
        }
    }

    /// Map a raw character code to a CID using the encoding CMap.
    /// Returns the code unchanged if no mapping exists (identity encoding).
    pub fn resolve_code_to_cid(&self, code: u32) -> u32 {
        match self {
            PdfFont::CidTrueType(f) => f.code_to_cid.get(&code).copied().unwrap_or(code),
            PdfFont::CidCff(f) => f.code_to_cid.get(&code).copied().unwrap_or(code),
            _ => code,
        }
    }

    /// Get the byte width of a character code starting with the given byte.
    /// Only meaningful for composite fonts; returns 1 for simple fonts.
    pub fn code_width(&self, first_byte: u8) -> usize {
        match self {
            PdfFont::CidTrueType(f) => {
                let w = f.code_lengths[first_byte as usize];
                if w == 0 { 2 } else { w as usize }
            }
            PdfFont::CidCff(f) => {
                let w = f.code_lengths[first_byte as usize];
                if w == 0 { 2 } else { w as usize }
            }
            _ => 1,
        }
    }

    /// Whether this is a Type 3 font (glyphs are content streams).
    pub fn is_type3(&self) -> bool {
        matches!(self, PdfFont::Type3(_))
    }

    /// Get the Type 3 glyph stream data for a character code.
    pub fn type3_char_proc(&self, char_code: u8) -> Option<&[u8]> {
        match self {
            PdfFont::Type3(f) => f.char_procs.get(&char_code).map(|v| v.as_slice()),
            _ => None,
        }
    }

    /// Get the Type 3 font resources dict.
    pub fn type3_resources(&self) -> Option<&PdfDict> {
        match self {
            PdfFont::Type3(f) => Some(&f.resources),
            _ => None,
        }
    }
}

impl Type1PdfFont {
    fn glyph_path(&self, char_code: u8) -> Option<PsPath> {
        let glyph_name = self.encoding[char_code as usize].as_deref();
        let charstring = glyph_name
            .and_then(|name| self.font.charstrings.get(name))
            .or_else(|| {
                if !self.builtin_fallback {
                    return None;
                }
                let builtin = self.font.encoding.get(char_code as usize)?;
                if builtin != ".notdef" && glyph_name.map_or(true, |n| n != builtin) {
                    self.font.charstrings.get(builtin.as_str())
                } else {
                    None
                }
            })?;
        // Provide charstring lookup for seac (accented character composition)
        let cs_lookup =
            |name: &str| -> Option<Vec<u8>> { self.font.charstrings.get(name).cloned() };
        let result = execute_charstring_mm(
            charstring,
            &self.font.subrs,
            self.font.len_iv,
            false,
            Some(&cs_lookup),
            self.weight_vector.as_deref(),
        )
        .ok()?;
        // For non-metric-compatible substitutes, scale glyph horizontally so its
        // width matches the PDF's /Widths entry. Without this, the substitute
        // font's different glyph metrics cause crowded or sparse character spacing.
        if self.per_char_width_scale {
            let pdf_w = self.widths[char_code as usize];
            let font_w = result.width_x * self.font_matrix.a;
            if font_w.abs() > 0.001 && pdf_w > 0.001 && (pdf_w / font_w - 1.0).abs() > 0.01 {
                return Some(result.path.transform(&Matrix::scale(pdf_w / font_w, 1.0)));
            }
        }
        Some(result.path)
    }
}

impl TrueTypePdfFont {
    /// Check if any gNNNN glyph name in the encoding contains hex letters (a-f),
    /// indicating the subsetting tool used hexadecimal GIDs.
    fn detect_gid_hex(encoding: &[Option<String>; 256]) -> bool {
        encoding.iter().any(|name| {
            if let Some(n) = name {
                n.starts_with('g')
                    && n.len() > 1
                    && n[1..].bytes().all(|b| b.is_ascii_hexdigit())
                    && n[1..]
                        .bytes()
                        .any(|b| b.is_ascii_hexdigit() && !b.is_ascii_digit())
            } else {
                false
            }
        })
    }

    fn glyph_path(&self, char_code: u8) -> Option<PsPath> {
        let gid = self.char_code_to_gid(char_code);
        let gid = gid?;
        let path = skrifa_glyph_path(&self.data, gid, self.units_per_em).or_else(|| {
            // Fallback for locx/glyx PDF-subset fonts that skrifa can't parse
            let glyf_data = get_glyf_data(&self.data, gid)?;
            let data_ref = &self.data;
            let p = parse_glyf_to_path(&glyf_data, &|cid| get_glyf_data(data_ref, cid));
            if p.is_empty() { None } else { Some(p) }
        })?;
        let scale = 1.0 / self.units_per_em;
        let m = Matrix::scale(scale, scale);
        Some(path.transform(&m))
    }

    fn char_code_to_gid(&self, char_code: u8) -> Option<u16> {
        // Symbolic re-encoded fonts: skip the encoding→AGL→cmap path, which maps
        // StandardEncoding names (e.g. "circumflex") to wrong Unicode→GID values.
        // Go directly to the cmap lookup by char code.
        if self.identity_gid {
            if let Some(&gid) = self.cmap.get(&(char_code as u32)) {
                return Some(gid);
            }
            if let Some(&gid) = self.cmap.get(&(0xF000 + char_code as u32)) {
                return Some(gid);
            }
            return Some(char_code as u16);
        }
        if let Some(glyph_name) = &self.encoding[char_code as usize] {
            // Only use encoding → glyph name → Unicode → cmap when the cmap
            // is Unicode-keyed ((3,1), (3,10), or (0,*)).  Non-Unicode cmaps
            // ((1,0) Mac Roman, (3,0) Symbol) in subset fonts map re-encoded
            // char codes directly — looking up Unicode values gives wrong GIDs.
            if self.cmap_is_unicode {
                if let Some(unicode) = stet_fonts::agl::glyph_name_to_unicode(glyph_name)
                    && let Some(&gid) = self.cmap.get(&(unicode as u32))
                {
                    return Some(gid);
                }
            }
        }
        // ToUnicode CMap → Unicode → cmap GID.  Tried before gNNNN because
        // gNNNN GIDs are font-specific — they're wrong for substitute fonts
        // (e.g. SimSun g18331 ≠ NotoSerif GID 18331).
        // Only use when cmap is Unicode-keyed — non-Unicode cmaps map
        // re-encoded char codes, not Unicode values.
        if self.cmap_is_unicode {
            if let Some(&unicode) = self.to_unicode.get(&(char_code as u16))
                && let Some(&gid) = self.cmap.get(&unicode)
            {
                return Some(gid);
            }
        }
        if let Some(glyph_name) = &self.encoding[char_code as usize] {
            // Try gNNNN pattern → direct GID (for embedded fonts where GIDs match).
            // Some subsetting tools use hex (g003a = GID 58), others decimal (g1863).
            // detect_gid_hex() checks if any name in this font has hex letters (a-f).
            if glyph_name.starts_with('g')
                && glyph_name.len() > 1
                && glyph_name[1..].bytes().all(|b| b.is_ascii_hexdigit())
            {
                let suffix = &glyph_name[1..];
                let gid = if self.gid_hex {
                    u16::from_str_radix(suffix, 16).ok()
                } else {
                    suffix.parse::<u16>().ok()
                };
                if let Some(gid) = gid {
                    return Some(gid);
                }
            }
        }
        // Direct cmap lookup by char code — preferred over post table for subset
        // TrueType fonts where glyph names may not match character code positions.
        if let Some(&gid) = self.cmap.get(&(char_code as u32)) {
            return Some(gid);
        }
        if let Some(glyph_name) = &self.encoding[char_code as usize] {
            // Post table fallback (handles ligatures like fl/fi)
            if let Some(&gid) = self.post_name_to_gid.get(glyph_name.as_str()) {
                return Some(gid);
            }
        }
        // Windows Symbol encoding (U+F0XX range, common in subset fonts)
        if let Some(&gid) = self.cmap.get(&(0xF000 + char_code as u32)) {
            return Some(gid);
        }
        // ToUnicode → glyph lookup.  Handles buggy subset fonts where the (3,0)
        // Symbol cmap is missing entries (e.g. issue8234: 0xF020 omitted).
        // Try AGL name → post table first, then skrifa's charmap (which checks
        // all cmap subtables including ones our parser may not have selected).
        if let Some(&unicode) = self.to_unicode.get(&(char_code as u16)) {
            if let Some(name) = stet_fonts::system_fonts::unicode_to_glyph_name(unicode) {
                if let Some(&gid) = self.post_name_to_gid.get(name) {
                    return Some(gid);
                }
            }
            if let Ok(font_ref) = skrifa::FontRef::new(&self.data) {
                let charmap = font_ref.charmap();
                if let Some(gid) = charmap.map(unicode) {
                    return Some(gid.to_u32() as u16);
                }
            }
            // Last resort: scan for unmapped composite GIDs.  Buggy subset
            // fonts may omit cmap entries for some glyphs.  The missing glyph
            // is typically a TrueType composite (e.g. ä = a + dieresis) at an
            // unmapped GID — sometimes even GID 0 (issue8234).
            if !self.cmap.is_empty() {
                use stet_fonts::truetype::{find_table, read_u16};
                let mapped: std::collections::HashSet<u16> = self.cmap.values().copied().collect();
                let num_glyphs = find_table(&self.data, b"maxp")
                    .map(|(off, _)| read_u16(&self.data, off + 4))
                    .unwrap_or(0);
                // Find an unmapped GID that is a composite glyph (numContours < 0).
                // Composites are the actual characters; simple glyphs at unmapped
                // GIDs are base components (a, dieresis, ring, etc.).
                for gid in 0..num_glyphs {
                    if mapped.contains(&gid) {
                        continue;
                    }
                    if let Some(glyf_data) = get_glyf_data(&self.data, gid) {
                        if glyf_data.len() >= 2 {
                            let num_contours = stet_fonts::truetype::read_i16(&glyf_data, 0);
                            if num_contours < 0 {
                                return Some(gid);
                            }
                        }
                    }
                }
            }
        }
        if self.cmap.is_empty() {
            // No cmap table: use char code as GID directly (PDF subset identity mapping)
            Some(char_code as u16)
        } else {
            None
        }
    }
}

impl CidTrueTypePdfFont {
    /// For UCS2 encodings, convert Unicode code point to CID for width lookup.
    fn resolve_cid(&self, code: u16) -> u16 {
        // Only remap when code_to_cid is empty (no CMap loaded) — in that case
        // the code IS a raw Unicode code point that needs mapping to a CID.
        // When a CMap IS loaded, it has already mapped to the correct CID.
        if self.ucs2_encoding && !self.ordering.is_empty() && self.code_to_cid.is_empty() {
            super::cid_unicode::unicode_to_cid(&self.ordering, code as u32).unwrap_or(code)
        } else {
            code
        }
    }

    fn glyph_path_cid(&self, cid: u16) -> Option<PsPath> {
        if std::env::var("STET_DEBUG_TEXT").is_ok() {
            eprintln!(
                "[cid_tt] cid={} sub={} ordering={} identity={} to_unicode={} cmap={} cid_to_gid_map={}",
                cid,
                self.substituted,
                String::from_utf8_lossy(&self.ordering),
                self.identity_cid_to_gid,
                !self.to_unicode.is_empty(),
                !self.cmap.is_empty(),
                self.cid_to_gid_map.is_some()
            );
        }
        let gid = if self.ucs2_encoding && !self.cmap.is_empty() && self.code_to_cid.is_empty() {
            // UCS2 encoding with no CMap: cid is a raw Unicode code point, map via cmap.
            if let Some(&g) = self.cmap.get(&(cid as u32)) {
                g
            } else {
                return None;
            }
        } else if self.ucs2_encoding && self.substituted && !self.ordering.is_empty() {
            // CMap was loaded: cid is an Adobe CID, convert back to Unicode for glyph lookup
            let unicode = super::cid_unicode::cid_to_unicode(&self.ordering, cid)?;
            *self.cmap.get(&unicode)?
        } else if let Some(ref map) = self.cid_to_gid_map {
            // Explicit CIDToGIDMap stream: look up CID → GID
            *map.get(cid as usize).unwrap_or(&0)
        } else if self.substituted && !self.to_unicode.is_empty() {
            // Substituted font: CID → Unicode (via ToUnicode) → GID (via cmap)
            if let Some(&unicode) = self.to_unicode.get(&cid) {
                *self.cmap.get(&unicode)?
            } else {
                // GID not covered by the to_unicode map (e.g. extended Latin
                // chars missing from the standard glyph map). Fall back to
                // CID as GID directly — may be wrong but better than blank.
                cid
            }
        } else if self.substituted && !self.ordering.is_empty() && self.ordering != b"Identity" {
            // Substituted font with Adobe CID registry (CJK): use CID→Unicode table
            let unicode = super::cid_unicode::cid_to_unicode(&self.ordering, cid)?;
            *self.cmap.get(&unicode)?
        } else if self.identity_cid_to_gid {
            // Identity CIDToGIDMap: CID = GID directly.
            cid
        } else if self.substituted && !self.cmap.is_empty() {
            // Substituted font with no ToUnicode, no CIDToGIDMap, and non-identity:
            // treat CID as Unicode and map through the substitute's cmap.
            if let Some(&g) = self.cmap.get(&(cid as u32)) {
                g
            } else {
                cid
            }
        } else if !self.cmap.is_empty() {
            // Non-Identity mapping: CID is Unicode, use cmap
            *self.cmap.get(&(cid as u32))?
        } else {
            cid
        };
        let path = skrifa_glyph_path(&self.data, gid, self.units_per_em).or_else(|| {
            // Fallback for fonts where skrifa can't render a glyph (e.g. locx/glyx
            // PDF-subset tables, or skrifa CFF rendering gaps).
            let glyf_data = get_glyf_data(&self.data, gid)?;
            let data_ref = &self.data;
            let p = parse_glyf_to_path(&glyf_data, &|cid| get_glyf_data(data_ref, cid));
            // Sanity check: real glyphs have at most a few thousand segments.
            // Bogus GIDs reading random glyf bytes can produce millions.
            if p.is_empty() || p.segments.len() > 10_000 {
                None
            } else {
                Some(p)
            }
        });
        let path = path?;
        let scale = 1.0 / self.units_per_em;
        // For substituted fonts, scale glyphs horizontally so their width matches
        // the PDF's /W array (original font metrics). Without this, the substitute
        // font's wider/narrower glyphs cause crowded or sparse text.
        let m = if self.substituted {
            // Only scale horizontally when the CID has an explicit /W entry.
            // When the width comes from the substitute font's hmtx (no /W entry),
            // the advance and glyph width already match — scaling would stretch
            // the glyph to DW while the advance uses the natural hmtx width.
            let pdf_w = self.cid_widths.get(&cid).copied();
            let font_w =
                hmtx_advance_width(&self.data, gid, self.units_per_em).unwrap_or(0.0) / 1000.0;
            if let Some(pw) = pdf_w {
                if font_w > 0.001 && pw > 0.001 {
                    Matrix::new(scale * pw / font_w, 0.0, 0.0, scale, 0.0, 0.0)
                } else {
                    Matrix::scale(scale, scale)
                }
            } else {
                Matrix::scale(scale, scale)
            }
        } else {
            Matrix::scale(scale, scale)
        };
        Some(path.transform(&m))
    }

    /// Check if a GID exists in the font (GID < numGlyphs from maxp table).
    /// Unlike glyph_path_cid, this returns true for space/whitespace GIDs
    /// that have no visible outline.
    fn has_glyph(&self, cid: u16) -> bool {
        // A CID with an explicit width in /W is always valid — even if we
        // can't resolve it to a glyph in the substitute font, the CID path
        // must be used so text advancement uses the correct width.
        if self.cid_widths.contains_key(&cid) {
            return true;
        }
        // Resolve CID to GID using the same logic as glyph_path_cid
        let gid = if let Some(ref map) = self.cid_to_gid_map {
            *map.get(cid as usize).unwrap_or(&0)
        } else if self.substituted && !self.to_unicode.is_empty() {
            // Substituted font with GID→Unicode table: resolve via cmap
            if let Some(&unicode) = self.to_unicode.get(&cid) {
                if let Some(&g) = self.cmap.get(&unicode) {
                    g
                } else {
                    return false;
                }
            } else {
                return false;
            }
        } else if self.identity_cid_to_gid {
            cid
        } else {
            return true; // non-identity: assume valid
        };
        // Check against font's glyph count
        let num_glyphs = stet_fonts::truetype::get_num_glyphs(&self.data);
        (gid as u32) < num_glyphs
    }

    fn glyph_width_cid(&self, cid: u16) -> f64 {
        let resolved = self.resolve_cid(cid);
        if let Some(&w) = self.cid_widths.get(&resolved) {
            return w;
        }
        // For substituted fonts with GID-to-Unicode tables, use the substitute
        // font's actual advance width instead of /DW. Many PDFs only populate
        // /W for a subset of CIDs, and /DW 1000 (full em) is wildly wrong for
        // narrow Latin characters like accented letters.
        if self.substituted && !self.to_unicode.is_empty() {
            if let Some(&unicode) = self.to_unicode.get(&cid) {
                if let Some(&gid) = self.cmap.get(&unicode) {
                    if let Some(w) = hmtx_advance_width(&self.data, gid, self.units_per_em) {
                        return w / 1000.0;
                    }
                }
            }
        }
        self.default_width
    }

    /// Get glyph path for a Unicode code point via cmap, bypassing CID mapping.
    /// Used when malformed PDFs embed WinAnsi literal strings in a CID font.
    fn glyph_path_unicode(&self, unicode: u16) -> Option<PsPath> {
        let &gid = self.cmap.get(&(unicode as u32))?;
        let path = skrifa_glyph_path(&self.data, gid, self.units_per_em)?;
        let scale = 1.0 / self.units_per_em;
        let m = Matrix::scale(scale, scale);
        Some(path.transform(&m))
    }

    /// Get width for a Unicode code point from hmtx via cmap, bypassing CID widths.
    /// Returns width in the same scale as glyph_width_cid (1/1000 of text space).
    fn glyph_width_unicode(&self, unicode: u16) -> f64 {
        if let Some(&gid) = self.cmap.get(&(unicode as u32)) {
            // hmtx_advance_width returns units in 1/1000 em; CID widths are stored
            // already divided by 1000, so divide here too for consistency.
            hmtx_advance_width(&self.data, gid, self.units_per_em)
                .map(|w| w / 1000.0)
                .unwrap_or(self.default_width)
        } else {
            self.default_width
        }
    }
}

impl CidCffPdfFont {
    /// Render the CFF charstring at the given GID.
    fn glyph_path_at_gid(&self, gid: usize) -> Option<PsPath> {
        if gid >= self.font.char_strings.len() {
            return None;
        }
        let (default_width_x, nominal_width_x, local_subrs, fd_font_matrix) = if self.font.is_cid
            && !self.font.fd_select.is_empty()
            && !self.font.fd_array.is_empty()
        {
            let fd_idx = *self.font.fd_select.get(gid).unwrap_or(&0) as usize;
            if let Some(fd) = self.font.fd_array.get(fd_idx) {
                (
                    fd.default_width_x,
                    fd.nominal_width_x,
                    &fd.local_subrs,
                    fd.font_matrix,
                )
            } else {
                (
                    self.font.default_width_x,
                    self.font.nominal_width_x,
                    &self.font.local_subrs,
                    None,
                )
            }
        } else {
            (
                self.font.default_width_x,
                self.font.nominal_width_x,
                &self.font.local_subrs,
                None,
            )
        };
        let result = execute_type2_charstring(
            &self.font.char_strings[gid],
            local_subrs,
            &self.font.global_subrs,
            default_width_x,
            nominal_width_x,
            false,
        )
        .ok()?;
        let effective_fm = if let Some(fd_fm) = fd_font_matrix {
            let fd = Matrix::new(fd_fm[0], fd_fm[1], fd_fm[2], fd_fm[3], fd_fm[4], fd_fm[5]);
            if fd.a.abs() < 0.01 || fd.d.abs() < 0.01 {
                fd
            } else {
                self.font_matrix.concat(&fd)
            }
        } else {
            self.font_matrix
        };
        Some(result.path.transform(&effective_fm))
    }

    /// Render a glyph by Unicode code point via the font's cmap table.
    fn glyph_path_unicode(&self, unicode: u16) -> Option<PsPath> {
        let cmap = self.cmap.as_ref()?;
        let &gid = cmap.get(&(unicode as u32))?;
        self.glyph_path_at_gid(gid as usize)
    }

    fn glyph_path_cid(&self, cid: u16) -> Option<PsPath> {
        // Type 1 fonts wrapped as CIDFontType0: use pre-computed paths.
        if let Some(ref paths) = self.type1_paths {
            return paths.get(&cid).cloned();
        }
        // For embedded OTF/CFF with PDF CIDToGIDMap, use the PDF's mapping.
        // For OpenType/CFF substitutes with a cmap, map Unicode → GID directly.
        // For embedded CID-keyed CFF, use cid_to_gid mapping.
        let gid = if let Some(ref map) = self.pdf_cid_to_gid {
            // Embedded font with PDF-supplied CID→GID map
            *map.get(cid as usize).unwrap_or(&0) as usize
        } else if self.identity_cid_to_gid {
            // Identity CIDToGIDMap: CID = charstring index directly.
            // Common for CIDFontType2 fonts stored as OTTO/CFF in FontFile2.
            cid as usize
        } else if let Some(ref cmap) = self.cmap {
            // OTF font with Unicode cmap (substituted fonts, or non-CID fonts).
            // If this is a substituted font with an Adobe CID ordering
            // (e.g. Japan1), the CID is from the Adobe registry, not Unicode.
            // Convert CID → Unicode first, then look up in cmap.
            if !self.ordering.is_empty() && self.ordering != b"Identity" {
                let unicode = super::cid_unicode::cid_to_unicode(&self.ordering, cid)?;
                // For CJK substitution, try full-width glyph variants first.
                // The substitute font may have a proportional glyph for U+00B7
                // (MIDDLE DOT, narrow) while the original CJK font used a
                // full-width centered dot. U+30FB is the CJK full-width variant.
                let gid_opt = cjk_fullwidth_alternative(unicode)
                    .and_then(|alt| cmap.get(&alt))
                    .or_else(|| cmap.get(&unicode));
                *gid_opt? as usize
            } else {
                *cmap.get(&(cid as u32))? as usize
            }
        } else if !self.font.cid_to_gid.is_empty() {
            let g = *self.font.cid_to_gid.get(cid as usize)?;
            if g == 0xFFFF {
                return None;
            }
            g as usize
        } else {
            cid as usize
        };
        self.glyph_path_at_gid(gid)
    }

    fn glyph_width_cid(&self, cid: u16) -> f64 {
        // CID widths from the /W array are already keyed by CID — use directly.
        self.cid_widths
            .get(&cid)
            .copied()
            .unwrap_or(self.default_width)
    }
}

impl CffPdfFont {
    fn glyph_path(&self, char_code: u8) -> Option<PsPath> {
        let glyph_name = self.encoding[char_code as usize].as_deref()?;
        // The PDF /Encoding is authoritative: map char_code → glyph name,
        // then find that glyph in the CFF charset. This is essential for
        // subset fonts where the CFF internal encoding maps codes to
        // sequential GIDs that don't match the PDF encoding's glyph names.
        // Fall back to the CFF's built-in encoding only when the charset
        // lookup fails (e.g., fonts without a proper charset).
        let gid = self
            .font
            .charset
            .iter()
            .position(|name| name == glyph_name)
            .or_else(|| {
                let cff_gid = self
                    .font
                    .encoding
                    .get(char_code as usize)
                    .copied()
                    .unwrap_or(0) as usize;
                if cff_gid > 0 && cff_gid < self.font.char_strings.len() {
                    Some(cff_gid)
                } else {
                    None
                }
            });
        let gid = gid?;
        if gid >= self.font.char_strings.len() {
            return None;
        }
        let result = execute_type2_charstring(
            &self.font.char_strings[gid],
            &self.font.local_subrs,
            &self.font.global_subrs,
            self.font.default_width_x,
            self.font.nominal_width_x,
            false,
        )
        .ok()?;

        // Handle deprecated seac (accented character composition)
        if let Some((adx, ady, bchar, achar)) = result.seac {
            return self.compose_seac(adx, ady, bchar, achar);
        }

        Some(result.path)
    }

    /// Compose a seac (Standard Encoding Accented Character) glyph from
    /// base and accent glyphs. bchar/achar are Standard Encoding codes.
    fn compose_seac(&self, adx: f64, ady: f64, bchar: u8, achar: u8) -> Option<PsPath> {
        use stet_fonts::encoding::STANDARD_ENCODING;

        let base_name = STANDARD_ENCODING.get(bchar as usize).copied().unwrap_or("");
        let accent_name = STANDARD_ENCODING.get(achar as usize).copied().unwrap_or("");

        let base_gid = self.font.charset.iter().position(|n| n == base_name)?;
        let accent_gid = self.font.charset.iter().position(|n| n == accent_name)?;

        let base_result = execute_type2_charstring(
            &self.font.char_strings[base_gid],
            &self.font.local_subrs,
            &self.font.global_subrs,
            self.font.default_width_x,
            self.font.nominal_width_x,
            false,
        )
        .ok()?;

        let accent_result = execute_type2_charstring(
            &self.font.char_strings[accent_gid],
            &self.font.local_subrs,
            &self.font.global_subrs,
            self.font.default_width_x,
            self.font.nominal_width_x,
            false,
        )
        .ok()?;

        // Combine: base path + accent path offset by (adx, ady)
        let mut combined = base_result.path;
        let offset = Matrix::translate(adx, ady);
        let shifted_accent = accent_result.path.transform(&offset);
        combined
            .segments
            .extend_from_slice(&shifted_accent.segments);
        Some(combined)
    }
}

/// Pen adapter that converts skrifa outline callbacks into a `PsPath`.
struct PsPathPen {
    path: PsPath,
    cur_x: f64,
    cur_y: f64,
}

impl skrifa::outline::OutlinePen for PsPathPen {
    fn move_to(&mut self, x: f32, y: f32) {
        self.cur_x = x as f64;
        self.cur_y = y as f64;
        self.path
            .segments
            .push(PathSegment::MoveTo(self.cur_x, self.cur_y));
    }
    fn line_to(&mut self, x: f32, y: f32) {
        self.cur_x = x as f64;
        self.cur_y = y as f64;
        self.path
            .segments
            .push(PathSegment::LineTo(self.cur_x, self.cur_y));
    }
    fn quad_to(&mut self, cx: f32, cy: f32, x: f32, y: f32) {
        let cx = cx as f64;
        let cy = cy as f64;
        let ex = x as f64;
        let ey = y as f64;
        // Quadratic → cubic degree elevation
        let cp1x = self.cur_x + 2.0 / 3.0 * (cx - self.cur_x);
        let cp1y = self.cur_y + 2.0 / 3.0 * (cy - self.cur_y);
        let cp2x = ex + 2.0 / 3.0 * (cx - ex);
        let cp2y = ey + 2.0 / 3.0 * (cy - ey);
        self.cur_x = ex;
        self.cur_y = ey;
        self.path.segments.push(PathSegment::CurveTo {
            x1: cp1x,
            y1: cp1y,
            x2: cp2x,
            y2: cp2y,
            x3: ex,
            y3: ey,
        });
    }
    fn curve_to(&mut self, cx0: f32, cy0: f32, cx1: f32, cy1: f32, x: f32, y: f32) {
        self.cur_x = x as f64;
        self.cur_y = y as f64;
        self.path.segments.push(PathSegment::CurveTo {
            x1: cx0 as f64,
            y1: cy0 as f64,
            x2: cx1 as f64,
            y2: cy1 as f64,
            x3: self.cur_x,
            y3: self.cur_y,
        });
    }
    fn close(&mut self) {
        self.path.segments.push(PathSegment::ClosePath);
    }
}

/// Extract a TrueType glyph outline using skrifa with hinting enabled.
///
/// Hinting is needed for correct composite glyph assembly — some fonts have
/// TrueType instructions that adjust component positions. Falls back to the
/// hand-written parser for fonts skrifa can't handle (e.g., locx/glyx subsets).
/// Map a WinAnsiEncoding byte to its Unicode code point.
/// Bytes 0x00-0x7F and 0xA0-0xFF match Unicode (ISO 8859-1).
/// Bytes 0x80-0x9F differ — WinAnsi maps these to specific Unicode characters.
pub(crate) fn winansi_byte_to_unicode(byte: u8) -> u16 {
    match byte {
        0x80 => 0x20AC, //        0x82 => 0x201A, //        0x83 => 0x0192, // ƒ
        0x84 => 0x201E, //        0x85 => 0x2026, //        0x86 => 0x2020, //        0x87 => 0x2021, //        0x88 => 0x02C6, // ˆ
        0x89 => 0x2030, //        0x8A => 0x0160, // Š
        0x8B => 0x2039, //        0x8C => 0x0152, // Œ
        0x8E => 0x017D, // Ž
        0x91 => 0x2018, // '
        0x92 => 0x2019, // '
        0x93 => 0x201C, // "
        0x94 => 0x201D, // "
        0x95 => 0x2022, //        0x96 => 0x2013, //        0x97 => 0x2014, //        0x98 => 0x02DC, // ˜
        0x99 => 0x2122, //        0x9A => 0x0161, // š
        0x9B => 0x203A, //        0x9C => 0x0153, // œ
        0x9E => 0x017E, // ž
        0x9F => 0x0178, // Ÿ
        _ => byte as u16,
    }
}

/// Read the advance width for a GID from the hmtx table, returning the width
/// in text space (1/1000 em) for PDF CID width compatibility.
fn hmtx_advance_width(font_data: &[u8], gid: u16, units_per_em: f64) -> Option<f64> {
    use stet_fonts::truetype::{find_table, read_u16};
    let (hhea_off, _) = find_table(font_data, b"hhea")?;
    let (hmtx_off, _) = find_table(font_data, b"hmtx")?;
    if hhea_off + 36 > font_data.len() {
        return None;
    }
    let num_h_metrics = read_u16(font_data, hhea_off + 34) as usize;
    let gid = gid as usize;
    let advance = if gid < num_h_metrics {
        let offset = hmtx_off + gid * 4;
        if offset + 2 > font_data.len() {
            return None;
        }
        read_u16(font_data, offset)
    } else {
        // Use last metric for GIDs beyond num_h_metrics
        if num_h_metrics == 0 {
            return None;
        }
        let offset = hmtx_off + (num_h_metrics - 1) * 4;
        if offset + 2 > font_data.len() {
            return None;
        }
        read_u16(font_data, offset)
    };
    // Convert from font units to 1/1000 em (PDF text space)
    Some(advance as f64 / units_per_em * 1000.0)
}

fn skrifa_glyph_path(font_data: &[u8], gid: u16, units_per_em: f64) -> Option<PsPath> {
    // Use from_index(0) to handle both plain TrueType and TTC files.
    let font_ref = skrifa::FontRef::from_index(font_data, 0).ok()?;
    let outlines = font_ref.outline_glyphs();
    let glyph = outlines.get(skrifa::GlyphId::new(gid as u32))?;

    // Use TrueType bytecode interpreter with mono hinting for correct composite
    // glyph assembly. Some fonts have TT instructions that adjust component positions;
    // the auto-hinter doesn't handle these correctly.
    let hinting = skrifa::outline::HintingInstance::new(
        &outlines,
        skrifa::prelude::Size::new(units_per_em as f32),
        skrifa::instance::LocationRef::default(),
        skrifa::outline::HintingOptions {
            engine: skrifa::outline::Engine::Interpreter,
            target: skrifa::outline::Target::Mono,
        },
    )
    .ok();

    let mut pen = PsPathPen {
        path: PsPath::new(),
        cur_x: 0.0,
        cur_y: 0.0,
    };

    let result = if let Some(ref instance) = hinting {
        glyph.draw(instance, &mut pen)
    } else {
        glyph.draw(
            skrifa::outline::DrawSettings::unhinted(
                skrifa::prelude::Size::new(units_per_em as f32),
                skrifa::instance::LocationRef::default(),
            ),
            &mut pen,
        )
    };

    result.ok()?;
    if pen.path.is_empty() {
        None
    } else {
        Some(pen.path)
    }
}