rdocx 0.5.0

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

use std::path::Path;
use std::sync::{Arc, Mutex};

#[cfg(test)]
use std::cell::Cell;

use oxml_media::MediaNamer;
use oxml_opc::OpcPackage;
use oxml_opc::relationship::rel_types;
use rdocx_oxml::document::{BodyContent, CT_Columns, CT_Document, CT_SectPr};
use rdocx_oxml::drawing::{CT_Anchor, CT_Drawing, CT_Inline};
use rdocx_oxml::header_footer::{CT_HdrFtr, HdrFtrRef, HdrFtrType};
use rdocx_oxml::numbering::{CT_Numbering, ST_NumberFormat};
use rdocx_oxml::properties::{CT_PPr, CT_RPr};
use rdocx_oxml::shared::{ST_PageOrientation, ST_SectionType};
use rdocx_oxml::styles::CT_Styles;
use rdocx_oxml::table::{CT_Tbl, CellContent};
use rdocx_oxml::text::{CT_P, CT_R, RunContent};

use rdocx_oxml::core_properties::CoreProperties;

use crate::Length;
use crate::error::{Error, Result};
use crate::paragraph::{Paragraph, ParagraphRef};
use crate::style::{self, Style, StyleBuilder};
use crate::table::{Table, TableRef};

/// A Word document (.docx file).
///
/// This is the main entry point for reading, creating, and modifying
/// DOCX documents.
pub struct Document {
    package: OpcPackage,
    document: CT_Document,
    styles: CT_Styles,
    numbering: Option<CT_Numbering>,
    core_properties: Option<CoreProperties>,
    /// Package part containing the core properties, resolved from `_rels/.rels`.
    core_properties_part_name: String,
    /// Part name for the main document
    doc_part_name: String,
    /// Part name the styles were loaded from, and where they are written back.
    /// Resolved through the relationship rather than assumed, so a document
    /// that keeps its styles somewhere other than `/word/styles.xml` is
    /// updated in place instead of gaining an orphaned second part.
    styles_part_name: String,
    /// Part name for numbering definitions, resolved the same way.
    numbering_part_name: String,
    /// Collision-free allocator for image media parts.
    image_namer: MediaNamer,
    /// Footnotes: loaded from word/footnotes.xml on open, written back on save.
    footnotes: rdocx_oxml::footnotes::CT_Footnotes,
    /// Normal layout, including system font discovery, computed on first use.
    layout_cache: Mutex<Option<Arc<oxml_layout::LayoutResult>>>,
    /// Bundled-font-only layout used by deterministic rendering.
    deterministic_layout_cache: Mutex<Option<Arc<oxml_layout::LayoutResult>>>,
}

/// Fallback part names used when a document does not already declare one.
const DEFAULT_STYLES_PART: &str = "/word/styles.xml";
const DEFAULT_NUMBERING_PART: &str = "/word/numbering.xml";
const DEFAULT_CORE_PROPERTIES_PART: &str = "/docProps/core.xml";
const DOCUMENT_CONTENT_TYPE: &str =
    "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml";
const STYLES_CONTENT_TYPE: &str =
    "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml";
const NUMBERING_CONTENT_TYPE: &str =
    "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml";
const CORE_PROPERTIES_REL_TYPE: &str =
    "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties";
const CORE_PROPERTIES_CONTENT_TYPE: &str =
    "application/vnd.openxmlformats-package.core-properties+xml";

#[cfg(test)]
thread_local! {
    static LAYOUT_INVOCATIONS: Cell<usize> = const { Cell::new(0) };
}

#[cfg(test)]
fn record_layout_invocation() {
    LAYOUT_INVOCATIONS.set(LAYOUT_INVOCATIONS.get() + 1);
}

fn new_word_package() -> OpcPackage {
    let mut package = OpcPackage::with_main_part("word/document.xml", DOCUMENT_CONTENT_TYPE);
    package
        .content_types
        .add_override(DEFAULT_STYLES_PART, STYLES_CONTENT_TYPE);
    package
}

impl Document {
    /// Create a new, empty document with default page setup and styles.
    pub fn new() -> Self {
        let mut package = new_word_package();
        let document = CT_Document::new();
        let styles = CT_Styles::new_default();

        // Set up styles relationship
        package
            .get_or_create_part_rels("/word/document.xml")
            .add(rel_types::STYLES, "styles.xml");

        Document {
            package,
            document,
            styles,
            numbering: None,
            core_properties: None,
            core_properties_part_name: DEFAULT_CORE_PROPERTIES_PART.to_string(),
            doc_part_name: "/word/document.xml".to_string(),
            styles_part_name: DEFAULT_STYLES_PART.to_string(),
            numbering_part_name: DEFAULT_NUMBERING_PART.to_string(),
            image_namer: MediaNamer::scan("/word/media", "image", std::iter::empty()),
            footnotes: rdocx_oxml::footnotes::CT_Footnotes::new(),
            layout_cache: Mutex::new(None),
            deterministic_layout_cache: Mutex::new(None),
        }
    }

    /// Open a document from a file path.
    pub fn open<P: AsRef<Path>>(path: P) -> Result<Self> {
        let package = OpcPackage::open(path)?;
        Self::from_package(package)
    }

    /// Open a document from bytes.
    pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
        let cursor = std::io::Cursor::new(bytes);
        let package = OpcPackage::from_reader(cursor)?;
        Self::from_package(package)
    }

    fn from_package(package: OpcPackage) -> Result<Self> {
        let doc_part_name = package.main_document_part().ok_or(Error::NoDocumentPart)?;

        let doc_xml = package
            .get_part(&doc_part_name)
            .ok_or(Error::NoDocumentPart)?;
        let document = CT_Document::from_xml(doc_xml)?;

        // Resolve the part a relationship of the given type points at.
        let resolve_part = |rel_type: &str| -> Option<String> {
            let rels = package.get_part_rels(&doc_part_name)?;
            let rel = rels.get_by_type(rel_type)?;
            Some(OpcPackage::resolve_rel_target(&doc_part_name, &rel.target))
        };

        // Try to load styles, remembering where they came from.
        let styles_part_name = resolve_part(rel_types::STYLES);
        let styles = match styles_part_name
            .as_deref()
            .and_then(|p| package.get_part(p))
        {
            Some(styles_xml) => CT_Styles::from_xml(styles_xml)?,
            None => CT_Styles::new_default(),
        };

        // Try to load numbering definitions
        let numbering_part_name = resolve_part(rel_types::NUMBERING);
        let numbering = match numbering_part_name
            .as_deref()
            .and_then(|p| package.get_part(p))
        {
            Some(num_xml) => Some(CT_Numbering::from_xml(num_xml)?),
            None => None,
        };

        // Core properties are a package-level relationship, not a document part.
        let core_properties_part_name = package
            .package_rels
            .get_by_type(CORE_PROPERTIES_REL_TYPE)
            .map(|rel| OpcPackage::resolve_rel_target("/", &rel.target));
        let core_properties = core_properties_part_name
            .as_deref()
            .and_then(|part| package.get_part(part))
            .and_then(|xml| CoreProperties::from_xml(xml).ok());

        let image_namer = MediaNamer::scan(
            "/word/media",
            "image",
            package.parts.keys().map(String::as_str),
        );

        let footnotes = package
            .get_part_rels(&doc_part_name)
            .and_then(|rels| rels.get_by_type(rel_types::FOOTNOTES))
            .map(|rel| OpcPackage::resolve_rel_target(&doc_part_name, &rel.target))
            .and_then(|part| package.get_part(&part))
            .and_then(|xml| rdocx_oxml::footnotes::CT_Footnotes::from_xml(xml).ok())
            .unwrap_or_default();

        Ok(Document {
            package,
            document,
            styles,
            numbering,
            core_properties,
            core_properties_part_name: core_properties_part_name
                .unwrap_or_else(|| DEFAULT_CORE_PROPERTIES_PART.to_string()),
            doc_part_name,
            styles_part_name: styles_part_name.unwrap_or_else(|| DEFAULT_STYLES_PART.to_string()),
            numbering_part_name: numbering_part_name
                .unwrap_or_else(|| DEFAULT_NUMBERING_PART.to_string()),
            image_namer,
            footnotes,
            layout_cache: Mutex::new(None),
            deterministic_layout_cache: Mutex::new(None),
        })
    }

    /// Clear layouts derived from the current document state.
    fn invalidate_layout(&mut self) {
        self.layout_cache
            .get_mut()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .take();
        self.deterministic_layout_cache
            .get_mut()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .take();
    }

    /// Return the normal-font layout, computing it once after each mutation.
    fn cached_layout(&self) -> Result<Arc<oxml_layout::LayoutResult>> {
        let mut cache = self
            .layout_cache
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        if let Some(layout) = cache.as_ref() {
            return Ok(Arc::clone(layout));
        }

        let input = self.build_layout_input();
        #[cfg(test)]
        record_layout_invocation();
        let layout = Arc::new(rdocx_layout::layout_document(&input)?);
        *cache = Some(Arc::clone(&layout));
        Ok(layout)
    }

    /// Return the bundled-font-only layout, computing it once after mutation.
    fn cached_deterministic_layout(&self) -> Result<Arc<oxml_layout::LayoutResult>> {
        let mut cache = self
            .deterministic_layout_cache
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        if let Some(layout) = cache.as_ref() {
            return Ok(Arc::clone(layout));
        }

        let input = self.build_layout_input();
        #[cfg(test)]
        record_layout_invocation();
        let layout = Arc::new(rdocx_layout::layout_document_deterministic(&input)?);
        *cache = Some(Arc::clone(&layout));
        Ok(layout)
    }

    /// Save the document to a file path.
    pub fn save<P: AsRef<Path>>(&mut self, path: P) -> Result<()> {
        self.flush_to_package()?;
        self.package.save(path)?;
        Ok(())
    }

    /// Save the document to a byte vector.
    pub fn to_bytes(&mut self) -> Result<Vec<u8>> {
        self.flush_to_package()?;
        let mut buf = std::io::Cursor::new(Vec::new());
        self.package.write_to(&mut buf)?;
        Ok(buf.into_inner())
    }

    /// Write the in-memory document/styles back into the OPC package parts.
    fn flush_to_package(&mut self) -> Result<()> {
        // Serialize document.xml
        let doc_xml = self.document.to_xml()?;
        self.package.set_part(&self.doc_part_name, doc_xml);

        // Serialize the styles part. A document opened without one still gets
        // rdocx's defaults written out, so make sure it is reachable: an
        // unreferenced, untyped part would simply be ignored by Word.
        let styles_xml = self.styles.to_xml()?;
        let styles_part = self.styles_part_name.clone();
        self.package.set_part(&styles_part, styles_xml);
        self.ensure_part_relationship(&styles_part, rel_types::STYLES, STYLES_CONTENT_TYPE);

        // Serialize numbering definitions if we have any
        if let Some(ref numbering) = self.numbering {
            let numbering_xml = numbering.to_xml()?;
            let numbering_part = self.numbering_part_name.clone();
            self.package.set_part(&numbering_part, numbering_xml);
            self.ensure_part_relationship(
                &numbering_part,
                rel_types::NUMBERING,
                NUMBERING_CONTENT_TYPE,
            );
        }

        // Serialize footnotes.xml when any footnotes exist
        if !self.footnotes.footnotes.is_empty() {
            let fx = self.footnotes.to_xml_footnotes()?;
            self.package.set_part("/word/footnotes.xml", fx);
            self.package.content_types.add_override(
                "/word/footnotes.xml",
                "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml",
            );
            let rels = self
                .package
                .get_or_create_part_rels(&self.doc_part_name.clone());
            if rels.get_by_type(rel_types::FOOTNOTES).is_none() {
                rels.add(rel_types::FOOTNOTES, "footnotes.xml");
            }
        }

        // Serialize core properties to the package relationship's target.
        if let Some(ref props) = self.core_properties {
            let core_xml = props.to_xml()?;
            self.package
                .set_part(&self.core_properties_part_name, core_xml);
            self.package.content_types.add_override(
                &self.core_properties_part_name,
                CORE_PROPERTIES_CONTENT_TYPE,
            );
            if self
                .package
                .package_rels
                .get_by_type(CORE_PROPERTIES_REL_TYPE)
                .is_none()
            {
                let target = self
                    .core_properties_part_name
                    .strip_prefix('/')
                    .unwrap_or(&self.core_properties_part_name);
                self.package
                    .package_rels
                    .add(CORE_PROPERTIES_REL_TYPE, target);
            }
        }

        Ok(())
    }

    /// Make sure `part_name` is reachable from the main document: it needs a
    /// relationship of `rel_type` and a content-type override.
    fn ensure_part_relationship(&mut self, part_name: &str, rel_type: &str, content_type: &str) {
        self.package
            .content_types
            .add_override(part_name, content_type);

        let doc_part_name = self.doc_part_name.clone();
        let already_linked = self
            .package
            .get_part_rels(&doc_part_name)
            .and_then(|rels| rels.get_by_type(rel_type))
            .map(|rel| OpcPackage::resolve_rel_target(&doc_part_name, &rel.target))
            .is_some_and(|target| target == part_name);
        if already_linked {
            return;
        }

        // Relationship targets are relative to the source part's directory.
        let target = relative_target(&doc_part_name, part_name);
        self.package
            .get_or_create_part_rels(&doc_part_name)
            .add(rel_type, &target);
    }

    // ---- Paragraph access ----

    /// Get immutable references to all paragraphs.
    pub fn paragraphs(&self) -> Vec<ParagraphRef<'_>> {
        self.document
            .body
            .paragraphs()
            .map(|p| ParagraphRef { inner: p })
            .collect()
    }

    /// Get an immutable reference to a paragraph by index (among paragraphs only).
    pub fn paragraph(&self, index: usize) -> Option<ParagraphRef<'_>> {
        self.document
            .body
            .paragraphs()
            .nth(index)
            .map(|p| ParagraphRef { inner: p })
    }

    /// All footnotes as (id, plain text), in file order.
    pub fn footnotes(&self) -> Vec<(i32, String)> {
        self.footnotes
            .footnotes
            .iter()
            .map(|f| {
                let text = f
                    .paragraphs
                    .iter()
                    .map(|p| p.text())
                    .collect::<Vec<_>>()
                    .join("\n");
                (f.id, text)
            })
            .collect()
    }

    /// Add a footnote with the given text; returns its id. Pair with
    /// `Paragraph::add_footnote_ref` to reference it from the body.
    pub fn add_footnote(&mut self, text: &str) -> i32 {
        self.invalidate_layout();
        use rdocx_oxml::footnotes::CT_Footnote;
        use rdocx_oxml::text::CT_P;
        let id = self
            .footnotes
            .footnotes
            .iter()
            .map(|f| f.id)
            .max()
            .unwrap_or(1)
            + 1;
        let mut p = CT_P::new();
        p.add_run(text);
        self.footnotes.footnotes.push(CT_Footnote {
            id,
            paragraphs: vec![p],
        });
        id
    }

    /// Add a paragraph with the given text and return a mutable reference.
    pub fn add_paragraph(&mut self, text: &str) -> Paragraph<'_> {
        self.invalidate_layout();
        let mut p = CT_P::new();
        if !text.is_empty() {
            p.add_run(text);
        }
        self.document.body.content.push(BodyContent::Paragraph(p));
        match self.document.body.content.last_mut().unwrap() {
            BodyContent::Paragraph(p) => Paragraph { inner: p },
            _ => unreachable!(),
        }
    }

    /// Get the number of paragraphs.
    pub fn paragraph_count(&self) -> usize {
        self.document.body.paragraphs().count()
    }

    /// Get the plain text of body paragraphs and table cells in document order.
    pub fn text(&self) -> String {
        let mut result = String::new();
        for content in &self.document.body.content {
            match content {
                BodyContent::Paragraph(paragraph) => {
                    result.push_str(&paragraph.text());
                    result.push('\n');
                }
                BodyContent::Table(table) => {
                    for row in &table.rows {
                        for cell in &row.cells {
                            for content in &cell.content {
                                if let CellContent::Paragraph(paragraph) = content {
                                    result.push_str(&paragraph.text());
                                    result.push('\t');
                                }
                            }
                        }
                        result.push('\n');
                    }
                }
                BodyContent::RawXml(_) => {}
            }
        }
        result
    }

    /// Get a mutable reference to a paragraph by index (among paragraphs only).
    pub fn paragraph_mut(&mut self, index: usize) -> Option<Paragraph<'_>> {
        self.invalidate_layout();
        self.document
            .body
            .paragraphs_mut()
            .nth(index)
            .map(|p| Paragraph { inner: p })
    }

    // ---- Table access ----

    /// Get immutable references to all tables.
    pub fn tables(&self) -> Vec<TableRef<'_>> {
        self.document
            .body
            .tables()
            .map(|t| TableRef { inner: t })
            .collect()
    }

    /// Get an immutable table by index among tables only.
    pub fn table(&self, index: usize) -> Option<TableRef<'_>> {
        self.document
            .body
            .tables()
            .nth(index)
            .map(|inner| TableRef { inner })
    }

    /// Get a mutable table by index among tables only.
    pub fn table_mut(&mut self, index: usize) -> Option<Table<'_>> {
        self.invalidate_layout();
        self.document
            .body
            .tables_mut()
            .nth(index)
            .map(|inner| Table { inner })
    }

    /// Add a table with the specified number of rows and columns.
    /// Returns a mutable reference for further configuration.
    pub fn add_table(&mut self, rows: usize, cols: usize) -> Table<'_> {
        self.invalidate_layout();
        use rdocx_oxml::table::{CT_Row, CT_TblGrid, CT_TblGridCol, CT_TblPr, CT_TblWidth, CT_Tc};
        use rdocx_oxml::units::Twips;

        // Default column width: divide 9360tw (6.5" printable at 1" margins) evenly.
        // A zero-column table has no grid to divide; clamp so this cannot divide by zero.
        let col_width = Twips(9360 / cols.max(1) as i32);

        let grid = CT_TblGrid {
            columns: (0..cols)
                .map(|_| CT_TblGridCol { width: col_width })
                .collect(),
        };

        let mut tbl = CT_Tbl::new();
        tbl.properties = Some(CT_TblPr {
            width: Some(CT_TblWidth::dxa(col_width.0 * cols as i32)),
            ..Default::default()
        });
        tbl.grid = Some(grid);

        for _ in 0..rows {
            let mut row = CT_Row::new();
            for _ in 0..cols {
                row.cells.push(CT_Tc::new());
            }
            tbl.rows.push(row);
        }

        self.document.body.content.push(BodyContent::Table(tbl));
        match self.document.body.content.last_mut().unwrap() {
            BodyContent::Table(t) => Table { inner: t },
            _ => unreachable!(),
        }
    }

    /// Get the number of tables.
    pub fn table_count(&self) -> usize {
        self.document.body.tables().count()
    }

    // ---- Content insertion ----

    /// Get the number of body content elements (paragraphs + tables).
    pub fn content_count(&self) -> usize {
        self.document.body.content_count()
    }

    /// Insert a paragraph at the given body index.
    ///
    /// Returns a mutable `Paragraph` for further configuration.
    /// # Panics
    ///
    /// Panics if `index > content_count()`. (Unlike [`Self::insert_document`]
    /// and [`Self::insert_toc`], which clamp an out-of-range index to the end.)
    pub fn insert_paragraph(&mut self, index: usize, text: &str) -> Paragraph<'_> {
        self.invalidate_layout();
        let mut p = CT_P::new();
        if !text.is_empty() {
            p.add_run(text);
        }
        self.document.body.insert_paragraph(index, p);
        match &mut self.document.body.content[index] {
            BodyContent::Paragraph(p) => Paragraph { inner: p },
            _ => unreachable!(),
        }
    }

    /// Insert a table at the given body index.
    ///
    /// Returns a mutable `Table` for further configuration.
    /// A `cols` of 0 produces a table with no columns rather than panicking.
    ///
    /// # Panics
    ///
    /// Panics if `index > content_count()`. (Unlike [`Self::insert_document`]
    /// and [`Self::insert_toc`], which clamp an out-of-range index to the end.)
    pub fn insert_table(&mut self, index: usize, rows: usize, cols: usize) -> Table<'_> {
        self.invalidate_layout();
        use rdocx_oxml::table::{CT_Row, CT_TblGrid, CT_TblGridCol, CT_TblPr, CT_TblWidth, CT_Tc};
        use rdocx_oxml::units::Twips;

        let col_width = Twips(9360 / cols.max(1) as i32);
        let grid = CT_TblGrid {
            columns: (0..cols)
                .map(|_| CT_TblGridCol { width: col_width })
                .collect(),
        };

        let mut tbl = CT_Tbl::new();
        tbl.properties = Some(CT_TblPr {
            width: Some(CT_TblWidth::dxa(col_width.0 * cols as i32)),
            ..Default::default()
        });
        tbl.grid = Some(grid);

        for _ in 0..rows {
            let mut row = CT_Row::new();
            for _ in 0..cols {
                row.cells.push(CT_Tc::new());
            }
            tbl.rows.push(row);
        }

        self.document.body.insert_table(index, tbl);
        match &mut self.document.body.content[index] {
            BodyContent::Table(t) => Table { inner: t },
            _ => unreachable!(),
        }
    }

    /// Find the body content index of the first paragraph containing the given text.
    pub fn find_content_index(&self, text: &str) -> Option<usize> {
        self.document.body.find_paragraph_index(text)
    }

    /// Remove the content at the given body index.
    ///
    /// Returns `true` if an element was removed, `false` if the index was out of bounds.
    pub fn remove_content(&mut self, index: usize) -> bool {
        self.invalidate_layout();
        self.document.body.remove(index).is_some()
    }

    // ---- Image support ----

    /// Add an inline image to the document.
    ///
    /// Embeds the image data (PNG, JPEG, etc.) into the package and adds a
    /// paragraph containing the image. Returns a mutable reference to the
    /// paragraph for further configuration.
    ///
    /// `width` and `height` specify the display size.
    pub fn add_picture(
        &mut self,
        image_data: &[u8],
        image_filename: &str,
        width: Length,
        height: Length,
    ) -> Paragraph<'_> {
        self.invalidate_layout();
        let rel_id = self.embed_image(image_data, image_filename);

        let inline = CT_Inline::new(&rel_id, width.to_emu(), height.to_emu());

        let drawing = CT_Drawing::inline(inline);
        let run = CT_R {
            alt_drawings: Vec::new(),
            properties: None,
            content: vec![RunContent::Drawing(drawing)],
            extra_xml: Vec::new(),
        };

        let mut p = CT_P::new();
        p.runs.push(run);
        self.document.body.content.push(BodyContent::Paragraph(p));
        match self.document.body.content.last_mut().unwrap() {
            BodyContent::Paragraph(p) => Paragraph { inner: p },
            _ => unreachable!(),
        }
    }

    /// Add an inline image at its native size using 72 DPI when none is declared.
    ///
    /// Returns an error without changing the document when the image dimensions
    /// cannot be determined.
    pub fn add_picture_auto(
        &mut self,
        image_data: &[u8],
        image_filename: &str,
    ) -> Result<Paragraph<'_>> {
        let native_size = oxml_media::probe(image_data)
            .and_then(|info| info.native_size(72.0))
            .ok_or_else(|| Error::UnavailableImageDimensions {
                filename: image_filename.to_owned(),
            })?;

        Ok(self.add_picture(
            image_data,
            image_filename,
            Length::emu(native_size.width_emu),
            Length::emu(native_size.height_emu),
        ))
    }

    /// Add a full-page background image behind text.
    ///
    /// The image is placed at position (0,0) relative to the page with
    /// dimensions matching the page size from section properties.
    /// It is inserted at the beginning of the document body so it renders
    /// behind all other content.
    pub fn add_background_image(
        &mut self,
        image_data: &[u8],
        image_filename: &str,
    ) -> Paragraph<'_> {
        self.invalidate_layout();
        let rel_id = self.embed_image(image_data, image_filename);

        // Get page dimensions from section properties (default US Letter)
        let sect = self
            .document
            .body
            .sect_pr
            .as_ref()
            .cloned()
            .unwrap_or_else(CT_SectPr::default_letter);
        let page_width_emu = sect
            .page_width
            .unwrap_or(rdocx_oxml::units::Twips(12240))
            .to_emu()
            .0;
        let page_height_emu = sect
            .page_height
            .unwrap_or(rdocx_oxml::units::Twips(15840))
            .to_emu()
            .0;

        let anchor = CT_Anchor::background(&rel_id, page_width_emu, page_height_emu);
        let drawing = CT_Drawing::anchor(anchor);
        let run = CT_R {
            alt_drawings: Vec::new(),
            properties: None,
            content: vec![RunContent::Drawing(drawing)],
            extra_xml: Vec::new(),
        };

        let mut p = CT_P::new();
        p.runs.push(run);
        self.document.body.insert_paragraph(0, p);
        match &mut self.document.body.content[0] {
            BodyContent::Paragraph(p) => Paragraph { inner: p },
            _ => unreachable!(),
        }
    }

    /// Add an anchored (floating) image to the document.
    ///
    /// If `behind_text` is true, the image renders behind text content.
    /// The image is inserted at the beginning of the document body.
    pub fn add_anchored_image(
        &mut self,
        image_data: &[u8],
        image_filename: &str,
        width: Length,
        height: Length,
        behind_text: bool,
    ) -> Paragraph<'_> {
        self.invalidate_layout();
        let rel_id = self.embed_image(image_data, image_filename);

        let mut anchor = CT_Anchor::background(&rel_id, width.to_emu(), height.to_emu());
        anchor.behind_doc = behind_text;

        let drawing = CT_Drawing::anchor(anchor);
        let run = CT_R {
            alt_drawings: Vec::new(),
            properties: None,
            content: vec![RunContent::Drawing(drawing)],
            extra_xml: Vec::new(),
        };

        let mut p = CT_P::new();
        p.runs.push(run);
        self.document.body.insert_paragraph(0, p);
        match &mut self.document.body.content[0] {
            BodyContent::Paragraph(p) => Paragraph { inner: p },
            _ => unreachable!(),
        }
    }

    /// Store image bytes as a new media part and declare its content type.
    ///
    /// Returns the relationship target to use when referencing it, e.g.
    /// `media/image3.png`. No relationship is created here: an image referenced
    /// from a header or footer must be related to *that* part, not the
    /// document, so the caller decides where it is attached.
    fn store_image_part(&mut self, image_data: &[u8], filename: &str) -> String {
        let format = oxml_media::resolve(image_data, filename);
        let extension = format.extension();
        let part_name = self.image_namer.next_part_name(extension);

        self.package.set_part(&part_name, image_data.to_vec());
        let content_type = format.content_type();
        match self.package.content_types.content_type_for(&part_name) {
            Some(existing) if existing == content_type => {}
            Some(_) => self
                .package
                .content_types
                .add_override(&part_name, content_type),
            None => self
                .package
                .content_types
                .add_default(extension, content_type),
        }

        part_name
            .strip_prefix("/word/")
            .unwrap_or(&part_name)
            .to_owned()
    }

    /// Embed an image into the OPC package and return the relationship ID.
    ///
    /// Public so callers can pre-embed an image and then pass the returned
    /// `rel_id` to [`crate::Cell::add_picture`] for inline cell images.
    pub fn embed_image(&mut self, image_data: &[u8], filename: &str) -> String {
        self.invalidate_layout();
        let rel_target = self.store_image_part(image_data, filename);
        self.package
            .get_or_create_part_rels(&self.doc_part_name)
            .add(rel_types::IMAGE, &rel_target)
    }

    /// Whether the given numbering definition renders as bullets (true)
    /// or numbers (false). None if the id is unknown.
    pub fn numbering_is_bullet(&self, num_id: u32) -> Option<bool> {
        let numbering = self.numbering.as_ref()?;
        let abstract_num = numbering.get_abstract_num_for(num_id)?;
        let fmt = abstract_num.levels.first()?.num_fmt?;
        Some(fmt == rdocx_oxml::numbering::ST_NumberFormat::Bullet)
    }

    /// Append an external hyperlink to the last paragraph (creating one if
    /// the document is empty): adds the External relationship and wraps the
    /// new run in a hyperlink span.
    pub fn append_hyperlink(&mut self, text: &str, url: &str) {
        let rel_id = self.add_hyperlink_relationship(url);

        if !matches!(
            self.document.body.content.last(),
            Some(BodyContent::Paragraph(_))
        ) {
            self.document
                .body
                .content
                .push(BodyContent::Paragraph(CT_P::new()));
        }
        let Some(BodyContent::Paragraph(p)) = self.document.body.content.last_mut() else {
            unreachable!();
        };
        crate::Paragraph { inner: p }.add_hyperlink(text, &rel_id);
    }

    /// Add an external hyperlink relationship and return its relationship ID.
    ///
    /// Use this with [`crate::Paragraph::add_hyperlink`] when the target
    /// paragraph is not the last body paragraph, such as a paragraph inside a
    /// table cell.
    pub fn add_hyperlink_relationship(&mut self, url: &str) -> String {
        self.invalidate_layout();
        self.package
            .get_or_create_part_rels(&self.doc_part_name)
            .add_external(rel_types::HYPERLINK, url)
    }

    /// Get a builder for the last paragraph in the body, if any. Lets
    /// callers interleave plain runs with `append_hyperlink` calls.
    pub fn last_paragraph_mut(&mut self) -> Option<Paragraph<'_>> {
        self.invalidate_layout();
        match self.document.body.content.last_mut() {
            Some(BodyContent::Paragraph(p)) => Some(Paragraph { inner: p }),
            _ => None,
        }
    }

    /// Fetch the raw bytes of an embedded image by its relationship ID.
    pub fn image_data(&self, rel_id: &str) -> Option<Vec<u8>> {
        let rels = self.package.get_part_rels(&self.doc_part_name)?;
        let rel = rels.items.iter().find(|r| r.id == rel_id)?;
        let target = OpcPackage::resolve_rel_target(&self.doc_part_name, &rel.target);
        self.package.get_part(&target).map(|b| b.to_vec())
    }

    /// Resolve a hyperlink relationship ID to its external URL.
    pub fn hyperlink_url(&self, rel_id: &str) -> Option<String> {
        use oxml_opc::relationship::rel_types;
        let rels = self.package.get_part_rels(&self.doc_part_name)?;
        rels.items
            .iter()
            .find(|r| r.id == rel_id && r.rel_type == rel_types::HYPERLINK)
            .map(|r| r.target.clone())
    }

    // ---- Header/Footer ----

    /// Set the default header text.
    ///
    /// Creates a header part with the given text and references it from
    /// the section properties.
    pub fn set_header(&mut self, text: &str) {
        self.invalidate_layout();
        self.set_header_footer_part(text, true, HdrFtrType::Default);
    }

    /// Set the default footer text.
    pub fn set_footer(&mut self, text: &str) {
        self.invalidate_layout();
        self.set_header_footer_part(text, false, HdrFtrType::Default);
    }

    /// Set the first-page header text.
    pub fn set_first_page_header(&mut self, text: &str) {
        self.invalidate_layout();
        self.set_different_first_page(true);
        self.set_header_footer_part(text, true, HdrFtrType::First);
    }

    /// Set the first-page footer text.
    pub fn set_first_page_footer(&mut self, text: &str) {
        self.invalidate_layout();
        self.set_different_first_page(true);
        self.set_header_footer_part(text, false, HdrFtrType::First);
    }

    /// Get the default header text, if set.
    pub fn header_text(&self) -> Option<String> {
        self.get_header_footer_text(true, HdrFtrType::Default)
    }

    /// Get the default footer text, if set.
    pub fn footer_text(&self) -> Option<String> {
        self.get_header_footer_text(false, HdrFtrType::Default)
    }

    /// Set the default header to an inline image.
    ///
    /// Creates a header part with an image paragraph. The image is embedded
    /// in the header part's relationships.
    pub fn set_header_image(
        &mut self,
        image_data: &[u8],
        image_filename: &str,
        width: Length,
        height: Length,
    ) {
        self.invalidate_layout();
        self.set_header_footer_image_part(
            image_data,
            image_filename,
            width,
            height,
            true,
            HdrFtrType::Default,
        );
    }

    /// Set the default footer to an inline image.
    pub fn set_footer_image(
        &mut self,
        image_data: &[u8],
        image_filename: &str,
        width: Length,
        height: Length,
    ) {
        self.invalidate_layout();
        self.set_header_footer_image_part(
            image_data,
            image_filename,
            width,
            height,
            false,
            HdrFtrType::Default,
        );
    }

    /// Set a header from raw XML bytes with associated images.
    ///
    /// This is useful for copying complex headers from template documents
    /// that contain grouped shapes, VML, or other elements not easily
    /// recreated through the high-level API.
    ///
    /// Each entry in `images` is `(rel_id, image_data, image_filename)`:
    /// - `rel_id`: the relationship ID referenced in the header XML (e.g. "rId1")
    /// - `image_data`: the raw image bytes
    /// - `image_filename`: used to derive the part name and content type (e.g. "image5.png")
    pub fn set_raw_header_with_images(
        &mut self,
        header_xml: Vec<u8>,
        images: &[(&str, &[u8], &str)],
        hdr_type: HdrFtrType,
    ) {
        self.invalidate_layout();
        self.set_raw_hdr_ftr_with_images(header_xml, images, true, hdr_type);
    }

    /// Set a footer from raw XML bytes with associated images.
    pub fn set_raw_footer_with_images(
        &mut self,
        footer_xml: Vec<u8>,
        images: &[(&str, &[u8], &str)],
        hdr_type: HdrFtrType,
    ) {
        self.invalidate_layout();
        self.set_raw_hdr_ftr_with_images(footer_xml, images, false, hdr_type);
    }

    /// Set the default header to an inline image with a colored background.
    ///
    /// Creates a header part where the paragraph has shading fill set to
    /// `bg_color` (hex string, e.g. "000000" for black) and contains the
    /// inline image.
    pub fn set_header_image_with_background(
        &mut self,
        image_data: &[u8],
        image_filename: &str,
        width: Length,
        height: Length,
        bg_color: &str,
    ) {
        self.invalidate_layout();
        self.set_header_footer_image_bg_part(
            image_data,
            image_filename,
            width,
            height,
            Some(bg_color),
            true,
            HdrFtrType::Default,
        );
    }

    /// Set the first-page header to an inline image.
    pub fn set_first_page_header_image(
        &mut self,
        image_data: &[u8],
        image_filename: &str,
        width: Length,
        height: Length,
    ) {
        self.invalidate_layout();
        self.set_different_first_page(true);
        self.set_header_footer_image_part(
            image_data,
            image_filename,
            width,
            height,
            true,
            HdrFtrType::First,
        );
    }

    /// Where a header/footer of this kind lives, and how to declare it.
    ///
    /// All four public entry points differ only in what goes *inside* the part;
    /// the surrounding bookkeeping — part name, content type, relationship,
    /// section reference — is identical, and lives here.
    ///
    /// Note the fixed `1` in the part name: rdocx manages one header and one
    /// footer per [`HdrFtrType`] for the document's single section. Setting a
    /// header of the same type again replaces the existing part.
    fn hdr_ftr_slots(
        is_header: bool,
        hdr_type: HdrFtrType,
    ) -> (String, &'static str, &'static str) {
        let type_suffix = match hdr_type {
            HdrFtrType::Default => "",
            HdrFtrType::First => "First",
            HdrFtrType::Even => "Even",
        };
        if is_header {
            (
                format!("/word/header{type_suffix}1.xml"),
                rel_types::HEADER,
                "application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml",
            )
        } else {
            (
                format!("/word/footer{type_suffix}1.xml"),
                rel_types::FOOTER,
                "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml",
            )
        }
    }

    /// Install a header/footer part: store its bytes, declare the content type,
    /// relate it to the document, and point the section properties at it.
    ///
    /// Any previous reference of the same [`HdrFtrType`] is replaced.
    fn install_hdr_ftr_part(
        &mut self,
        xml: Vec<u8>,
        is_header: bool,
        hdr_type: HdrFtrType,
    ) -> String {
        let (part_name, rel_type, content_type) = Self::hdr_ftr_slots(is_header, hdr_type);

        self.package.set_part(&part_name, xml);
        self.package
            .content_types
            .add_override(&part_name, content_type);

        // Setting the same header twice must not leave the first relationship
        // behind pointing at the same part.
        let rel_target = relative_target(&self.doc_part_name, &part_name);
        let rels = self.package.get_or_create_part_rels(&self.doc_part_name);
        let rel_id = match rels
            .items
            .iter()
            .find(|r| r.rel_type == rel_type && r.target == rel_target)
        {
            Some(existing) => existing.id.clone(),
            None => rels.add(rel_type, &rel_target),
        };

        let sect = self.section_properties_mut();
        let refs = if is_header {
            &mut sect.header_refs
        } else {
            &mut sect.footer_refs
        };
        refs.retain(|r| r.hdr_ftr_type != hdr_type);
        refs.push(HdrFtrRef {
            hdr_ftr_type: hdr_type,
            rel_id,
        });

        part_name
    }

    /// Serialize a header/footer body, choosing the right root element.
    fn serialize_hdr_ftr(hdr_ftr: &CT_HdrFtr, is_header: bool) -> Result<Vec<u8>> {
        let xml = if is_header {
            hdr_ftr.to_xml_header()
        } else {
            hdr_ftr.to_xml_footer()
        };
        Ok(xml?)
    }

    fn set_header_footer_part(&mut self, text: &str, is_header: bool, hdr_type: HdrFtrType) {
        let mut hdr_ftr = CT_HdrFtr::new();
        let mut p = CT_P::new();
        if !text.is_empty() {
            p.add_run(text);
        }
        hdr_ftr.paragraphs.push(p);

        let Ok(xml) = Self::serialize_hdr_ftr(&hdr_ftr, is_header) else {
            return;
        };
        self.install_hdr_ftr_part(xml, is_header, hdr_type);
    }

    fn set_raw_hdr_ftr_with_images(
        &mut self,
        xml: Vec<u8>,
        images: &[(&str, &[u8], &str)],
        is_header: bool,
        hdr_type: HdrFtrType,
    ) {
        let part_name = self.install_hdr_ftr_part(xml, is_header, hdr_type);

        // The supplied markup already references these images by ID, so each
        // relationship has to be created with that exact ID.
        for &(rel_id, image_data, image_filename) in images {
            let img_rel_target = self.store_image_part(image_data, image_filename);
            self.package
                .get_or_create_part_rels(&part_name)
                .add_with_id(rel_id, rel_types::IMAGE, &img_rel_target);
        }
    }

    fn set_header_footer_image_part(
        &mut self,
        image_data: &[u8],
        image_filename: &str,
        width: Length,
        height: Length,
        is_header: bool,
        hdr_type: HdrFtrType,
    ) {
        self.set_header_footer_image_bg_part(
            image_data,
            image_filename,
            width,
            height,
            None,
            is_header,
            hdr_type,
        );
    }

    fn set_header_footer_image_bg_part(
        &mut self,
        image_data: &[u8],
        image_filename: &str,
        width: Length,
        height: Length,
        bg_color: Option<&str>,
        is_header: bool,
        hdr_type: HdrFtrType,
    ) {
        use rdocx_oxml::properties::CT_Shd;

        let (part_name, _, _) = Self::hdr_ftr_slots(is_header, hdr_type);

        // The image relationship belongs to the header/footer part, not the
        // document, because that is where the drawing referencing it lives.
        let img_rel_target = self.store_image_part(image_data, image_filename);
        let img_rel_id = self
            .package
            .get_or_create_part_rels(&part_name)
            .add(rel_types::IMAGE, &img_rel_target);

        let inline = CT_Inline::new(&img_rel_id, width.to_emu(), height.to_emu());
        let run = CT_R {
            alt_drawings: Vec::new(),
            properties: None,
            content: vec![RunContent::Drawing(CT_Drawing::inline(inline))],
            extra_xml: Vec::new(),
        };

        let mut p = CT_P::new();
        p.runs.push(run);
        if let Some(color) = bg_color {
            p.properties = Some(CT_PPr {
                shading: Some(CT_Shd {
                    val: "clear".to_string(),
                    color: Some("auto".to_string()),
                    fill: Some(color.to_string()),
                }),
                ..Default::default()
            });
        }

        let mut hdr_ftr = CT_HdrFtr::new();
        hdr_ftr.paragraphs.push(p);

        let Ok(xml) = Self::serialize_hdr_ftr(&hdr_ftr, is_header) else {
            return;
        };
        self.install_hdr_ftr_part(xml, is_header, hdr_type);
    }

    fn get_header_footer_text(&self, is_header: bool, hdr_type: HdrFtrType) -> Option<String> {
        let sect = self.document.body.sect_pr.as_ref()?;
        let refs = if is_header {
            &sect.header_refs
        } else {
            &sect.footer_refs
        };
        let hdr_ref = refs.iter().find(|r| r.hdr_ftr_type == hdr_type)?;

        // Resolve the part
        let rels = self.package.get_part_rels(&self.doc_part_name)?;
        let rel = rels.get_by_id(&hdr_ref.rel_id)?;
        let part_name = OpcPackage::resolve_rel_target(&self.doc_part_name, &rel.target);
        let xml = self.package.get_part(&part_name)?;
        let hdr_ftr = CT_HdrFtr::from_xml(xml).ok()?;
        Some(hdr_ftr.text())
    }

    // ---- Numbering/Lists ----

    /// Ensure a numbering part exists.
    ///
    /// The relationship and content-type override are added by
    /// [`Self::flush_to_package`], which knows the resolved part name and will
    /// not create a second numbering relationship if one already exists.
    fn ensure_numbering(&mut self) -> &mut CT_Numbering {
        self.numbering.get_or_insert_with(CT_Numbering::new)
    }

    /// Add a bullet list item at the given indentation level (0-based).
    ///
    /// If no bullet list definition exists yet, one is created automatically.
    /// Returns a mutable `Paragraph` for further configuration.
    pub fn add_bullet_list_item(&mut self, text: &str, level: u32) -> Paragraph<'_> {
        self.invalidate_layout();
        // Find or create a bullet list numId
        let num_id = {
            let numbering = self.ensure_numbering();
            // Look for an existing bullet list
            let existing = numbering.nums.iter().find(|n| {
                numbering
                    .get_abstract_num_for(n.num_id)
                    .map(|a| {
                        a.levels.first().and_then(|l| l.num_fmt)
                            == Some(rdocx_oxml::numbering::ST_NumberFormat::Bullet)
                    })
                    .unwrap_or(false)
            });
            if let Some(existing) = existing {
                existing.num_id
            } else {
                numbering.add_bullet_list()
            }
        };

        let mut p = CT_P::new();
        if !text.is_empty() {
            p.add_run(text);
        }
        let ppr = CT_PPr {
            num_id: Some(num_id),
            num_ilvl: Some(level),
            ..Default::default()
        };
        p.properties = Some(ppr);

        self.document.body.content.push(BodyContent::Paragraph(p));
        match self.document.body.content.last_mut().unwrap() {
            BodyContent::Paragraph(p) => Paragraph { inner: p },
            _ => unreachable!(),
        }
    }

    /// Add a numbered list item at the given indentation level (0-based).
    ///
    /// If no numbered list definition exists yet, one is created automatically.
    /// Returns a mutable `Paragraph` for further configuration.
    pub fn add_numbered_list_item(&mut self, text: &str, level: u32) -> Paragraph<'_> {
        self.invalidate_layout();
        // Find or create a numbered list numId
        let num_id = {
            let numbering = self.ensure_numbering();
            // Look for an existing numbered list
            let existing = numbering.nums.iter().find(|n| {
                numbering
                    .get_abstract_num_for(n.num_id)
                    .map(|a| {
                        a.levels.first().and_then(|l| l.num_fmt)
                            == Some(rdocx_oxml::numbering::ST_NumberFormat::Decimal)
                    })
                    .unwrap_or(false)
            });
            if let Some(existing) = existing {
                existing.num_id
            } else {
                numbering.add_numbered_list()
            }
        };

        let mut p = CT_P::new();
        if !text.is_empty() {
            p.add_run(text);
        }
        let ppr = CT_PPr {
            num_id: Some(num_id),
            num_ilvl: Some(level),
            ..Default::default()
        };
        p.properties = Some(ppr);

        self.document.body.content.push(BodyContent::Paragraph(p));
        match self.document.body.content.last_mut().unwrap() {
            BodyContent::Paragraph(p) => Paragraph { inner: p },
            _ => unreachable!(),
        }
    }

    /// Create a list definition with explicit per-level formats and return
    /// its numId.
    ///
    /// Unlike [`Self::add_bullet_list_item`] / [`Self::add_numbered_list_item`],
    /// which share one bullet and one numbered definition per document, every
    /// call creates a fresh definition — so separate lists restart their
    /// numbering, and one definition can mix formats across levels (e.g. a
    /// bullet list whose nested level is decimal). Attach paragraphs with
    /// [`crate::Paragraph::set_numbering`].
    ///
    /// `levels[i]` configures level `i`; deeper unspecified levels fall back
    /// to the standard template rotation for the last specified format's
    /// family. An empty slice produces the standard numbered template. Word
    /// supports nine levels, so entries after index eight are ignored.
    ///
    /// ```no_run
    /// use rdocx::{Document, ListLevel};
    ///
    /// let mut doc = Document::new();
    /// let num_id = doc.add_list_definition(&[
    ///     ListLevel::bullet(),
    ///     ListLevel::decimal().start(3),
    /// ]);
    /// doc.add_paragraph("first bullet").set_numbering(num_id, 0);
    /// doc.add_paragraph("third decimal").set_numbering(num_id, 1);
    /// ```
    pub fn add_list_definition(&mut self, levels: &[ListLevel]) -> u32 {
        self.invalidate_layout();
        let levels: Vec<(ST_NumberFormat, Option<u32>)> = levels
            .iter()
            .take(9)
            .map(|level| (level.format.to_st(), level.start))
            .collect();
        self.ensure_numbering().add_list(&levels)
    }

    /// Redefine one level (0–8) of an existing list definition, for callers
    /// that only learn a deeper level's format when content first reaches it.
    ///
    /// Returns `false` when `num_id` is unknown or `level` is out of range.
    pub fn set_list_level(&mut self, num_id: u32, level: u32, spec: ListLevel) -> bool {
        let updated = self.numbering.as_mut().is_some_and(|numbering| {
            numbering.set_list_level(num_id, level, spec.format.to_st(), spec.start)
        });
        if updated {
            self.invalidate_layout();
        }
        updated
    }

    // ---- Style access ----

    /// Get all styles.
    pub fn styles(&self) -> Vec<Style<'_>> {
        self.styles
            .styles
            .iter()
            .map(|s| Style { inner: s })
            .collect()
    }

    /// Find a style by its ID.
    pub fn style(&self, style_id: &str) -> Option<Style<'_>> {
        self.styles.get_by_id(style_id).map(|s| Style { inner: s })
    }

    // ---- Style manipulation ----

    /// Add a custom style to the document.
    pub fn add_style(&mut self, builder: StyleBuilder) {
        self.invalidate_layout();
        self.styles.styles.push(builder.build());
    }

    /// Resolve the effective paragraph properties for a given style ID,
    /// walking the full inheritance chain (docDefaults → basedOn → ...).
    pub fn resolve_paragraph_properties(&self, style_id: Option<&str>) -> CT_PPr {
        style::resolve_paragraph_properties(style_id, &self.styles)
    }

    /// Resolve the effective run properties for the given paragraph and character styles,
    /// walking the full inheritance chain.
    pub fn resolve_run_properties(
        &self,
        para_style_id: Option<&str>,
        run_style_id: Option<&str>,
    ) -> CT_RPr {
        style::resolve_run_properties(para_style_id, run_style_id, &self.styles)
    }

    // ---- Section/Page setup ----

    /// Get the section properties (page size, margins).
    pub fn section_properties(&self) -> Option<&CT_SectPr> {
        self.document.body.sect_pr.as_ref()
    }

    /// Get a mutable reference to section properties, creating defaults if needed.
    pub fn section_properties_mut(&mut self) -> &mut CT_SectPr {
        self.invalidate_layout();
        self.document
            .body
            .sect_pr
            .get_or_insert_with(CT_SectPr::default_letter)
    }

    /// Set page size.
    pub fn set_page_size(&mut self, width: Length, height: Length) {
        let sect = self.section_properties_mut();
        sect.page_width = Some(width.as_twips());
        sect.page_height = Some(height.as_twips());
    }

    /// Set page orientation to landscape (swaps width and height if needed).
    pub fn set_landscape(&mut self) {
        let sect = self.section_properties_mut();
        sect.orientation = Some(ST_PageOrientation::Landscape);
        // Swap width/height if portrait dimensions
        if let (Some(w), Some(h)) = (sect.page_width, sect.page_height)
            && w.0 < h.0
        {
            sect.page_width = Some(h);
            sect.page_height = Some(w);
        }
    }

    /// Set page orientation to portrait (swaps width and height if needed).
    pub fn set_portrait(&mut self) {
        let sect = self.section_properties_mut();
        sect.orientation = Some(ST_PageOrientation::Portrait);
        // Swap width/height if landscape dimensions
        if let (Some(w), Some(h)) = (sect.page_width, sect.page_height)
            && w.0 > h.0
        {
            sect.page_width = Some(h);
            sect.page_height = Some(w);
        }
    }

    /// Set all page margins.
    pub fn set_margins(&mut self, top: Length, right: Length, bottom: Length, left: Length) {
        let sect = self.section_properties_mut();
        sect.margin_top = Some(top.as_twips());
        sect.margin_right = Some(right.as_twips());
        sect.margin_bottom = Some(bottom.as_twips());
        sect.margin_left = Some(left.as_twips());
    }

    /// Set equal-width column layout.
    pub fn set_columns(&mut self, num: u32, spacing: Length) {
        let sect = self.section_properties_mut();
        sect.columns = Some(CT_Columns {
            num: Some(num),
            space: Some(spacing.as_twips()),
            equal_width: Some(true),
            sep: None,
            columns: Vec::new(),
        });
    }

    /// Set header and footer distances from page edges.
    pub fn set_header_footer_distance(&mut self, header: Length, footer: Length) {
        let sect = self.section_properties_mut();
        sect.header_distance = Some(header.as_twips());
        sect.footer_distance = Some(footer.as_twips());
    }

    /// Set the gutter margin.
    pub fn set_gutter(&mut self, gutter: Length) {
        self.section_properties_mut().gutter = Some(gutter.as_twips());
    }

    /// Enable or disable different first page header/footer.
    pub fn set_different_first_page(&mut self, val: bool) {
        self.section_properties_mut().title_pg = Some(val);
    }

    // ---- Metadata access ----

    /// Get the document title.
    pub fn title(&self) -> Option<&str> {
        self.core_properties.as_ref()?.title.as_deref()
    }

    /// Set the document title.
    pub fn set_title(&mut self, title: &str) {
        self.invalidate_layout();
        self.ensure_core_properties().title = Some(title.to_string());
    }

    /// Get the document author/creator.
    pub fn author(&self) -> Option<&str> {
        self.core_properties.as_ref()?.creator.as_deref()
    }

    /// Set the document author/creator.
    pub fn set_author(&mut self, author: &str) {
        self.invalidate_layout();
        self.ensure_core_properties().creator = Some(author.to_string());
    }

    /// Get the document subject.
    pub fn subject(&self) -> Option<&str> {
        self.core_properties.as_ref()?.subject.as_deref()
    }

    /// Set the document subject.
    pub fn set_subject(&mut self, subject: &str) {
        self.invalidate_layout();
        self.ensure_core_properties().subject = Some(subject.to_string());
    }

    /// Get the document keywords.
    pub fn keywords(&self) -> Option<&str> {
        self.core_properties.as_ref()?.keywords.as_deref()
    }

    /// Set the document keywords.
    pub fn set_keywords(&mut self, keywords: &str) {
        self.invalidate_layout();
        self.ensure_core_properties().keywords = Some(keywords.to_string());
    }

    fn ensure_core_properties(&mut self) -> &mut CoreProperties {
        self.core_properties
            .get_or_insert_with(CoreProperties::default)
    }

    // ---- Document Merging ----

    /// Append the content of another document to this document.
    ///
    /// Copies all body content (paragraphs and tables) from the other document.
    /// Handles style deduplication and numbering remapping.
    pub fn append(&mut self, other: &Document) {
        self.invalidate_layout();
        self.merge_styles(other);

        let start_idx = self.document.body.content.len();
        for content in &other.document.body.content {
            self.document.body.content.push(content.clone());
        }

        self.remap_merged_numbering(other, start_idx);
    }

    /// Append the content of another document with a section break.
    pub fn append_with_break(&mut self, other: &Document, break_type: crate::SectionBreak) {
        self.invalidate_layout();
        // Insert a section break paragraph before the merged content
        let mut p = CT_P::new();
        let sect_pr = match break_type {
            crate::SectionBreak::NextPage => CT_SectPr::default_letter(),
            crate::SectionBreak::Continuous => {
                let mut sp = CT_SectPr::default_letter();
                sp.section_type = Some(ST_SectionType::Continuous);
                sp
            }
            crate::SectionBreak::EvenPage => {
                let mut sp = CT_SectPr::default_letter();
                sp.section_type = Some(ST_SectionType::EvenPage);
                sp
            }
            crate::SectionBreak::OddPage => {
                let mut sp = CT_SectPr::default_letter();
                sp.section_type = Some(ST_SectionType::OddPage);
                sp
            }
        };
        p.properties = Some(CT_PPr {
            sect_pr: Some(sect_pr),
            ..Default::default()
        });
        self.document.body.content.push(BodyContent::Paragraph(p));

        self.append(other);
    }

    /// Insert the content of another document at a specified body index.
    ///
    /// An `index` past the end is clamped to the end rather than panicking.
    pub fn insert_document(&mut self, index: usize, other: &Document) {
        self.invalidate_layout();
        self.merge_styles(other);

        let insert_at = index.min(self.document.body.content.len());
        for (i, content) in other.document.body.content.iter().enumerate() {
            self.document
                .body
                .content
                .insert(insert_at + i, content.clone());
        }

        self.remap_merged_numbering(other, insert_at);
    }

    /// Merge styles from another document, avoiding duplicates.
    fn merge_styles(&mut self, other: &Document) {
        for style in &other.styles.styles {
            if self.styles.get_by_id(&style.style_id).is_none() {
                self.styles.styles.push(style.clone());
            }
        }
    }

    /// Merge numbering from another document and remap IDs in the merged content.
    /// `start_idx` is the index where the other document's content starts in self.
    fn remap_merged_numbering(&mut self, other: &Document, start_idx: usize) {
        let Some(other_numbering) = &other.numbering else {
            return;
        };

        let numbering = self
            .numbering
            .get_or_insert_with(|| rdocx_oxml::numbering::CT_Numbering {
                abstract_nums: Vec::new(),
                nums: Vec::new(),
                root_attributes: Vec::new(),
                extra_xml: Vec::new(),
            });

        // Find max existing IDs to avoid collision
        let max_abstract_id = numbering
            .abstract_nums
            .iter()
            .map(|a| a.abstract_num_id)
            .max()
            .unwrap_or(0);
        let max_num_id = numbering.nums.iter().map(|n| n.num_id).max().unwrap_or(0);

        let abstract_offset = max_abstract_id + 1;
        let num_offset = max_num_id + 1;

        // Copy abstract nums with remapped IDs
        for abs_num in &other_numbering.abstract_nums {
            let mut new_abs = abs_num.clone();
            new_abs.abstract_num_id += abstract_offset;
            numbering.abstract_nums.push(new_abs);
        }

        // Copy num instances with remapped IDs
        for num in &other_numbering.nums {
            let mut new_num = num.clone();
            new_num.num_id += num_offset;
            new_num.abstract_num_id += abstract_offset;
            numbering.nums.push(new_num);
        }

        // Remap numId references in the merged content
        let incoming_count = other.document.body.content.len();
        for content in self.document.body.content[start_idx..start_idx + incoming_count].iter_mut()
        {
            Self::remap_num_ids(content, num_offset);
        }
    }

    /// Remap numId references in body content by adding an offset.
    fn remap_num_ids(content: &mut BodyContent, offset: u32) {
        match content {
            BodyContent::Paragraph(p) => {
                Self::remap_paragraph_num_id(p, offset);
            }
            BodyContent::Table(tbl) => {
                Self::remap_table_num_ids(tbl, offset);
            }
            BodyContent::RawXml(_) => {}
        }
    }

    fn remap_paragraph_num_id(p: &mut CT_P, offset: u32) {
        if let Some(ppr) = &mut p.properties
            && let Some(num_id) = &mut ppr.num_id
            && *num_id > 0
        {
            *num_id += offset;
        }
    }

    fn remap_table_num_ids(tbl: &mut CT_Tbl, offset: u32) {
        for row in &mut tbl.rows {
            for cell in &mut row.cells {
                for cc in &mut cell.content {
                    match cc {
                        rdocx_oxml::table::CellContent::Paragraph(p) => {
                            Self::remap_paragraph_num_id(p, offset);
                        }
                        rdocx_oxml::table::CellContent::Table(nested) => {
                            Self::remap_table_num_ids(nested, offset);
                        }
                    }
                }
            }
        }
    }

    // ---- Table of Contents ----

    /// Insert a Table of Contents at the given body content index.
    ///
    /// Scans the document for heading paragraphs (Heading1..HeadingN where N <= max_level),
    /// inserts bookmark markers at each heading, and generates TOC entry paragraphs
    /// with internal hyperlinks and dot-leader tab stops.
    ///
    /// # Arguments
    /// * `index` - Body content index at which to insert the TOC
    /// * `max_level` - Maximum heading level to include (1-9, typically 3)
    pub fn insert_toc(&mut self, index: usize, max_level: u32) {
        self.invalidate_layout();
        use rdocx_oxml::borders::{CT_TabStop, CT_Tabs};
        use rdocx_oxml::shared::{ST_TabJc, ST_TabLeader};
        use rdocx_oxml::text::HyperlinkSpan;
        use rdocx_oxml::units::Twips;

        let max_level = max_level.clamp(1, 9);

        // Step 1: Collect heading info from the document body
        struct HeadingInfo {
            content_index: usize,
            level: u32,
            text: String,
            bookmark_name: String,
        }

        // Calling insert_toc twice must not mint bookmarks that collide with
        // the ones the first call left behind — duplicate `w:name` values make
        // the internal links ambiguous. Continue numbering past whatever is
        // already there.
        let mut toc_counter = self.highest_toc_bookmark();
        let mut bookmark_id = 100 + toc_counter;

        let mut headings = Vec::new();

        for (idx, content) in self.document.body.content.iter().enumerate() {
            if let BodyContent::Paragraph(p) = content
                && let Some(level) = Self::detect_heading_level_for_toc(p)
                && level <= max_level
            {
                let text = p.text();
                if !text.trim().is_empty() {
                    toc_counter += 1;
                    headings.push(HeadingInfo {
                        content_index: idx,
                        level,
                        text,
                        bookmark_name: format!("_Toc{toc_counter}"),
                    });
                }
            }
        }

        // Step 2: Insert bookmark markers at each heading paragraph (as raw XML in extra_xml)
        // We insert bookmarkStart/bookmarkEnd as extra_xml at position 0 in the paragraph.
        for heading in &headings {
            if let Some(BodyContent::Paragraph(p)) =
                self.document.body.content.get_mut(heading.content_index)
            {
                let bm_start = format!(
                    "<w:bookmarkStart w:id=\"{bookmark_id}\" w:name=\"{}\"/>",
                    heading.bookmark_name
                );
                let bm_end = format!("<w:bookmarkEnd w:id=\"{bookmark_id}\"/>");
                // Insert at position 0 (before runs)
                p.extra_xml.push((0, bm_start.into_bytes()));
                // Insert at end (after runs)
                p.extra_xml.push((p.runs.len(), bm_end.into_bytes()));
                bookmark_id += 1;
            }
        }

        // Step 3: Build TOC entry paragraphs.
        // The dot leader runs to the right text margin, which depends on the
        // section's page size and margins rather than being a fixed 6.5".
        let right_tab = CT_Tabs {
            tabs: vec![CT_TabStop {
                val: ST_TabJc::Right,
                pos: Twips(self.text_width_twips()),
                leader: Some(ST_TabLeader::Dot),
                source_occurrence: None,
            }],
        };

        let mut toc_paragraphs: Vec<CT_P> = Vec::new();

        // TOC title
        let mut title_p = CT_P::new();
        let mut title_r = CT_R::new("Table of Contents");
        title_r.properties = Some(CT_RPr {
            bold: Some(true),
            ..Default::default()
        });
        title_p.runs.push(title_r);
        title_p.properties = Some(CT_PPr {
            space_after: Some(Twips(120)),
            ..Default::default()
        });
        toc_paragraphs.push(title_p);

        for heading in &headings {
            let mut p = CT_P::new();

            // Indentation based on heading level (each level indented 360 twips = 0.25")
            let indent = Twips(360 * (heading.level as i32 - 1));

            p.properties = Some(CT_PPr {
                tabs: Some(right_tab.clone()),
                ind_left: if indent.0 > 0 { Some(indent) } else { None },
                ..Default::default()
            });

            // Run with heading text
            let text_run = CT_R::new(&heading.text);
            p.runs.push(text_run);

            // Tab run (separates text from page number)
            p.runs.push(CT_R {
                alt_drawings: Vec::new(),
                properties: None,
                content: vec![rdocx_oxml::text::RunContent::Tab],
                extra_xml: Vec::new(),
            });

            // Wrap the text run in a hyperlink to the bookmark
            p.hyperlinks.push(HyperlinkSpan {
                rel_id: None,
                anchor: Some(heading.bookmark_name.clone()),
                run_start: 0,
                run_end: 1, // Just the text run, not the tab
            });

            toc_paragraphs.push(p);
        }

        // Step 4: Insert TOC paragraphs at the specified index
        let insert_at = index.min(self.document.body.content.len());
        for (i, p) in toc_paragraphs.into_iter().enumerate() {
            self.document
                .body
                .content
                .insert(insert_at + i, BodyContent::Paragraph(p));
        }
    }

    /// The highest `_TocN` bookmark number already present in the body.
    ///
    /// Returns 0 when there are none, so the next bookmark is `_Toc1`.
    fn highest_toc_bookmark(&self) -> u32 {
        let mut highest = 0;
        for content in &self.document.body.content {
            let BodyContent::Paragraph(p) = content else {
                continue;
            };
            for (_, raw) in &p.extra_xml {
                let Ok(text) = std::str::from_utf8(raw) else {
                    continue;
                };
                for (_, after) in text.match_indices("_Toc") {
                    let digits: String = after
                        .trim_start_matches("_Toc")
                        .chars()
                        .take_while(char::is_ascii_digit)
                        .collect();
                    if let Ok(n) = digits.parse::<u32>() {
                        highest = highest.max(n);
                    }
                }
            }
        }
        highest
    }

    /// Width of the text column in twips: page width less both side margins.
    ///
    /// Falls back to the US Letter default (6.5") when the section does not
    /// specify a size, and never returns a non-positive width.
    fn text_width_twips(&self) -> i32 {
        const DEFAULT_TEXT_WIDTH: i32 = 9360;

        let Some(sect) = self.document.body.sect_pr.as_ref() else {
            return DEFAULT_TEXT_WIDTH;
        };
        let page_width = sect.page_width.map(|w| w.0).unwrap_or(12240);
        let left = sect.margin_left.map(|m| m.0).unwrap_or(1440);
        let right = sect.margin_right.map(|m| m.0).unwrap_or(1440);

        let width = page_width - left - right;
        if width > 0 { width } else { DEFAULT_TEXT_WIDTH }
    }

    /// Detect heading level from a paragraph's style ID.
    fn detect_heading_level_for_toc(para: &CT_P) -> Option<u32> {
        let ppr = para.properties.as_ref()?;
        let style_id = ppr.style_id.as_deref()?;
        let rest = style_id.strip_prefix("Heading")?;
        rest.parse::<u32>().ok().filter(|n| (1..=9).contains(n))
    }

    // ---- Placeholder replacement ----

    /// Replace all occurrences of `placeholder` with `replacement` throughout the document.
    ///
    /// Searches body paragraphs, tables (including nested), headers, footers,
    /// text boxes and chart labels. Handles placeholders split across multiple
    /// runs. Returns the total number of replacements made.
    ///
    /// A `replacement` that contains `placeholder` is substituted once, not
    /// repeatedly.
    pub fn replace_text(&mut self, placeholder: &str, replacement: &str) -> usize {
        self.invalidate_layout();
        self.replace_batch(&[(placeholder, replacement)])
    }

    /// Replace multiple placeholders at once. Returns total replacements.
    ///
    /// Cheaper than calling [`Self::replace_text`] per entry: the document is
    /// serialised and re-parsed once for the whole batch rather than once per
    /// placeholder.
    pub fn replace_all(&mut self, replacements: &std::collections::HashMap<&str, &str>) -> usize {
        self.invalidate_layout();
        let pairs: Vec<(&str, &str)> = replacements.iter().map(|(k, v)| (*k, *v)).collect();
        self.replace_batch(&pairs)
    }

    /// Apply a batch of literal replacements across the whole document.
    fn replace_batch(&mut self, pairs: &[(&str, &str)]) -> usize {
        if pairs.is_empty() {
            return 0;
        }

        let mut count = 0;

        // Typed model: body content, then headers and footers.
        for (placeholder, replacement) in pairs {
            count += self.replace_in_body(placeholder, replacement);
        }
        count += self.replace_in_headers_footers(pairs);

        // Raw XML: text boxes, shapes and charts live in markup the typed model
        // does not cover, so flush first and work on the serialised parts.
        if self.flush_to_package().is_ok() {
            count += self.replace_in_xml_parts(pairs);
        }

        count
    }

    /// Run the typed replacement over body paragraphs and tables.
    fn replace_in_body(&mut self, placeholder: &str, replacement: &str) -> usize {
        use rdocx_oxml::placeholder;

        let mut count = 0;
        for content in &mut self.document.body.content {
            match content {
                BodyContent::Paragraph(p) => {
                    count += placeholder::replace_in_paragraph(p, placeholder, replacement);
                }
                BodyContent::Table(t) => {
                    count += placeholder::replace_in_table(t, placeholder, replacement);
                }
                BodyContent::RawXml(_) => {}
            }
        }
        count
    }

    /// Run the typed replacement over every referenced header and footer part.
    fn replace_in_headers_footers(&mut self, pairs: &[(&str, &str)]) -> usize {
        use rdocx_oxml::placeholder;

        let mut count = 0;
        for (rel_id, is_header) in self.header_footer_rel_ids() {
            let Some(mut hf) = self.load_header_footer(&rel_id) else {
                continue;
            };
            let mut part_count = 0;
            for (placeholder, replacement) in pairs {
                part_count +=
                    placeholder::replace_in_header_footer(&mut hf, placeholder, replacement);
            }
            if part_count > 0 {
                self.save_header_footer(&rel_id, &hf, is_header);
                count += part_count;
            }
        }
        count
    }

    /// Relationship IDs of the section's headers and footers, with a flag
    /// saying which kind each one is.
    fn header_footer_rel_ids(&self) -> Vec<(String, bool)> {
        let Some(sect_pr) = self.document.body.sect_pr.as_ref() else {
            return Vec::new();
        };
        sect_pr
            .header_refs
            .iter()
            .map(|r| (r.rel_id.clone(), true))
            .chain(
                sect_pr
                    .footer_refs
                    .iter()
                    .map(|r| (r.rel_id.clone(), false)),
            )
            .collect()
    }

    // ---- Regex replacement ----

    /// Replace all regex matches with `replacement` throughout the document.
    ///
    /// The `replacement` string supports capture groups: `$1`, `$2`, etc.
    /// Searches body paragraphs, tables (including nested), headers, and footers.
    /// Returns the total number of replacements made, or an error if the regex is invalid.
    pub fn replace_regex(&mut self, pattern: &str, replacement: &str) -> Result<usize> {
        self.invalidate_layout();
        let re =
            regex::Regex::new(pattern).map_err(|e| Error::Other(format!("invalid regex: {e}")))?;
        Ok(self.replace_regex_compiled(&re, replacement))
    }

    /// Replace multiple regex patterns at once. Returns total replacements.
    pub fn replace_all_regex(&mut self, patterns: &[(String, String)]) -> Result<usize> {
        self.invalidate_layout();
        let mut count = 0;
        for (pattern, replacement) in patterns {
            count += self.replace_regex(pattern, replacement)?;
        }
        Ok(count)
    }

    /// Internal: replace using a pre-compiled regex.
    fn replace_regex_compiled(&mut self, re: &regex::Regex, replacement: &str) -> usize {
        use rdocx_oxml::placeholder;

        let mut count = 0;

        // Replace in body paragraphs and tables
        for content in &mut self.document.body.content {
            match content {
                BodyContent::Paragraph(p) => {
                    count += placeholder::replace_regex_in_paragraph(p, re, replacement);
                }
                BodyContent::Table(t) => {
                    count += placeholder::replace_regex_in_table(t, re, replacement);
                }
                BodyContent::RawXml(_) => {}
            }
        }

        // Replace in headers and footers
        for (rel_id, is_header) in self.header_footer_rel_ids() {
            let Some(mut hf) = self.load_header_footer(&rel_id) else {
                continue;
            };
            let n = placeholder::replace_regex_in_header_footer(&mut hf, re, replacement);
            if n > 0 {
                self.save_header_footer(&rel_id, &hf, is_header);
                count += n;
            }
        }

        // Text boxes and shapes live in raw markup the typed model does not
        // reach. `replace_text` has always covered them; do the same here so
        // the two entry points search the same places.
        if self.flush_to_package().is_ok() {
            count += self.replace_regex_in_xml_parts(re, replacement);
        }

        count
    }

    /// Apply a regex replacement to the text-box content of the raw XML parts.
    fn replace_regex_in_xml_parts(&mut self, re: &regex::Regex, replacement: &str) -> usize {
        let mut count = 0;

        for part_name in self.text_bearing_part_names() {
            let Some(xml) = self.package.get_part(&part_name).map(<[u8]>::to_vec) else {
                continue;
            };
            if let Ok((new_xml, n)) =
                rdocx_oxml::placeholder::replace_regex_in_xml_part(&xml, re, replacement)
                && n > 0
            {
                self.package.set_part(&part_name, new_xml);
                count += n;
            }
        }

        // Re-parse so the in-memory model reflects the edited markup; otherwise
        // the next flush would write the pre-replacement document back out.
        if count > 0
            && let Some(doc_xml) = self.package.get_part(&self.doc_part_name)
            && let Ok(doc) = CT_Document::from_xml(doc_xml)
        {
            self.document = doc;
        }

        count
    }

    /// The main document part plus every header and footer part: everywhere
    /// text boxes and shapes with replaceable text can appear.
    fn text_bearing_part_names(&self) -> Vec<String> {
        let mut names = vec![self.doc_part_name.clone()];
        if let Some(rels) = self.package.get_part_rels(&self.doc_part_name) {
            for (rel_id, _) in self.header_footer_rel_ids() {
                if let Some(rel) = rels.get_by_id(&rel_id) {
                    names.push(OpcPackage::resolve_rel_target(
                        &self.doc_part_name,
                        &rel.target,
                    ));
                }
            }
        }
        names
    }

    /// Load a header/footer part by its relationship ID.
    fn load_header_footer(&self, rel_id: &str) -> Option<CT_HdrFtr> {
        let rels = self.package.get_part_rels(&self.doc_part_name)?;
        let rel = rels.get_by_id(rel_id)?;
        let part_name = OpcPackage::resolve_rel_target(&self.doc_part_name, &rel.target);
        let xml = self.package.get_part(&part_name)?;
        CT_HdrFtr::from_xml(xml).ok()
    }

    /// Run raw XML replacement on all XML parts (for text boxes, shapes, charts, etc.).
    ///
    /// This is called after the typed-model replacement and flush_to_package.
    fn replace_in_xml_parts(&mut self, pairs: &[(&str, &str)]) -> usize {
        use rdocx_oxml::placeholder::{replace_many_in_chart_xml, replace_many_in_xml_part};

        let mut count = 0;

        // Collect part names for XML parts to process (text boxes/shapes)
        let mut xml_parts: Vec<String> = vec![self.doc_part_name.clone()];
        if let Some(sect_pr) = self.document.body.sect_pr.as_ref()
            && let Some(rels) = self.package.get_part_rels(&self.doc_part_name)
        {
            for href in &sect_pr.header_refs {
                if let Some(rel) = rels.get_by_id(&href.rel_id) {
                    xml_parts.push(OpcPackage::resolve_rel_target(
                        &self.doc_part_name,
                        &rel.target,
                    ));
                }
            }
            for fref in &sect_pr.footer_refs {
                if let Some(rel) = rels.get_by_id(&fref.rel_id) {
                    xml_parts.push(OpcPackage::resolve_rel_target(
                        &self.doc_part_name,
                        &rel.target,
                    ));
                }
            }
        }

        for part_name in xml_parts {
            if let Some(xml) = self.package.get_part(&part_name) {
                let xml = xml.to_vec();
                if let Ok((new_xml, n)) = replace_many_in_xml_part(&xml, pairs)
                    && n > 0
                {
                    self.package.set_part(&part_name, new_xml);
                    count += n;
                }
            }
        }

        // Collect chart part names
        let chart_parts: Vec<String> = self
            .package
            .get_part_rels(&self.doc_part_name)
            .map(|rels| {
                rels.get_all_by_type(rel_types::CHART)
                    .iter()
                    .map(|rel| OpcPackage::resolve_rel_target(&self.doc_part_name, &rel.target))
                    .collect()
            })
            .unwrap_or_default();

        for part_name in chart_parts {
            if let Some(xml) = self.package.get_part(&part_name) {
                let xml = xml.to_vec();
                if let Ok((new_xml, n)) = replace_many_in_chart_xml(&xml, pairs)
                    && n > 0
                {
                    self.package.set_part(&part_name, new_xml);
                    count += n;
                }
            }
        }

        // Re-parse document from the (possibly modified) package XML
        if count > 0
            && let Some(doc_xml) = self.package.get_part(&self.doc_part_name)
            && let Ok(doc) = CT_Document::from_xml(doc_xml)
        {
            self.document = doc;
        }

        count
    }

    // ---- PDF conversion ----

    /// Render the document to PDF bytes.
    ///
    /// This performs a full layout pass (font shaping, line breaking, pagination)
    /// and then renders the result to a PDF document.
    ///
    /// Font resolution order:
    /// 1. Fonts embedded in the DOCX file (word/fonts/)
    /// 2. System fonts when the default `system-fonts` feature is enabled
    /// 3. Always-available bundled metric-compatible fonts
    pub fn to_pdf(&self) -> Result<Vec<u8>> {
        let layout = self.cached_layout()?;
        Ok(oxml_pdf::render_to_pdf(&layout))
    }

    /// Render the document to PDF bytes using bundled fonts without system
    /// font discovery.
    ///
    /// The deterministic layout is cached independently from the normal-font
    /// layout and is suitable for reproducible render baselines.
    pub fn to_pdf_deterministic(&self) -> Result<Vec<u8>> {
        let layout = self.cached_deterministic_layout()?;
        Ok(oxml_pdf::render_to_pdf(&layout))
    }

    /// Render the document to PDF bytes with user-provided font files.
    ///
    /// User-provided fonts take highest priority in font resolution.
    ///
    /// # Arguments
    /// * `font_files` - Additional font files to use. Each entry is `(family_name, font_bytes)`.
    ///
    /// Font resolution order:
    /// 1. User-provided fonts (this parameter)
    /// 2. Fonts embedded in the DOCX file (word/fonts/)
    /// 3. System fonts when the default `system-fonts` feature is enabled
    /// 4. Always-available bundled metric-compatible fonts
    pub fn to_pdf_with_fonts(&self, font_files: &[(&str, &[u8])]) -> Result<Vec<u8>> {
        let mut input = self.build_layout_input();
        for (family, data) in font_files {
            input.fonts.push(rdocx_layout::FontFile {
                family: family.to_string(),
                data: data.to_vec(),
            });
        }
        #[cfg(test)]
        record_layout_invocation();
        let layout = rdocx_layout::layout_document(&input)?;
        Ok(oxml_pdf::render_to_pdf(&layout))
    }

    /// Save the document as a PDF file.
    pub fn save_pdf<P: AsRef<Path>>(&self, path: P) -> Result<()> {
        let pdf_bytes = self.to_pdf()?;
        std::fs::write(path, pdf_bytes)?;
        Ok(())
    }

    /// Convert the document to a complete HTML document string.
    pub fn to_html(&self) -> String {
        let input = self.build_html_input();
        rdocx_html::to_html_document(&input, &rdocx_html::HtmlOptions::default())
    }

    /// Convert the document to an HTML fragment (body content only, no `<html>` wrapper).
    pub fn to_html_fragment(&self) -> String {
        let input = self.build_html_input();
        rdocx_html::to_html_fragment(&input, &rdocx_html::HtmlOptions::default())
    }

    /// Convert the document to Markdown.
    pub fn to_markdown(&self) -> String {
        let input = self.build_html_input();
        rdocx_html::to_markdown(&input)
    }

    /// Build an HtmlInput from the document's current state.
    fn build_html_input(&self) -> rdocx_html::HtmlInput {
        use oxml_opc::relationship::rel_types;
        use std::collections::HashMap;

        let mut images: HashMap<String, rdocx_html::ImageData> = HashMap::new();
        let mut hyperlink_urls: HashMap<String, String> = HashMap::new();

        if let Some(rels) = self.package.get_part_rels(&self.doc_part_name) {
            for rel in &rels.items {
                match rel.rel_type.as_str() {
                    t if t == rel_types::IMAGE => {
                        let part_name =
                            OpcPackage::resolve_rel_target(&self.doc_part_name, &rel.target);
                        if let Some(data) = self.package.get_part(&part_name) {
                            let content_type = oxml_media::resolve(data, &part_name)
                                .content_type()
                                .to_owned();
                            images.insert(
                                rel.id.clone(),
                                rdocx_html::ImageData {
                                    data: data.to_vec(),
                                    content_type,
                                },
                            );
                        }
                    }
                    t if t == rel_types::HYPERLINK
                        && rel.target_mode.as_ref().is_some_and(|m| m == "External") =>
                    {
                        hyperlink_urls.insert(rel.id.clone(), rel.target.clone());
                    }
                    _ => {}
                }
            }
        }

        rdocx_html::HtmlInput {
            document: self.document.clone(),
            styles: self.styles.clone(),
            numbering: self.numbering.clone(),
            images,
            hyperlink_urls,
        }
    }

    /// Render a single page of the document to PNG bytes.
    ///
    /// # Arguments
    /// * `page_index` - 0-based page index
    /// * `dpi` - Resolution (72 = 1:1, 150 = standard, 300 = high quality)
    pub fn render_page_to_png(&self, page_index: usize, dpi: f64) -> Result<Option<Vec<u8>>> {
        let layout = self.cached_layout()?;
        Ok(oxml_pdf::render_page_to_png(&layout, page_index, dpi))
    }

    /// Render a single page to PNG using bundled fonts without system font
    /// discovery.
    ///
    /// # Arguments
    /// * `page_index` - 0-based page index
    /// * `dpi` - Resolution (72 = 1:1, 150 = standard, 300 = high quality)
    pub fn render_page_to_png_deterministic(
        &self,
        page_index: usize,
        dpi: f64,
    ) -> Result<Option<Vec<u8>>> {
        let layout = self.cached_deterministic_layout()?;
        Ok(oxml_pdf::render_page_to_png(&layout, page_index, dpi))
    }

    /// Render all pages of the document to PNG bytes.
    pub fn render_all_pages(&self, dpi: f64) -> Result<Vec<Vec<u8>>> {
        let layout = self.cached_layout()?;
        Ok(oxml_pdf::render_all_pages(&layout, dpi))
    }

    /// Return a cloned positioned page from the cached normal-font layout.
    ///
    /// `page_index` is zero-based. An index beyond the document returns `None`.
    pub fn layout_page(&self, page_index: usize) -> Result<Option<oxml_layout::PageFrame>> {
        let layout = self.cached_layout()?;
        Ok(layout.pages.get(page_index).cloned())
    }

    /// Build a LayoutInput from the document's current state.
    fn build_layout_input(&self) -> rdocx_layout::LayoutInput {
        use oxml_opc::relationship::rel_types;
        use rdocx_layout::{ImageData, LayoutInput};
        use std::collections::HashMap;

        let mut headers: HashMap<String, CT_HdrFtr> = HashMap::new();
        let mut footers: HashMap<String, CT_HdrFtr> = HashMap::new();
        let mut images: HashMap<String, ImageData> = HashMap::new();
        let mut hyperlink_urls: HashMap<String, String> = HashMap::new();
        let mut footnotes = None;
        let mut endnotes = None;

        // Extract embedded fonts from the DOCX package
        let fonts = self.extract_embedded_fonts();

        if let Some(rels) = self.package.get_part_rels(&self.doc_part_name) {
            for rel in &rels.items {
                match rel.rel_type.as_str() {
                    t if t == rel_types::HEADER => {
                        let part_name =
                            OpcPackage::resolve_rel_target(&self.doc_part_name, &rel.target);
                        if let Some(xml) = self.package.get_part(&part_name)
                            && let Ok(hf) = CT_HdrFtr::from_xml(xml)
                        {
                            headers.insert(rel.id.clone(), hf);
                        }
                    }
                    t if t == rel_types::FOOTER => {
                        let part_name =
                            OpcPackage::resolve_rel_target(&self.doc_part_name, &rel.target);
                        if let Some(xml) = self.package.get_part(&part_name)
                            && let Ok(hf) = CT_HdrFtr::from_xml(xml)
                        {
                            footers.insert(rel.id.clone(), hf);
                        }
                    }
                    t if t == rel_types::IMAGE => {
                        let part_name =
                            OpcPackage::resolve_rel_target(&self.doc_part_name, &rel.target);
                        if let Some(data) = self.package.get_part(&part_name) {
                            let content_type = oxml_media::resolve(data, &part_name)
                                .content_type()
                                .to_owned();
                            images.insert(
                                rel.id.clone(),
                                ImageData {
                                    data: data.to_vec(),
                                    content_type,
                                },
                            );
                        }
                    }
                    t if t == rel_types::HYPERLINK => {
                        if rel.target_mode.as_ref().is_some_and(|m| m == "External") {
                            hyperlink_urls.insert(rel.id.clone(), rel.target.clone());
                        }
                    }
                    t if t == rel_types::FOOTNOTES => {
                        let part_name =
                            OpcPackage::resolve_rel_target(&self.doc_part_name, &rel.target);
                        if let Some(xml) = self.package.get_part(&part_name) {
                            footnotes = rdocx_oxml::footnotes::CT_Footnotes::from_xml(xml).ok();
                        }
                    }
                    t if t == rel_types::ENDNOTES => {
                        let part_name =
                            OpcPackage::resolve_rel_target(&self.doc_part_name, &rel.target);
                        if let Some(xml) = self.package.get_part(&part_name) {
                            endnotes = rdocx_oxml::footnotes::CT_Footnotes::from_xml(xml).ok();
                        }
                    }
                    _ => {}
                }
            }
        }

        // Parse theme if available
        let theme = self
            .package
            .get_part("/word/theme/theme1.xml")
            .and_then(|data| rdocx_oxml::theme::Theme::from_xml(data).ok());

        LayoutInput {
            document: self.document.clone(),
            styles: self.styles.clone(),
            numbering: self.numbering.clone(),
            headers,
            footers,
            images,
            core_properties: self.core_properties.clone(),
            hyperlink_urls,
            footnotes,
            endnotes,
            theme,
            fonts,
        }
    }

    /// Extract embedded fonts from the DOCX package.
    ///
    /// Word can embed fonts as `.odttf` (obfuscated TrueType) or regular `.ttf`/`.otf`
    /// files in the `word/fonts/` directory. ODTTF files have the first 32 bytes
    /// XOR'd with a 16-byte GUID derived from the font's relationship ID.
    fn extract_embedded_fonts(&self) -> Vec<rdocx_layout::FontFile> {
        let mut fonts = Vec::new();

        // Look for font parts in word/fonts/ directory
        for (part_name, data) in &self.package.parts {
            let lower = part_name.to_lowercase();
            if !lower.contains("/word/fonts/") && !lower.contains("/word/font") {
                continue;
            }

            // Determine font family name from the file name
            let file_name = part_name.rsplit('/').next().unwrap_or(part_name);
            let family = file_name.split('.').next().unwrap_or(file_name).to_string();

            if lower.ends_with(".odttf") {
                // Deobfuscate ODTTF: XOR first 32 bytes with GUID from the file name
                if let Some(deobfuscated) = deobfuscate_odttf(data, file_name) {
                    fonts.push(rdocx_layout::FontFile {
                        family,
                        data: deobfuscated,
                    });
                }
            } else if lower.ends_with(".ttf") || lower.ends_with(".otf") || lower.ends_with(".ttc")
            {
                fonts.push(rdocx_layout::FontFile {
                    family,
                    data: data.clone(),
                });
            }
        }

        fonts
    }

    /// Load font files from a directory and return them as FontFile entries.
    ///
    /// This is useful for CLI tools that accept a `--font-dir` argument.
    /// Supports `.ttf`, `.otf`, and `.ttc` files.
    pub fn load_fonts_from_dir<P: AsRef<Path>>(dir: P) -> Vec<rdocx_layout::FontFile> {
        let mut fonts = Vec::new();
        let dir = dir.as_ref();
        if let Ok(entries) = std::fs::read_dir(dir) {
            for entry in entries.flatten() {
                let path = entry.path();
                let ext = path
                    .extension()
                    .and_then(|e| e.to_str())
                    .unwrap_or("")
                    .to_lowercase();
                if (ext == "ttf" || ext == "otf" || ext == "ttc")
                    && let Ok(data) = std::fs::read(&path)
                {
                    let family = path
                        .file_stem()
                        .and_then(|s| s.to_str())
                        .unwrap_or("Unknown")
                        .to_string();
                    fonts.push(rdocx_layout::FontFile { family, data });
                }
            }
        }
        fonts
    }

    /// Save a header/footer part back to the OPC package.
    fn save_header_footer(&mut self, rel_id: &str, hf: &CT_HdrFtr, is_header: bool) {
        let part_name = {
            let rels = self.package.get_part_rels(&self.doc_part_name);
            rels.and_then(|r| r.get_by_id(rel_id))
                .map(|rel| OpcPackage::resolve_rel_target(&self.doc_part_name, &rel.target))
        };
        if let Some(part_name) = part_name {
            let xml = if is_header {
                hf.to_xml_header()
            } else {
                hf.to_xml_footer()
            };
            if let Ok(xml) = xml {
                self.package.set_part(&part_name, xml);
            }
        }
    }

    // ---- Document Intelligence API ----

    /// Get all headings in the document as (level, text) pairs.
    ///
    /// Detects heading paragraphs by their style ID (e.g. "Heading1", "Heading2").
    pub fn headings(&self) -> Vec<(u32, String)> {
        let mut result = Vec::new();
        for content in &self.document.body.content {
            if let BodyContent::Paragraph(p) = content
                && let Some(level) = Self::detect_heading_level_for_toc(p)
            {
                result.push((level, p.text()));
            }
        }
        result
    }

    /// Get a hierarchical outline of the document headings.
    ///
    /// Returns a tree structure where each node contains the heading level,
    /// text, and children (sub-headings).
    pub fn document_outline(&self) -> Vec<OutlineNode> {
        let headings = self.headings();
        build_outline_tree(&headings)
    }

    /// Get information about all images in the document.
    ///
    /// Returns metadata for each inline and anchored image found in body paragraphs.
    pub fn images(&self) -> Vec<ImageInfo> {
        let mut result = Vec::new();

        for content in &self.document.body.content {
            Self::collect_images_from_content(content, &mut result);
        }
        result
    }

    fn collect_images_from_content(content: &BodyContent, result: &mut Vec<ImageInfo>) {
        match content {
            BodyContent::Paragraph(p) => Self::collect_images_from_paragraph(p, result),
            BodyContent::Table(tbl) => Self::collect_images_from_table(tbl, result),
            BodyContent::RawXml(_) => {}
        }
    }

    fn collect_images_from_paragraph(p: &CT_P, result: &mut Vec<ImageInfo>) {
        for run in &p.runs {
            for rc in &run.content {
                let RunContent::Drawing(drawing) = rc else {
                    continue;
                };
                if let Some(inline) = &drawing.inline {
                    result.push(ImageInfo {
                        embed_id: inline.embed_id.clone(),
                        name: inline.name.clone(),
                        description: inline.description.clone(),
                        width_emu: inline.extent_cx.0,
                        height_emu: inline.extent_cy.0,
                        is_anchor: false,
                    });
                }
                if let Some(anchor) = &drawing.anchor {
                    result.push(ImageInfo {
                        embed_id: anchor.embed_id.clone(),
                        name: anchor.name.clone(),
                        description: anchor.description.clone(),
                        width_emu: anchor.extent_cx.0,
                        height_emu: anchor.extent_cy.0,
                        is_anchor: true,
                    });
                }
            }
        }
    }

    fn collect_images_from_table(tbl: &CT_Tbl, result: &mut Vec<ImageInfo>) {
        use rdocx_oxml::table::CellContent;

        for row in &tbl.rows {
            for cell in &row.cells {
                for cc in &cell.content {
                    match cc {
                        CellContent::Paragraph(p) => Self::collect_images_from_paragraph(p, result),
                        CellContent::Table(nested) => {
                            Self::collect_images_from_table(nested, result)
                        }
                    }
                }
            }
        }
    }

    /// Get information about all hyperlinks in the document.
    ///
    /// Resolves hyperlink relationship IDs to their target URLs where possible.
    pub fn links(&self) -> Vec<LinkInfo> {
        use oxml_opc::relationship::rel_types;

        // Build a map of hyperlink rel_id -> target URL
        let mut url_map = std::collections::HashMap::new();
        if let Some(rels) = self.package.get_part_rels(&self.doc_part_name) {
            for rel in &rels.items {
                if rel.rel_type == rel_types::HYPERLINK
                    && rel.target_mode.as_ref().is_some_and(|m| m == "External")
                {
                    url_map.insert(rel.id.clone(), rel.target.clone());
                }
            }
        }

        let mut result = Vec::new();
        for content in &self.document.body.content {
            if let BodyContent::Paragraph(p) = content {
                for hl in &p.hyperlinks {
                    // `HyperlinkSpan`'s bounds are public and can be set by
                    // hand, so clamp rather than slice-panic on a bad range.
                    let start = hl.run_start.min(p.runs.len());
                    let end = hl.run_end.clamp(start, p.runs.len());
                    let text: String = p.runs[start..end].iter().map(|r| r.text()).collect();

                    let url = hl.rel_id.as_ref().and_then(|id| url_map.get(id)).cloned();

                    result.push(LinkInfo {
                        text,
                        url,
                        anchor: hl.anchor.clone(),
                        rel_id: hl.rel_id.clone(),
                    });
                }
            }
        }
        result
    }

    /// Count the number of words in the document.
    ///
    /// Counts whitespace-separated tokens across all paragraphs (including
    /// paragraphs inside table cells).
    pub fn word_count(&self) -> usize {
        let mut count = 0;
        for content in &self.document.body.content {
            count += Self::word_count_in_content(content);
        }
        count
    }

    fn word_count_in_content(content: &BodyContent) -> usize {
        match content {
            BodyContent::Paragraph(p) => p.text().split_whitespace().count(),
            BodyContent::Table(tbl) => Self::word_count_in_table(tbl),
            BodyContent::RawXml(_) => 0,
        }
    }

    fn word_count_in_table(tbl: &CT_Tbl) -> usize {
        use rdocx_oxml::table::CellContent;

        let mut count = 0;
        for row in &tbl.rows {
            for cell in &row.cells {
                for cc in &cell.content {
                    match cc {
                        CellContent::Paragraph(p) => {
                            count += p.text().split_whitespace().count();
                        }
                        CellContent::Table(nested) => {
                            count += Self::word_count_in_table(nested);
                        }
                    }
                }
            }
        }
        count
    }

    /// Audit the document for accessibility issues.
    ///
    /// Checks for common problems: missing image alt text, heading level gaps,
    /// empty paragraphs, missing document metadata.
    pub fn audit_accessibility(&self) -> Vec<AccessibilityIssue> {
        let mut issues = Vec::new();

        // Check: missing document title
        if self.title().is_none() {
            issues.push(AccessibilityIssue {
                severity: IssueSeverity::Warning,
                message: "Document has no title".to_string(),
            });
        }

        // Check: missing document language (author as a proxy for basic metadata)
        if self.author().is_none() {
            issues.push(AccessibilityIssue {
                severity: IssueSeverity::Info,
                message: "Document has no author".to_string(),
            });
        }

        // Check: images without alt text
        let images = self.images();
        for img in &images {
            let has_alt = img
                .description
                .as_ref()
                .is_some_and(|d| !d.is_empty() && d != "Background");
            if !has_alt {
                let name = img
                    .name
                    .as_deref()
                    .or(Some(&img.embed_id))
                    .unwrap_or("unknown");
                issues.push(AccessibilityIssue {
                    severity: IssueSeverity::Error,
                    message: format!("Image \"{name}\" has no alt text"),
                });
            }
        }

        // Check: heading level gaps
        let headings = self.headings();
        let mut prev_level: Option<u32> = None;
        for (level, text) in &headings {
            if let Some(prev) = prev_level
                && *level > prev + 1
            {
                issues.push(AccessibilityIssue {
                    severity: IssueSeverity::Warning,
                    message: format!(
                        "Heading level gap: h{prev} -> h{level} (\"{}\")",
                        truncate_str(text, 40)
                    ),
                });
            }
            prev_level = Some(*level);
        }

        // Check: excessive empty paragraphs
        let mut consecutive_empty = 0u32;
        for content in &self.document.body.content {
            if let BodyContent::Paragraph(p) = content {
                if p.text().trim().is_empty() {
                    consecutive_empty += 1;
                    if consecutive_empty >= 3 {
                        issues.push(AccessibilityIssue {
                            severity: IssueSeverity::Info,
                            message: format!(
                                "{consecutive_empty} consecutive empty paragraphs (consider using spacing instead)"
                            ),
                        });
                    }
                } else {
                    consecutive_empty = 0;
                }
            } else {
                consecutive_empty = 0;
            }
        }

        issues
    }
}

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

/// Express `target_part` relative to the directory holding `source_part`.
///
/// Falls back to the absolute part name when the two live in different
/// directories, which OPC also permits.
fn relative_target(source_part: &str, target_part: &str) -> String {
    let dir = match source_part.rfind('/') {
        Some(pos) => &source_part[..=pos],
        None => "/",
    };
    match target_part.strip_prefix(dir) {
        Some(rest) if !rest.contains('/') => rest.to_string(),
        _ => target_part.to_string(),
    }
}

/// Numbering format for one level of a custom list definition.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ListNumberFormat {
    Bullet,
    Decimal,
    LowerLetter,
    UpperLetter,
    LowerRoman,
    UpperRoman,
    Ordinal,
}

impl ListNumberFormat {
    fn to_st(self) -> ST_NumberFormat {
        match self {
            Self::Bullet => ST_NumberFormat::Bullet,
            Self::Decimal => ST_NumberFormat::Decimal,
            Self::LowerLetter => ST_NumberFormat::LowerLetter,
            Self::UpperLetter => ST_NumberFormat::UpperLetter,
            Self::LowerRoman => ST_NumberFormat::LowerRoman,
            Self::UpperRoman => ST_NumberFormat::UpperRoman,
            Self::Ordinal => ST_NumberFormat::Ordinal,
        }
    }
}

/// One level of a custom list definition for [`Document::add_list_definition`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ListLevel {
    /// Numbering format for this level.
    pub format: ListNumberFormat,
    /// Starting number (defaults to 1; ignored for bullet levels).
    pub start: Option<u32>,
}

impl ListLevel {
    /// A level with the given format, starting at 1.
    pub fn new(format: ListNumberFormat) -> Self {
        ListLevel {
            format,
            start: None,
        }
    }

    /// A bullet level.
    pub fn bullet() -> Self {
        Self::new(ListNumberFormat::Bullet)
    }

    /// A decimal-numbered level.
    pub fn decimal() -> Self {
        Self::new(ListNumberFormat::Decimal)
    }

    /// Override the starting number for this level.
    pub fn start(mut self, start: u32) -> Self {
        self.start = Some(start);
        self
    }
}

/// A node in the document outline tree.
#[derive(Debug, Clone, PartialEq)]
pub struct OutlineNode {
    /// The heading level (1-9).
    pub level: u32,
    /// The heading text.
    pub text: String,
    /// Child headings (sub-headings).
    pub children: Vec<OutlineNode>,
}

/// Information about an image in the document.
#[derive(Debug, Clone, PartialEq)]
pub struct ImageInfo {
    /// The relationship ID for the embedded image.
    pub embed_id: String,
    /// Optional name attribute.
    pub name: Option<String>,
    /// Optional description (alt text).
    pub description: Option<String>,
    /// Width in EMUs (English Metric Units, 914400 EMU = 1 inch).
    pub width_emu: i64,
    /// Height in EMUs.
    pub height_emu: i64,
    /// Whether this is an anchored (floating) image vs inline.
    pub is_anchor: bool,
}

/// Information about a hyperlink in the document.
#[derive(Debug, Clone, PartialEq)]
pub struct LinkInfo {
    /// The display text of the hyperlink.
    pub text: String,
    /// The resolved target URL (if external).
    pub url: Option<String>,
    /// Internal document anchor (if any).
    pub anchor: Option<String>,
    /// The relationship ID.
    pub rel_id: Option<String>,
}

/// Severity level for accessibility issues.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IssueSeverity {
    /// Informational suggestion.
    Info,
    /// Potential problem.
    Warning,
    /// Definite accessibility barrier.
    Error,
}

/// An accessibility issue found during audit.
#[derive(Debug, Clone, PartialEq)]
pub struct AccessibilityIssue {
    /// How severe the issue is.
    pub severity: IssueSeverity,
    /// Human-readable description of the issue.
    pub message: String,
}

/// Build a hierarchical outline tree from a flat list of (level, text) headings.
fn build_outline_tree(headings: &[(u32, String)]) -> Vec<OutlineNode> {
    let mut root: Vec<OutlineNode> = Vec::new();
    let mut stack: Vec<(u32, usize)> = Vec::new(); // (level, index in parent's children)

    for (level, text) in headings {
        let node = OutlineNode {
            level: *level,
            text: text.clone(),
            children: Vec::new(),
        };

        // Pop stack until we find a parent with a lower level
        while let Some(&(stack_level, _)) = stack.last() {
            if stack_level >= *level {
                stack.pop();
            } else {
                break;
            }
        }

        if stack.is_empty() {
            root.push(node);
            let idx = root.len() - 1;
            stack.push((*level, idx));
        } else {
            // Navigate to the correct parent in the tree
            let target = get_outline_parent_mut(&mut root, &stack);
            target.children.push(node);
            let idx = target.children.len() - 1;
            stack.push((*level, idx));
        }
    }

    root
}

/// Navigate to the parent node indicated by the stack.
fn get_outline_parent_mut<'a>(
    root: &'a mut [OutlineNode],
    stack: &[(u32, usize)],
) -> &'a mut OutlineNode {
    let mut current = &mut root[stack[0].1];
    for &(_, idx) in &stack[1..] {
        current = &mut current.children[idx];
    }
    current
}

/// Truncate a string to at most `max_len` characters, appending "..." if it
/// was cut short.
///
/// Both the comparison and the cut are in characters; mixing byte length with
/// character counts would truncate non-ASCII text earlier than asked.
fn truncate_str(s: &str, max_len: usize) -> String {
    if s.chars().count() <= max_len {
        return s.to_string();
    }
    let truncated: String = s.chars().take(max_len.saturating_sub(3)).collect();
    format!("{truncated}...")
}

/// Deobfuscate an ODTTF (obfuscated TrueType) font file.
///
/// Word embeds fonts as `.odttf` files whose first 32 bytes are XOR'd with a
/// 16-byte key derived from the GUID in the part name (ECMA-376 Part 1,
/// "Embedded Font Obfuscation"). The GUID hex is read into the key *backwards*,
/// but implementations differ in whether they reverse the raw hex string or the
/// mixed-endian layout .NET's `Guid.ToByteArray` produces — the two agree on
/// the first eight key bytes and disagree on the rest.
///
/// Rather than pick one and hope, both orders are tried and the result is only
/// accepted if it starts with a recognised sfnt version. A wrong key yields
/// bytes that no font parser can use, so validating here means a bad guess
/// degrades to "font not embedded" instead of feeding garbage downstream.
fn deobfuscate_odttf(data: &[u8], file_name: &str) -> Option<Vec<u8>> {
    if data.len() < 32 {
        return None;
    }

    // Extract GUID from file name: "00112233-4455-6677-8899-AABBCCDDEEFF.odttf"
    // or "{00112233-4455-6677-8899-AABBCCDDEEFF}.odttf"
    let name = file_name
        .split('.')
        .next()
        .unwrap_or("")
        .trim_start_matches('{')
        .trim_end_matches('}');

    // Remove hyphens and parse as hex bytes
    let hex: String = name.chars().filter(|c| c.is_ascii_hexdigit()).collect();
    if hex.len() != 32 {
        return None;
    }

    let mut guid = [0u8; 16];
    for (i, byte) in guid.iter_mut().enumerate() {
        *byte = u8::from_str_radix(&hex[i * 2..i * 2 + 2], 16).ok()?;
    }

    let candidates = odttf_key_candidates(&guid);
    let decoded: Vec<Vec<u8>> = candidates
        .iter()
        .map(|key| {
            let mut result = data.to_vec();
            // XOR the first 32 bytes with the 16-byte key, applied twice.
            for (i, byte) in result.iter_mut().take(32).enumerate() {
                *byte ^= key[i % 16];
            }
            result
        })
        .collect();

    // A well-formed table directory pins down which key was used. Fall back to
    // the weaker signature check for fonts whose header arithmetic is wrong —
    // subsetting tools do emit those — so they still load rather than being
    // dropped entirely.
    decoded
        .iter()
        .find(|d| has_consistent_sfnt_header(d))
        .or_else(|| decoded.iter().find(|d| looks_like_sfnt(d)))
        .cloned()
}

/// The two candidate XOR keys for ODTTF deobfuscation, most likely first.
fn odttf_key_candidates(guid: &[u8; 16]) -> [[u8; 16]; 2] {
    // Read the hex string end-first, as the spec prose describes.
    let mut plain_reversed = *guid;
    plain_reversed.reverse();

    // The .NET route: `Guid.ToByteArray` byte-swaps the first three groups,
    // and the whole array is then reversed.
    let dotnet = [
        guid[3], guid[2], guid[1], guid[0], guid[5], guid[4], guid[7], guid[6], guid[8], guid[9],
        guid[10], guid[11], guid[12], guid[13], guid[14], guid[15],
    ];
    let mut dotnet_reversed = dotnet;
    dotnet_reversed.reverse();

    [plain_reversed, dotnet_reversed]
}

/// Check that `data` opens with a plausible sfnt (TrueType/OpenType) header.
///
/// This is the weak test: signature plus printable table tags. It cannot always
/// tell the two ODTTF key conventions apart, since they produce identical
/// output for the first eight bytes.
fn looks_like_sfnt(data: &[u8]) -> bool {
    let Some(signature) = data.first_chunk::<4>() else {
        return false;
    };
    match signature {
        b"\x00\x01\x00\x00" | b"OTTO" | b"true" => {}
        // A collection header has a different layout; take it on signature.
        b"ttcf" => return true,
        _ => return false,
    }

    if data.len() < 32 {
        return false;
    }

    let num_tables = u16::from_be_bytes([data[4], data[5]]);
    if num_tables == 0 || num_tables > 512 {
        return false;
    }

    // Table records begin at offset 12 and are 16 bytes each, so the first
    // record's tag is at 12..16 and the second record's tag at 28..32 — both
    // inside the 32 bytes the obfuscation touches.
    let is_tag = |tag: &[u8]| tag.iter().all(|b| (0x20..=0x7E).contains(b));
    is_tag(&data[12..16]) && (num_tables < 2 || is_tag(&data[28..32]))
}

/// The strong test: the sfnt header's binary-search hints must agree with the
/// table count.
///
/// `searchRange`, `entrySelector` and `rangeShift` are all derived from
/// `numTables`, and `entrySelector`/`rangeShift` sit in the byte range where
/// the two ODTTF key conventions differ — so this identifies the right key
/// outright whenever the font's header is spec-conformant.
fn has_consistent_sfnt_header(data: &[u8]) -> bool {
    if !looks_like_sfnt(data) || data.len() < 12 {
        return false;
    }
    if data.first_chunk::<4>() == Some(b"ttcf") {
        return false; // no table directory at this offset
    }

    let num_tables = u16::from_be_bytes([data[4], data[5]]);
    let search_range = u16::from_be_bytes([data[6], data[7]]);
    let entry_selector = u16::from_be_bytes([data[8], data[9]]);
    let range_shift = u16::from_be_bytes([data[10], data[11]]);

    let expected_selector = num_tables.ilog2() as u16;
    let expected_search_range = (1u16 << expected_selector) * 16;
    let expected_range_shift = num_tables
        .wrapping_mul(16)
        .wrapping_sub(expected_search_range);

    search_range == expected_search_range
        && entry_selector == expected_selector
        && range_shift == expected_range_shift
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::paragraph::Alignment;
    use rdocx_oxml::units::{HalfPoint, Twips};

    fn reset_layout_invocations() {
        LAYOUT_INVOCATIONS.set(0);
    }

    fn layout_invocations() -> usize {
        LAYOUT_INVOCATIONS.get()
    }

    #[test]
    fn rendering_all_pages_performs_one_layout() {
        let mut doc = Document::new();
        doc.add_paragraph("Page 1");
        for page in 2..=20 {
            doc.add_paragraph(&format!("Page {page}"))
                .page_break_before(true);
        }

        reset_layout_invocations();
        for page_index in 0..20 {
            assert!(
                doc.render_page_to_png_deterministic(page_index, 1.0)
                    .expect("deterministic layout should succeed")
                    .is_some(),
                "page {page_index} should exist"
            );
        }

        assert_eq!(layout_invocations(), 1);
    }

    #[test]
    fn document_mutation_invalidates_cached_layout() {
        let mut doc = Document::new();
        doc.add_paragraph("Before mutation");

        reset_layout_invocations();
        doc.render_page_to_png_deterministic(0, 1.0).unwrap();
        doc.render_page_to_png_deterministic(0, 1.0).unwrap();
        assert_eq!(layout_invocations(), 1);

        doc.add_paragraph("After mutation");
        doc.render_page_to_png_deterministic(0, 1.0).unwrap();
        doc.render_page_to_png_deterministic(0, 1.0).unwrap();
        assert_eq!(layout_invocations(), 2);
    }

    #[test]
    fn mutable_accessor_invalidates_cached_layout() {
        let mut doc = Document::new();
        doc.add_paragraph("Before wrapper mutation");

        reset_layout_invocations();
        doc.render_page_to_png_deterministic(0, 1.0).unwrap();
        doc.render_page_to_png_deterministic(0, 1.0).unwrap();
        assert_eq!(layout_invocations(), 1);

        doc.paragraph_mut(0)
            .expect("paragraph should exist")
            .add_run(" changed");
        doc.render_page_to_png_deterministic(0, 1.0).unwrap();
        doc.render_page_to_png_deterministic(0, 1.0).unwrap();
        assert_eq!(layout_invocations(), 2);

        let mut table = doc.add_table(1, 1);
        table
            .cell(0, 0)
            .expect("cell should exist")
            .set_text("table mutation");
        doc.render_page_to_png_deterministic(0, 1.0).unwrap();
        doc.render_page_to_png_deterministic(0, 1.0).unwrap();
        assert_eq!(layout_invocations(), 3);
    }

    #[test]
    fn immutable_run_accessors_preserve_cached_layout() {
        let mut doc = Document::new();
        doc.add_paragraph("Before immutable access")
            .add_run(" remains cached");

        reset_layout_invocations();
        doc.render_page_to_png_deterministic(0, 1.0).unwrap();
        assert_eq!(layout_invocations(), 1);

        let paragraph = doc.paragraph(0).expect("paragraph should exist");
        assert_eq!(paragraph.run_count(), 2);
        assert_eq!(
            paragraph.run(1).expect("run should exist").text(),
            " remains cached"
        );
        assert!(paragraph.run(2).is_none());

        doc.render_page_to_png_deterministic(0, 1.0).unwrap();
        assert_eq!(layout_invocations(), 1);
    }

    #[test]
    fn font_modes_use_isolated_layout_caches() {
        let mut doc = Document::new();
        doc.add_paragraph("Font mode isolation");

        reset_layout_invocations();
        doc.render_page_to_png(0, 1.0).unwrap();
        doc.render_page_to_png(0, 1.0).unwrap();
        assert!(doc.layout_page(0).unwrap().is_some());
        assert!(doc.layout_page(usize::MAX).unwrap().is_none());
        assert_eq!(doc.render_all_pages(1.0).unwrap().len(), 1);
        assert!(!doc.to_pdf().unwrap().is_empty());
        assert_eq!(layout_invocations(), 1);

        doc.render_page_to_png_deterministic(0, 1.0).unwrap();
        doc.render_page_to_png_deterministic(0, 1.0).unwrap();
        assert_eq!(layout_invocations(), 2);

        doc.render_page_to_png(0, 1.0).unwrap();
        doc.render_page_to_png_deterministic(0, 1.0).unwrap();
        assert_eq!(layout_invocations(), 2);

        let (family, font_data) = oxml_layout::bundled_fonts::bundled_font_data()[0];
        doc.to_pdf_with_fonts(&[(family, font_data)]).unwrap();
        doc.to_pdf_with_fonts(&[(family, font_data)]).unwrap();
        assert_eq!(layout_invocations(), 4);
    }

    #[test]
    fn document_remains_send_and_sync() {
        fn assert_send_and_sync<T: Send + Sync>() {}
        assert_send_and_sync::<Document>();
    }

    #[test]
    fn html_and_layout_media_use_sniffed_content_type() {
        let jpeg = [0xff, 0xd8, 0xff, 0xd9];
        let mut document = Document::new();
        document
            .package
            .set_part("/word/media/misleading.png", jpeg.to_vec());
        let relationship_id = document
            .package
            .get_or_create_part_rels("/word/document.xml")
            .add(rel_types::IMAGE, "media/misleading.png");

        let html_input = document.build_html_input();
        let layout_input = document.build_layout_input();

        assert_eq!(
            html_input.images[&relationship_id].content_type,
            "image/jpeg"
        );
        assert_eq!(
            layout_input.images[&relationship_id].content_type,
            "image/jpeg"
        );
    }

    #[test]
    fn deterministic_render_is_independent_of_system_fonts() {
        let mut doc = Document::new();
        doc.add_paragraph("Deterministic rendering");

        let input = doc.build_layout_input();
        let layout = rdocx_layout::layout_document_deterministic(&input)
            .expect("deterministic layout should succeed");
        let bundled_fonts = oxml_layout::bundled_fonts::bundled_font_data();

        assert!(!layout.fonts.is_empty());
        for font in &layout.fonts {
            assert!(!font.data.is_empty());
            assert!(
                bundled_fonts
                    .iter()
                    .any(|(_family, data)| *data == font.data.as_slice()),
                "resolved font '{}' did not come from the bundled font set",
                font.family
            );
        }

        let inspected = oxml_pdf::render_page_to_png(&layout, 0, 150.0)
            .expect("document should have a first page");
        let facade = doc
            .render_page_to_png_deterministic(0, 150.0)
            .expect("deterministic layout should succeed")
            .expect("document should have a first page");

        assert!(!inspected.is_empty());
        assert_eq!(facade, inspected);
    }

    #[test]
    fn deterministic_pdf_facade_reuses_bundled_font_layout() {
        let mut doc = Document::new();
        doc.add_paragraph("Deterministic PDF rendering");

        reset_layout_invocations();
        let first = doc
            .to_pdf_deterministic()
            .expect("deterministic PDF rendering should succeed");
        let second = doc
            .to_pdf_deterministic()
            .expect("cached deterministic PDF rendering should succeed");

        assert!(first.starts_with(b"%PDF-"));
        assert!(second.starts_with(b"%PDF-"));
        assert_eq!(layout_invocations(), 1);
    }

    #[test]
    fn create_new_document() {
        let doc = Document::new();
        assert_eq!(doc.paragraph_count(), 0);
        assert!(doc.section_properties().is_some());
    }

    #[test]
    fn add_paragraphs() {
        let mut doc = Document::new();
        doc.add_paragraph("First paragraph");
        doc.add_paragraph("Second paragraph");
        assert_eq!(doc.paragraph_count(), 2);

        let paras = doc.paragraphs();
        assert_eq!(paras[0].text(), "First paragraph");
        assert_eq!(paras[1].text(), "Second paragraph");
    }

    #[test]
    fn document_text_preserves_body_and_table_order() {
        let mut doc = Document::new();
        doc.add_paragraph("Before");
        let mut table = doc.add_table(1, 2);
        table.cell(0, 0).unwrap().set_text("Left");
        table.cell(0, 1).unwrap().set_text("Right");
        doc.add_paragraph("After");

        assert_eq!(doc.text(), "Before\nLeft\tRight\t\nAfter\n");
    }

    #[test]
    fn paragraph_formatting() {
        let mut doc = Document::new();
        doc.add_paragraph("Centered").alignment(Alignment::Center);

        let paras = doc.paragraphs();
        assert_eq!(paras[0].alignment(), Some(Alignment::Center));
    }

    #[test]
    fn run_formatting() {
        let mut doc = Document::new();
        let mut para = doc.add_paragraph("");
        para.add_run("Bold text").bold(true).size(14.0);

        let paras = doc.paragraphs();
        let runs: Vec<_> = paras[0].runs().collect();
        assert!(runs[0].is_bold());
        assert_eq!(runs[0].size(), Some(14.0));
    }

    #[test]
    fn round_trip_in_memory() {
        let mut doc = Document::new();
        doc.add_paragraph("Hello, World!");
        doc.add_paragraph("Second paragraph")
            .alignment(Alignment::Center);

        let bytes = doc.to_bytes().unwrap();
        let doc2 = Document::from_bytes(&bytes).unwrap();

        assert_eq!(doc2.paragraph_count(), 2);
        let paras = doc2.paragraphs();
        assert_eq!(paras[0].text(), "Hello, World!");
        assert_eq!(paras[1].text(), "Second paragraph");
        assert_eq!(paras[1].alignment(), Some(Alignment::Center));
    }

    #[test]
    fn styles_present() {
        let doc = Document::new();
        assert!(doc.style("Normal").is_some());
        assert!(doc.style("Heading1").is_some());
    }

    #[test]
    fn paragraph_with_style() {
        let mut doc = Document::new();
        doc.add_paragraph("Title").style("Heading1");

        let paras = doc.paragraphs();
        assert_eq!(paras[0].style_id(), Some("Heading1"));
    }

    #[test]
    fn multiple_runs_in_paragraph() {
        let mut doc = Document::new();
        let mut para = doc.add_paragraph("");
        para.add_run("Normal ");
        para.add_run("bold ").bold(true);
        para.add_run("italic").italic(true);

        let paras = doc.paragraphs();
        assert_eq!(paras[0].text(), "Normal bold italic");
        let runs: Vec<_> = paras[0].runs().collect();
        assert_eq!(runs.len(), 3);
        assert!(!runs[0].is_bold());
        assert!(runs[1].is_bold());
        assert!(runs[2].is_italic());
    }

    #[test]
    fn add_custom_style() {
        let mut doc = Document::new();
        doc.add_style(StyleBuilder::paragraph("MyCustom", "My Custom Style").based_on("Normal"));
        assert!(doc.style("MyCustom").is_some());
        let s = doc.style("MyCustom").unwrap();
        assert_eq!(s.name(), Some("My Custom Style"));
        assert_eq!(s.based_on(), Some("Normal"));
    }

    #[test]
    fn resolve_style_properties() {
        let doc = Document::new();
        // Heading1 should inherit from docDefaults and have its own overrides
        let ppr = doc.resolve_paragraph_properties(Some("Heading1"));
        assert_eq!(ppr.keep_next, Some(true));
        assert_eq!(ppr.space_before, Some(Twips(240)));

        // Default (None) should apply Normal style
        let ppr = doc.resolve_paragraph_properties(None);
        assert_eq!(ppr.space_after, Some(Twips(160)));
    }

    #[test]
    fn resolve_run_style_properties() {
        let doc = Document::new();
        let rpr = doc.resolve_run_properties(Some("Heading1"), None);
        assert_eq!(rpr.bold, Some(true));
        assert_eq!(rpr.sz, Some(HalfPoint(32)));
        assert_eq!(rpr.font_ascii, Some("Calibri".to_string()));
    }

    #[test]
    fn set_landscape() {
        let mut doc = Document::new();
        doc.set_landscape();
        let sect = doc.section_properties().unwrap();
        assert_eq!(sect.orientation, Some(ST_PageOrientation::Landscape));
        // Width should be > height in landscape
        assert!(sect.page_width.unwrap().0 > sect.page_height.unwrap().0);
    }

    #[test]
    fn set_margins() {
        let mut doc = Document::new();
        doc.set_margins(
            Length::inches(0.5),
            Length::inches(0.75),
            Length::inches(0.5),
            Length::inches(0.75),
        );
        let sect = doc.section_properties().unwrap();
        assert_eq!(sect.margin_top, Some(Twips(720)));
        assert_eq!(sect.margin_right, Some(Twips(1080)));
    }

    #[test]
    fn set_columns() {
        let mut doc = Document::new();
        doc.set_columns(2, Length::inches(0.5));
        let sect = doc.section_properties().unwrap();
        let cols = sect.columns.as_ref().unwrap();
        assert_eq!(cols.num, Some(2));
        assert_eq!(cols.space, Some(Twips(720)));
        assert_eq!(cols.equal_width, Some(true));
    }

    #[test]
    fn set_page_size() {
        let mut doc = Document::new();
        doc.set_page_size(Length::cm(21.0), Length::cm(29.7));
        let sect = doc.section_properties().unwrap();
        // A4: ~11906tw x ~16838tw
        let w = sect.page_width.unwrap().0;
        let h = sect.page_height.unwrap().0;
        assert!((w - 11906).abs() < 5);
        assert!((h - 16838).abs() < 5);
    }

    #[test]
    fn set_different_first_page() {
        let mut doc = Document::new();
        doc.set_different_first_page(true);
        assert_eq!(doc.section_properties().unwrap().title_pg, Some(true));
    }

    #[test]
    fn content_insertion_api() {
        let mut doc = Document::new();
        doc.add_paragraph("First");
        doc.add_paragraph("Third");

        // Insert in middle
        doc.insert_paragraph(1, "Second");
        assert_eq!(doc.content_count(), 3);
        let paras = doc.paragraphs();
        assert_eq!(paras[0].text(), "First");
        assert_eq!(paras[1].text(), "Second");
        assert_eq!(paras[2].text(), "Third");

        // Insert at beginning
        doc.insert_paragraph(0, "Zeroth");
        assert_eq!(doc.content_count(), 4);
        assert_eq!(doc.paragraphs()[0].text(), "Zeroth");
    }

    #[test]
    fn find_content_index_and_remove() {
        let mut doc = Document::new();
        doc.add_paragraph("Hello");
        doc.add_paragraph("{{PLACEHOLDER}}");
        doc.add_paragraph("World");

        assert_eq!(doc.find_content_index("{{PLACEHOLDER}}"), Some(1));
        assert_eq!(doc.find_content_index("NONEXISTENT"), None);

        assert!(doc.remove_content(1));
        assert_eq!(doc.content_count(), 2);
        assert_eq!(doc.paragraphs()[1].text(), "World");

        // Out of bounds
        assert!(!doc.remove_content(10));
    }

    #[test]
    fn insert_table_at_index() {
        let mut doc = Document::new();
        doc.add_paragraph("Before");
        doc.add_paragraph("After");

        doc.insert_table(1, 2, 3);
        assert_eq!(doc.content_count(), 3);
        assert_eq!(doc.table_count(), 1);
        // Paragraphs are still in correct order
        let paras = doc.paragraphs();
        assert_eq!(paras[0].text(), "Before");
        assert_eq!(paras[1].text(), "After");
    }

    #[test]
    fn replace_text_in_body() {
        let mut doc = Document::new();
        doc.add_paragraph("Hello {{name}}!");
        doc.add_paragraph("Welcome to {{company}}.");

        let count = doc.replace_text("{{name}}", "Alice");
        assert_eq!(count, 1);
        assert_eq!(doc.paragraphs()[0].text(), "Hello Alice!");

        let count = doc.replace_text("{{company}}", "Acme");
        assert_eq!(count, 1);
        assert_eq!(doc.paragraphs()[1].text(), "Welcome to Acme.");
    }

    #[test]
    fn replace_text_in_header_and_footer() {
        let mut doc = Document::new();
        doc.set_header("Header: {{title}}");
        doc.set_footer("Footer: {{title}}");
        doc.add_paragraph("Body: {{title}}");

        let count = doc.replace_text("{{title}}", "My Doc");
        assert_eq!(count, 3);

        assert_eq!(doc.paragraphs()[0].text(), "Body: My Doc");
        assert_eq!(doc.header_text().unwrap(), "Header: My Doc");
        assert_eq!(doc.footer_text().unwrap(), "Footer: My Doc");
    }

    #[test]
    fn replace_all_batch() {
        let mut doc = Document::new();
        doc.add_paragraph("{{a}} and {{b}}");

        let mut map = std::collections::HashMap::new();
        map.insert("{{a}}", "X");
        map.insert("{{b}}", "Y");
        let count = doc.replace_all(&map);
        assert_eq!(count, 2);
        assert_eq!(doc.paragraphs()[0].text(), "X and Y");
    }

    #[test]
    fn template_workflow_round_trip() {
        let mut doc = Document::new();
        doc.add_paragraph("Company: {{company}}");
        doc.add_paragraph("Date: {{date}}");

        doc.replace_text("{{company}}", "Acme Corp");
        doc.replace_text("{{date}}", "2026-02-22");

        // Round-trip
        let bytes = doc.to_bytes().unwrap();
        let doc2 = Document::from_bytes(&bytes).unwrap();
        assert_eq!(doc2.paragraphs()[0].text(), "Company: Acme Corp");
        assert_eq!(doc2.paragraphs()[1].text(), "Date: 2026-02-22");
    }

    #[test]
    fn add_background_image_round_trip() {
        // Create a minimal 1x1 PNG
        let png_data: Vec<u8> = vec![
            0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, // PNG signature
            0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, // IHDR chunk
            0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, // 1x1
            0x08, 0x02, 0x00, 0x00, 0x00, 0x90, 0x77, 0x53, 0xde, 0x00, 0x00, 0x00, 0x0c, 0x49,
            0x44, 0x41, 0x54, // IDAT chunk
            0x08, 0xd7, 0x63, 0xf8, 0xcf, 0xc0, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0xe2, 0x21,
            0xbc, 0x33, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, // IEND chunk
            0xae, 0x42, 0x60, 0x82,
        ];

        let mut doc = Document::new();
        doc.add_paragraph("Hello World");
        doc.add_background_image(&png_data, "bg.png");

        // Background image paragraph should be at index 0
        assert_eq!(doc.content_count(), 2);

        // Round-trip
        let bytes = doc.to_bytes().unwrap();
        let doc2 = Document::from_bytes(&bytes).unwrap();

        // Should still have 2 content items
        assert_eq!(doc2.content_count(), 2);
        // The second paragraph should have our text
        assert_eq!(doc2.paragraphs().last().unwrap().text(), "Hello World");
    }

    #[test]
    fn add_anchored_image() {
        let png_data: Vec<u8> = vec![
            0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48,
            0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x02, 0x00, 0x00,
            0x00, 0x90, 0x77, 0x53, 0xde, 0x00, 0x00, 0x00, 0x0c, 0x49, 0x44, 0x41, 0x54, 0x08,
            0xd7, 0x63, 0xf8, 0xcf, 0xc0, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0xe2, 0x21, 0xbc,
            0x33, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82,
        ];

        let mut doc = Document::new();
        doc.add_paragraph("Content");
        doc.add_anchored_image(
            &png_data,
            "overlay.png",
            Length::inches(4.0),
            Length::inches(3.0),
            false,
        );
        assert_eq!(doc.content_count(), 2);
    }

    #[test]
    fn insert_toc_basic() {
        let mut doc = Document::new();
        doc.add_paragraph("Introduction");
        doc.add_paragraph("Chapter 1").style("Heading1");
        doc.add_paragraph("Some text in chapter 1.");
        doc.add_paragraph("Section 1.1").style("Heading2");
        doc.add_paragraph("Text in section 1.1.");
        doc.add_paragraph("Chapter 2").style("Heading1");
        doc.add_paragraph("Text in chapter 2.");

        // Before TOC: 7 content elements
        assert_eq!(doc.content_count(), 7);

        // Insert TOC at index 0 with max_level 2
        doc.insert_toc(0, 2);

        // TOC adds: 1 title + 3 heading entries (Ch1, Sec1.1, Ch2) = 4 paragraphs
        assert_eq!(doc.content_count(), 11);

        // Verify TOC title
        let paras = doc.paragraphs();
        assert_eq!(paras[0].text(), "Table of Contents");

        // Verify TOC entries contain heading text
        assert_eq!(paras[1].text(), "Chapter 1\t");
        assert_eq!(paras[2].text(), "Section 1.1\t");
        assert_eq!(paras[3].text(), "Chapter 2\t");

        // Verify round-trip: save and re-open
        let bytes = doc.to_bytes().expect("should serialize");
        let doc2 = Document::from_bytes(&bytes).expect("should open");
        assert_eq!(doc2.content_count(), 11);
        let paras2 = doc2.paragraphs();
        assert_eq!(paras2[0].text(), "Table of Contents");
    }

    #[test]
    fn append_documents() {
        let mut doc_a = Document::new();
        doc_a.add_paragraph("Paragraph A1");
        doc_a.add_paragraph("Paragraph A2");

        let mut doc_b = Document::new();
        doc_b.add_paragraph("Paragraph B1");
        doc_b.add_paragraph("Paragraph B2");
        doc_b.add_paragraph("Paragraph B3");

        assert_eq!(doc_a.content_count(), 2);
        doc_a.append(&doc_b);
        assert_eq!(doc_a.content_count(), 5);

        let paras = doc_a.paragraphs();
        assert_eq!(paras[0].text(), "Paragraph A1");
        assert_eq!(paras[1].text(), "Paragraph A2");
        assert_eq!(paras[2].text(), "Paragraph B1");
        assert_eq!(paras[3].text(), "Paragraph B2");
        assert_eq!(paras[4].text(), "Paragraph B3");

        // Verify round-trip
        let bytes = doc_a.to_bytes().expect("serialize");
        let reopened = Document::from_bytes(&bytes).expect("open");
        assert_eq!(reopened.content_count(), 5);
    }

    #[test]
    fn append_with_section_break() {
        let mut doc_a = Document::new();
        doc_a.add_paragraph("A1");

        let mut doc_b = Document::new();
        doc_b.add_paragraph("B1");

        doc_a.append_with_break(&doc_b, crate::SectionBreak::Continuous);
        // 1 original + 1 section break paragraph + 1 merged = 3
        assert_eq!(doc_a.content_count(), 3);
    }

    #[test]
    fn insert_document_at_index() {
        let mut doc_a = Document::new();
        doc_a.add_paragraph("First");
        doc_a.add_paragraph("Last");

        let mut doc_b = Document::new();
        doc_b.add_paragraph("Middle 1");
        doc_b.add_paragraph("Middle 2");

        doc_a.insert_document(1, &doc_b);
        assert_eq!(doc_a.content_count(), 4);

        let paras = doc_a.paragraphs();
        assert_eq!(paras[0].text(), "First");
        assert_eq!(paras[1].text(), "Middle 1");
        assert_eq!(paras[2].text(), "Middle 2");
        assert_eq!(paras[3].text(), "Last");
    }

    #[test]
    fn merge_deduplicates_styles() {
        let mut doc_a = Document::new();
        doc_a.add_paragraph("A").style("Heading1");

        let mut doc_b = Document::new();
        doc_b.add_paragraph("B").style("Heading1");
        doc_b.add_style(
            crate::style::StyleBuilder::paragraph("CustomB", "Custom B").based_on("Normal"),
        );
        doc_b.add_paragraph("C").style("CustomB");

        let styles_before = doc_a.styles.styles.len();
        doc_a.append(&doc_b);
        let styles_after = doc_a.styles.styles.len();

        // Heading1 already existed, so only CustomB should be added
        assert_eq!(styles_after, styles_before + 1);
    }

    #[test]
    fn headings_and_outline() {
        let mut doc = Document::new();
        doc.add_paragraph("Intro");
        doc.add_paragraph("Chapter 1").style("Heading1");
        doc.add_paragraph("Section 1.1").style("Heading2");
        doc.add_paragraph("Section 1.2").style("Heading2");
        doc.add_paragraph("Chapter 2").style("Heading1");
        doc.add_paragraph("Section 2.1").style("Heading2");
        doc.add_paragraph("Sub 2.1.1").style("Heading3");

        let headings = doc.headings();
        assert_eq!(headings.len(), 6);
        assert_eq!(headings[0], (1, "Chapter 1".to_string()));
        assert_eq!(headings[1], (2, "Section 1.1".to_string()));
        assert_eq!(headings[5], (3, "Sub 2.1.1".to_string()));

        let outline = doc.document_outline();
        assert_eq!(outline.len(), 2); // Two h1 nodes
        assert_eq!(outline[0].text, "Chapter 1");
        assert_eq!(outline[0].children.len(), 2); // 1.1 and 1.2
        assert_eq!(outline[1].text, "Chapter 2");
        assert_eq!(outline[1].children.len(), 1); // 2.1
        assert_eq!(outline[1].children[0].children.len(), 1); // 2.1.1
    }

    #[test]
    fn word_count_basic() {
        let mut doc = Document::new();
        doc.add_paragraph("Hello world");
        doc.add_paragraph("Three more words");
        assert_eq!(doc.word_count(), 5);
    }

    #[test]
    fn audit_accessibility_missing_metadata() {
        let doc = Document::new();
        let issues = doc.audit_accessibility();
        // New document has no title or author
        assert!(issues.iter().any(|i| i.message.contains("no title")));
        assert!(issues.iter().any(|i| i.message.contains("no author")));
    }

    #[test]
    fn audit_heading_level_gap() {
        let mut doc = Document::new();
        doc.set_title("Test");
        doc.set_author("Test");
        doc.add_paragraph("Ch 1").style("Heading1");
        doc.add_paragraph("Skip to 3").style("Heading3");

        let issues = doc.audit_accessibility();
        assert!(
            issues
                .iter()
                .any(|i| i.message.contains("Heading level gap"))
        );
    }

    #[test]
    fn links_returns_empty_for_no_hyperlinks() {
        let mut doc = Document::new();
        doc.add_paragraph("No links here.");
        assert!(doc.links().is_empty());
    }

    #[test]
    fn images_returns_empty_for_text_only() {
        let mut doc = Document::new();
        doc.add_paragraph("Just text.");
        assert!(doc.images().is_empty());
    }

    #[test]
    fn numbering_getter_round_trips() {
        let mut doc = Document::new();
        doc.add_bullet_list_item("bullet item", 0);
        doc.add_numbered_list_item("numbered item", 0);
        doc.add_paragraph("plain");

        let bytes = doc.to_bytes().unwrap();
        let doc2 = Document::from_bytes(&bytes).unwrap();
        let paras = doc2.paragraphs();

        let (bullet_id, bullet_lvl) = paras[0].numbering().expect("bullet numbering");
        assert_eq!(bullet_lvl, 0);
        assert_eq!(doc2.numbering_is_bullet(bullet_id), Some(true));

        let (num_id, _) = paras[1].numbering().expect("numbered numbering");
        assert_eq!(doc2.numbering_is_bullet(num_id), Some(false));

        assert!(paras[2].numbering().is_none());
    }

    #[test]
    fn highlight_getter_round_trips() {
        let mut doc = Document::new();
        {
            let mut p = doc.add_paragraph("");
            let mut r = p.add_run("glowing");
            r = r.highlight("yellow");
            let _ = r;
        }

        let bytes = doc.to_bytes().unwrap();
        let doc2 = Document::from_bytes(&bytes).unwrap();
        let paras = doc2.paragraphs();
        let run = paras[0].runs().next().expect("run");
        assert_eq!(run.highlight().as_deref(), Some("yellow"));
    }

    #[test]
    fn run_style_id_getter_round_trips() {
        let mut doc = Document::new();
        {
            let mut p = doc.add_paragraph("");
            let mut r = p.add_run("code text");
            r = r.style("SourceText");
            let _ = r;
        }

        let bytes = doc.to_bytes().unwrap();
        let doc2 = Document::from_bytes(&bytes).unwrap();
        let paras = doc2.paragraphs();
        let run = paras[0].runs().next().expect("run");
        assert_eq!(run.style_id(), Some("SourceText"));
    }

    #[test]
    fn append_hyperlink_round_trips() {
        let mut doc = Document::new();
        doc.add_paragraph("visit ");
        doc.append_hyperlink("GNOME", "https://gnome.org");

        let bytes = doc.to_bytes().unwrap();
        let doc2 = Document::from_bytes(&bytes).unwrap();

        let links = doc2.links();
        assert_eq!(links.len(), 1);
        assert_eq!(links[0].text, "GNOME");
        assert_eq!(links[0].url.as_deref(), Some("https://gnome.org"));
        assert_eq!(doc2.paragraphs()[0].text(), "visit GNOME");

        let paras = doc2.paragraphs();
        let spans = paras[0].hyperlink_spans();
        assert_eq!(spans.len(), 1);
        let (start, end, rel_id) = (spans[0].0, spans[0].1, spans[0].2);
        assert_eq!(end - start, 1);
        let url = doc2.hyperlink_url(rel_id.expect("rel id"));
        assert_eq!(url.as_deref(), Some("https://gnome.org"));
    }

    #[test]
    fn paragraph_hard_break_and_table_cell_hyperlink_round_trip() {
        let mut doc = Document::new();
        let relationship_id = doc.add_hyperlink_relationship("https://example.com/table");

        let mut paragraph = doc.add_paragraph("");
        paragraph.add_run("before");
        paragraph.add_line_break();
        paragraph.add_run("after");

        let mut table = doc.add_table(1, 1);
        let mut cell = table.cell(0, 0).expect("cell");
        cell.remove_first_empty_paragraph();
        cell.add_paragraph("")
            .add_hyperlink("table link", &relationship_id)
            .bold(true);

        let bytes = doc.to_bytes().unwrap();
        let reopened = Document::from_bytes(&bytes).unwrap();

        assert_eq!(reopened.paragraphs()[0].text(), "before\nafter");
        let tables = reopened.tables();
        let cell = tables[0].cell(0, 0).expect("cell");
        let paragraph = cell.paragraphs().next().expect("paragraph");
        assert_eq!(paragraph.text(), "table link");
        assert!(paragraph.runs().next().expect("run").is_bold());
        let spans = paragraph.hyperlink_spans();
        assert_eq!(spans.len(), 1);
        assert_eq!(
            reopened.hyperlink_url(spans[0].2.expect("relationship id")),
            Some("https://example.com/table".to_string())
        );
    }

    #[test]
    fn rejected_list_level_update_does_not_materialize_numbering() {
        let mut doc = Document::new();
        assert!(doc.numbering.is_none());

        assert!(!doc.set_list_level(999, 1, ListLevel::decimal()));

        assert!(
            doc.numbering.is_none(),
            "a rejected setter must not add an empty numbering part"
        );
    }

    #[test]
    fn custom_list_and_paragraph_numbering_enforce_the_nine_level_contract() {
        let mut doc = Document::new();
        let levels = vec![ListLevel::decimal(); 10];
        let num_id = doc.add_list_definition(&levels);
        assert_eq!(
            doc.numbering.as_ref().unwrap().abstract_nums[0]
                .levels
                .len(),
            9
        );

        let mut paragraph = doc.add_paragraph("item");
        assert!(!paragraph.set_numbering(num_id, 9));
        assert_eq!(
            paragraph.inner.properties.as_ref().and_then(|p| p.num_id),
            None
        );
        assert!(paragraph.set_numbering(num_id, 8));
        assert_eq!(
            paragraph.inner.properties.as_ref().unwrap().num_ilvl,
            Some(8)
        );
    }

    #[test]
    fn picture_round_trips() {
        // 1x1 red PNG
        let png: &[u8] = &[
            0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48,
            0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x02, 0x00, 0x00,
            0x00, 0x90, 0x77, 0x53, 0xDE, 0x00, 0x00, 0x00, 0x0C, 0x49, 0x44, 0x41, 0x54, 0x08,
            0xD7, 0x63, 0xF8, 0xCF, 0xC0, 0x00, 0x00, 0x00, 0x03, 0x00, 0x01, 0x9E, 0xDD, 0x22,
            0x71, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82,
        ];
        let mut doc = Document::new();
        doc.add_paragraph("before");
        doc.add_picture(png, "dot.png", Length::inches(1.0), Length::inches(1.0));

        let bytes = doc.to_bytes().unwrap();
        let doc2 = Document::from_bytes(&bytes).unwrap();
        let paras = doc2.paragraphs();
        let mut found = None;
        for p in &paras {
            for r in p.runs() {
                if let Some((rel, _alt)) = r.inline_image() {
                    found = Some(rel.to_string());
                }
            }
        }
        let rel = found.expect("no inline image found on read");
        let data = doc2.image_data(&rel).expect("image bytes missing");
        assert_eq!(data, png);
    }

    #[test]
    fn layout_resolves_relationship_images_to_shared_media() {
        let png: &[u8] = &[
            0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48,
            0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x02, 0x00, 0x00,
            0x00, 0x90, 0x77, 0x53, 0xDE, 0x00, 0x00, 0x00, 0x0C, 0x49, 0x44, 0x41, 0x54, 0x08,
            0xD7, 0x63, 0xF8, 0xCF, 0xC0, 0x00, 0x00, 0x00, 0x03, 0x00, 0x01, 0x9E, 0xDD, 0x22,
            0x71, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82,
        ];
        let mut document = Document::new();
        document.add_picture(png, "first.png", Length::inches(1.0), Length::inches(1.0));
        document.add_picture(png, "second.png", Length::inches(1.0), Length::inches(1.0));

        let page = document
            .layout_page(0)
            .expect("layout should succeed")
            .expect("document should have a first page");
        let images = page
            .elements
            .iter()
            .filter_map(|element| match element {
                oxml_layout::PositionedElement::Image {
                    data,
                    content_type,
                    media_id,
                    ..
                } => Some((data, content_type, media_id)),
                _ => None,
            })
            .collect::<Vec<_>>();

        assert_eq!(images.len(), 2);
        assert!(images.iter().all(|(data, _, _)| data.as_slice() == png));
        assert!(
            images
                .iter()
                .all(|(_, content_type, _)| *content_type == "image/png")
        );
        assert_eq!(*images[0].2, oxml_layout::MediaId::from_bytes(png));
        assert_eq!(images[0].2, images[1].2);
    }
}

#[cfg(test)]
mod hyperlink_span_tests {
    use super::*;
    use rdocx_oxml::text::HyperlinkSpan;

    /// `HyperlinkSpan`'s bounds are public, so a caller building the OXML model
    /// by hand can hand us a range past the end of `runs`. `links()` used to
    /// slice with it and panic.
    #[test]
    fn links_clamps_out_of_range_spans() {
        let mut doc = Document::new();
        {
            let mut para = doc.add_paragraph("");
            para.add_run("one");
            para.add_run("two");
        }

        let BodyContent::Paragraph(p) = &mut doc.document.body.content[0] else {
            unreachable!("just added a paragraph")
        };
        p.hyperlinks.push(HyperlinkSpan {
            rel_id: None,
            anchor: Some("bookmark".to_string()),
            run_start: 1,
            run_end: 99,
        });
        p.hyperlinks.push(HyperlinkSpan {
            rel_id: None,
            anchor: Some("inverted".to_string()),
            run_start: 5,
            run_end: 1,
        });

        let links = doc.links();

        assert_eq!(links.len(), 2);
        assert_eq!(links[0].text, "two");
        assert_eq!(links[1].text, "");
    }
}

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

    /// Build a TrueType header with a two-entry table directory.
    fn fake_font() -> Vec<u8> {
        let mut data = Vec::new();
        data.extend(b"\x00\x01\x00\x00"); // sfntVersion
        data.extend(2u16.to_be_bytes()); // numTables
        data.extend(32u16.to_be_bytes()); // searchRange
        data.extend(1u16.to_be_bytes()); // entrySelector
        data.extend(0u16.to_be_bytes()); // rangeShift
        for (tag, offset, length) in [(b"cmap", 96u32, 40u32), (b"head", 136, 54)] {
            data.extend(tag); // tag
            data.extend(0u32.to_be_bytes()); // checksum
            data.extend(offset.to_be_bytes());
            data.extend(length.to_be_bytes());
        }
        data.extend((0u8..64).map(|i| i.wrapping_mul(7)));
        data
    }

    fn obfuscate(font: &[u8], key: &[u8; 16]) -> Vec<u8> {
        let mut out = font.to_vec();
        for (i, byte) in out.iter_mut().take(32).enumerate() {
            *byte ^= key[i % 16];
        }
        out
    }

    const GUID_HEX: &str = "00112233445566778899AABBCCDDEEFF";

    fn guid_bytes() -> [u8; 16] {
        let mut g = [0u8; 16];
        for (i, b) in g.iter_mut().enumerate() {
            *b = u8::from_str_radix(&GUID_HEX[i * 2..i * 2 + 2], 16).unwrap();
        }
        g
    }

    #[test]
    fn recovers_font_under_either_key_convention() {
        let font = fake_font();
        let name = format!("{GUID_HEX}.odttf");
        for key in odttf_key_candidates(&guid_bytes()) {
            let obfuscated = obfuscate(&font, &key);
            assert_eq!(
                deobfuscate_odttf(&obfuscated, &name).as_deref(),
                Some(font.as_slice()),
                "failed to recover font for key {key:02x?}",
            );
        }
    }

    #[test]
    fn rejects_data_that_does_not_decode_to_a_font() {
        // A GUID that matches nothing in the payload must not yield garbage.
        let junk = vec![0xAB; 64];
        let name = format!("{GUID_HEX}.odttf");
        assert_eq!(deobfuscate_odttf(&junk, &name), None);
    }

    #[test]
    fn rejects_short_or_malformed_input() {
        assert_eq!(deobfuscate_odttf(&[0u8; 8], "abc.odttf"), None);
        assert_eq!(deobfuscate_odttf(&[0u8; 64], "not-a-guid.odttf"), None);
    }

    #[test]
    fn accepts_braced_and_hyphenated_names() {
        let font = fake_font();
        let key = odttf_key_candidates(&guid_bytes())[0];
        let obfuscated = obfuscate(&font, &key);
        for name in [
            "{00112233-4455-6677-8899-AABBCCDDEEFF}.odttf",
            "00112233-4455-6677-8899-AABBCCDDEEFF.odttf",
        ] {
            assert_eq!(
                deobfuscate_odttf(&obfuscated, name).as_deref(),
                Some(font.as_slice()),
                "failed for {name}"
            );
        }
    }
}