text-document-io 1.11.1

Import/export for text-document: plain text, Markdown, HTML, LaTeX, DOCX
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
// Generated by Qleany v1.4.8 from feature_use_case.tera
use crate::ExportDocxDto;
use crate::ExportDocxResultDto;
use anyhow::{Result, anyhow};
use common::database::QueryUnitOfWork;
use common::database::rope_helpers::{block_content_via_store, block_document_position};
use common::entities::{
    Alignment, Block, Document, Frame, List, ListStyle, MarkerType, Root, SemanticRole, Table,
    TableCell,
};
use common::format_runs::{InlineContent, InlineSegment};
use common::long_operation::LongOperation;
use common::parser_tools::{DocumentComments, DocumentMarks, ExportImages};
use common::types::{EntityId, ROOT_ENTITY_ID};
use regex::Regex;
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};

pub trait ExportDocxUnitOfWorkFactoryTrait: Send + Sync {
    fn create(&self) -> Box<dyn ExportDocxUnitOfWorkTrait>;
}

#[macros::uow_action(entity = "Root", action = "GetRO", thread_safe = true)]
#[macros::uow_action(entity = "Root", action = "GetRelationshipRO", thread_safe = true)]
#[macros::uow_action(entity = "Document", action = "GetRO", thread_safe = true)]
#[macros::uow_action(entity = "Document", action = "GetRelationshipRO", thread_safe = true)]
#[macros::uow_action(entity = "Frame", action = "GetRO", thread_safe = true)]
#[macros::uow_action(entity = "Frame", action = "GetRelationshipRO", thread_safe = true)]
#[macros::uow_action(entity = "Block", action = "GetRO", thread_safe = true)]
#[macros::uow_action(entity = "Block", action = "GetMultiRO", thread_safe = true)]
#[macros::uow_action(entity = "Block", action = "GetRelationshipRO", thread_safe = true)]
#[macros::uow_action(entity = "List", action = "GetRO", thread_safe = true)]
#[macros::uow_action(entity = "Table", action = "GetRO", thread_safe = true)]
#[macros::uow_action(entity = "Table", action = "GetRelationshipRO", thread_safe = true)]
#[macros::uow_action(entity = "TableCell", action = "GetMultiRO", thread_safe = true)]
pub trait ExportDocxUnitOfWorkTrait: QueryUnitOfWork + Send + Sync {}

/// Each note's body as finished paragraphs, by label.
///
/// OOXML carries a footnote's text inside the run that references it, so the
/// body has to be in hand by the time a marker is built — the same inversion
/// LaTeX has, and why both pre-render rather than emitting at a definition site.
type NoteParagraphs = std::collections::HashMap<String, Vec<docx_rs::Paragraph>>;

/// What `build_run` needs to render a footnote reference correctly the
/// *second* time a label is cited.
///
/// OOXML has no construct for "the same footnote, cited again" through this
/// library: `docx-rs`'s `Docx::collect_footnotes()` turns *every*
/// `<w:footnoteReference>` it finds anywhere in the run tree into its own
/// `<w:footnote>` entry, unconditionally — so a second `add_footnote_reference`
/// call for a label already defined would not reuse that note, it would emit a
/// **second** `<w:footnote>` (duplicating the body) and, worse, share the first
/// one's `w:id`, which OOXML does not allow two definitions to share. So only
/// the label's first citation becomes a real, native footnote; a repeat prints
/// a plain run carrying the same number that citation already earned —
/// `numbers`' own reading-order marker table, styled with Word's built-in
/// `"FootnoteReference"` character style so it still *looks* like a footnote
/// mark, just without a second, duplicate definition underneath it.
struct FootnoteRefState<'a> {
    numbers: &'a crate::footnotes::Footnotes,
    /// Labels whose real `<w:footnoteReference>` has already been emitted —
    /// scoped to ONE pass over the document (a fresh, throwaway state per note
    /// while pre-rendering note bodies, the shared one for the main walk — see
    /// `build_docx`) so a nested citation inside one note's body can never be
    /// mistaken for the label's real, resolved citation out in the manuscript,
    /// which would silently swap a note's real content for a bare marker.
    emitted: std::cell::RefCell<std::collections::HashSet<String>>,
}

impl<'a> FootnoteRefState<'a> {
    fn new(numbers: &'a crate::footnotes::Footnotes) -> Self {
        FootnoteRefState {
            numbers,
            emitted: std::cell::RefCell::new(std::collections::HashSet::new()),
        }
    }
}

// ── Comment ranges (M-T1) ────────────────────────────────────────────────────────────
//
// A `common::parser_tools::DocumentComment` carries a character range in the document's
// addressable space plus a flat list of replies. Turning that into real DOCX comments takes
// three separate pieces of machinery:
//
//  1. `prepare_comments` resolves every thread (root + each reply, since a reply anchors to
//     the exact same range as the comment it answers — see `DocumentComment`'s own doc
//     comment) into a `PreparedSpan`: a docx-rs numeric id, a deterministic paragraph id
//     for its one-paragraph body, and the built `docx_rs::Comment` itself.
//  2. `CommentEmitState` (built from that list) is threaded through the block-rendering walk
//     so `render_block`/`add_inline_content` can ask "which comments open or close inside
//     *this* block" and split whichever run or hyperlink child straddles a boundary.
//  3. `patch_comment_extras` fixes up three fields `docx-rs` 0.4.22's builder API cannot set
//     at all (`w15:done`, `w:initials`, and a durable uid) by rewriting the raw
//     `word/comments.xml` / `word/commentsExtended.xml` bytes `Docx::build()` hands back,
//     before those bytes are packed to the zip.

/// One comment or reply, resolved to what `docx-rs` needs to place and later identify it.
///
/// A comment thread with N replies produces N+1 of these, all sharing the thread's own
/// `start`/`end` — see this module's `DocumentComment` note above for why a reply has no range
/// of its own. Each one gets its own `CommentRangeStart`/`CommentRangeEnd` pair anchored at
/// that shared range: real Word output does the same thing (a thread with replies has as many
/// stacked range markers in the body as it has comments), and it is the only way to get a
/// reply into `comments.xml` at all — see `patch_comment_extras`'s doc comment for why.
pub(crate) struct PreparedSpan {
    /// The plain, sequentially-assigned `usize` docx-rs uses for `w:id` /
    /// `w:commentRangeStart`/`w:commentRangeEnd`/`w:commentReference`. Never touched by
    /// `Docx::build()`'s paragraph-id dedup pass (that only rewrites `Paragraph::id`, a
    /// completely different id space) — safe to use as a stable lookup key after `build()`.
    ///
    /// Shared by comments and marks, because [`CommentEmitState`]'s started/ended sets are keyed
    /// by it alone and two spans sharing one would mark each other placed. A mark's *bookmark*
    /// id is a separate OOXML id space and lives in [`SpanEmit::Mark`].
    id: usize,
    /// The uid this span carries — `DocumentComment::uid` for a comment root,
    /// `CommentReply::uid` for a reply, and the bookmark's own name for a mark.
    uid: String,
    /// `[start, end)` in the document's addressable character space — for a comment, the
    /// thread's own range, shared by every `PreparedSpan` in the same thread.
    start: u32,
    end: u32,
    /// Whether failing to anchor this span fails the export. True for comments (a note the
    /// caller asked for that is silently missing is data loss); false for marks, which are an
    /// aid to reading the file back rather than content — see the ODF writer's
    /// `PreparedSpan::required` for the full reasoning, which is identical here.
    required: bool,
    /// What this span actually writes at its two boundaries.
    emit: SpanEmit,
}

/// The kind-specific half of a [`PreparedSpan`].
///
/// Comments and marks share every bit of the range arithmetic — block windowing, per-piece
/// marker resolution, run splitting — and differ only in the builder calls at the boundary and
/// in the post-`build()` patch pass, which is comment-only. Keeping the difference in one enum
/// rather than in two parallel pipelines is what stops the two from drifting.
enum SpanEmit {
    Comment {
        author_initials: String,
        /// Only meaningful on the root (`DocumentComment::resolved`); always `false` for a
        /// reply, which carries no resolved state of its own.
        resolved: bool,
        /// The built `docx_rs::Comment`, ready to hand to
        /// `Paragraph`/`Hyperlink::add_comment_start`. Cloned exactly once (each id opens
        /// exactly one range), but `Comment` is cheap and the clone keeps `PreparedSpan` itself
        /// immutable through the whole render walk.
        comment: docx_rs::Comment,
    },
    Mark {
        /// OOXML's own bookmark id space, which is unrelated to `w:id` on a comment. Named only
        /// on `w:bookmarkStart`; `w:bookmarkEnd` carries the id alone, which is why this has to
        /// be kept rather than re-derived from the name at the closing boundary.
        bookmark_id: usize,
        name: String,
        /// A zero-length bookmark. OOXML has no self-closing spelling the way ODF's
        /// `<text:bookmark/>` does, so a point mark is a `bookmarkStart` immediately followed by
        /// its `bookmarkEnd`, both emitted at the opening boundary — the closing one is never
        /// reached, since `window_for_block`'s strictly-greater `ends` test never selects an
        /// empty range.
        point: bool,
    },
}

impl PreparedSpan {
    /// The comment-specific fields, for the passes that only apply to comments (the
    /// `word/comments.xml` patch). `None` for a mark.
    fn as_comment(&self) -> Option<(&str, bool, &docx_rs::Comment)> {
        match &self.emit {
            SpanEmit::Comment {
                author_initials,
                resolved,
                comment,
            } => Some((author_initials, *resolved, comment)),
            SpanEmit::Mark { .. } => None,
        }
    }
}

/// FNV-1a (32-bit) — a small, dependency-free, deterministic hash used only to turn a
/// comment's own uid into a paragraph id (see `prepare_comments`). Not a security boundary;
/// picked for being tiny and stable across Rust versions, unlike `DefaultHasher`.
fn fnv1a32(s: &str) -> u32 {
    let mut hash: u32 = 0x811c_9dc5;
    for b in s.bytes() {
        hash ^= b as u32;
        hash = hash.wrapping_mul(0x0100_0193);
    }
    hash
}

/// Resolve every comment thread in `comments` into its flat `PreparedSpan` list, in
/// document order (root immediately followed by its own replies, in the order they were
/// authored).
///
/// # Why the paragraph id is hashed rather than sequential
///
/// Each body gets `Paragraph::id(..)` set to an 8-hex-digit id derived from its own uid,
/// deterministic and reproducible across identical exports — but the actual reason it is a
/// *hash* rather than, say, `"00000001"`, `"00000002"`, ... is collision avoidance:
/// `docx-rs` hands out exactly that small sequential range (reset to 1 at the top of every
/// `build()`) to every OTHER paragraph in the document that never had `.id(..)` called on it.
/// Landing in a disjoint part of the id space keeps `Docx::build()`'s own dedup pass
/// (`refresh_duplicate_para_ids`) from ever needing to touch these — though the writer does
/// not *rely* on that being guaranteed (see `patch_comment_extras`'s doc comment for the code
/// path that stays correct even if it collides anyway).
fn prepare_comments(comments: &DocumentComments) -> Vec<PreparedSpan> {
    let mut out = Vec::new();
    let mut used_para_ids: HashSet<String> = HashSet::new();
    let mut next_id: usize = 1;

    fn para_id_for(seed: &str, used: &mut HashSet<String>) -> String {
        let mut h = fnv1a32(seed);
        loop {
            let candidate = format!("{h:08x}");
            if used.insert(candidate.clone()) {
                return candidate;
            }
            h = h.wrapping_add(1);
        }
    }

    for c in comments.in_document_order() {
        let root_id = next_id;
        next_id += 1;
        let root_para_id = para_id_for(&c.uid, &mut used_para_ids);
        let root_comment = docx_rs::Comment::new(root_id)
            .author(c.author.clone())
            .date(c.date.clone())
            .add_paragraph(render_comment_body(&c.body).id(root_para_id.clone()));
        out.push(PreparedSpan {
            id: root_id,
            uid: c.uid.clone(),
            start: c.start,
            end: c.end,
            required: true,
            emit: SpanEmit::Comment {
                author_initials: c.author_initials.clone(),
                resolved: c.resolved,
                comment: root_comment,
            },
        });

        for reply in &c.replies {
            let reply_id = next_id;
            next_id += 1;
            let reply_para_id = para_id_for(&reply.uid, &mut used_para_ids);
            let reply_comment = docx_rs::Comment::new(reply_id)
                .author(reply.author.clone())
                .date(reply.date.clone())
                .add_paragraph(render_comment_body(&reply.body).id(reply_para_id.clone()))
                .parent_comment_id(root_id);
            out.push(PreparedSpan {
                id: reply_id,
                uid: reply.uid.clone(),
                start: c.start,
                end: c.end,
                required: true,
                emit: SpanEmit::Comment {
                    author_initials: reply.author_initials.clone(),
                    // A reply carries no resolved state of its own — only the thread it belongs
                    // to (`DocumentComment::resolved`) does.
                    resolved: false,
                    comment: reply_comment,
                },
            });
        }
    }
    out
}

/// Resolve every comment thread *and* every round-trip mark into one ordered
/// [`PreparedSpan`] list — the OOXML twin of `export_odt_uc::prepare_spans`.
fn prepare_spans(comments: &DocumentComments, marks: &DocumentMarks) -> Result<Vec<PreparedSpan>> {
    let mut out = prepare_comments(comments);
    let first_span_id = out.len() + 1;
    out.extend(prepare_marks(marks, first_span_id)?);
    Ok(out)
}

/// Resolve every round-trip mark into a [`PreparedSpan`].
///
/// Refuses the whole export on an invalid name rather than dropping the offender, for the same
/// reason `export_odt_uc::prepare_marks` does: these names are minted by the host from its own
/// identifiers, so a bad one is a caller bug, and a silently missing mark surfaces much later as
/// a returning file that mysteriously fails to match.
///
/// Bookmark ids start at 0 and are their own OOXML id space, unrelated to `w:id` on a comment.
fn prepare_marks(marks: &DocumentMarks, first_span_id: usize) -> Result<Vec<PreparedSpan>> {
    marks
        .validate()
        .map_err(|e| anyhow!("invalid round-trip mark(s): {e}"))?;

    Ok(marks
        .in_document_order()
        .into_iter()
        .enumerate()
        .map(|(i, m)| PreparedSpan {
            id: first_span_id + i,
            uid: m.name.clone(),
            start: m.start,
            end: m.end,
            required: false,
            emit: SpanEmit::Mark {
                bookmark_id: i,
                name: m.name.clone(),
                point: m.is_point(),
            },
        })
        .collect())
}

/// Render a comment or reply body's Djot source into exactly **one** `docx_rs::Paragraph`.
///
/// Exactly one, never more, even when the source has several block-level paragraphs — this is
/// load-bearing, not a simplification for its own sake. `docx-rs` 0.4.22's auto-collector
/// (`push_comment_and_comment_extended` in `documents/mod.rs`) walks `comment.children` and,
/// for *every* `CommentChild::Paragraph` it finds, pushes the **whole** `Comment` into
/// `comments.xml` again and mints another `commentEx` entry for it. A two-paragraph body would
/// therefore silently duplicate its entire `<w:comment>` element and produce two conflicting
/// `w15:paraId`s for what is supposed to be one thread. A block break in the source becomes a
/// `<w:br/>` inside this one paragraph instead, exactly the way `render_code_block` folds a
/// fenced block's embedded newlines into line breaks within one paragraph.
///
/// Formatting support is deliberately narrow: bold, italic, underline, strikethrough, and
/// paragraph/line breaks — plain text for everything else (links, images, lists, tables,
/// footnotes, code spans). A margin note is short annotation prose, not manuscript content;
/// nothing here panics or drops text on an unsupported construct, it just renders as plain
/// text, so an unusual comment body degrades gracefully instead of failing the export.
fn render_comment_body(djot: &str) -> docx_rs::Paragraph {
    use docx_rs::*;
    use jotdown::{Container as C, Event as E, Parser};

    let mut paragraph = Paragraph::new();
    let mut bold = false;
    let mut italic = false;
    let mut underline = false;
    let mut strikeout = false;
    let mut buffer = String::new();
    let mut buf_bold = false;
    let mut buf_italic = false;
    let mut buf_underline = false;
    let mut buf_strikeout = false;
    let mut wrote_any_block = false;

    macro_rules! flush {
        () => {
            if !buffer.is_empty() {
                paragraph = append_formatted_text(
                    paragraph,
                    &buffer,
                    buf_bold,
                    buf_italic,
                    buf_underline,
                    buf_strikeout,
                );
                buffer.clear();
            }
        };
    }

    for event in Parser::new(djot) {
        match event {
            E::Start(C::Paragraph, _) | E::Start(C::Heading { .. }, _) => {
                if wrote_any_block {
                    flush!();
                    paragraph = paragraph.add_run(Run::new().add_break(BreakType::TextWrapping));
                }
            }
            E::End(C::Paragraph) | E::End(C::Heading { .. }) => {
                flush!();
                wrote_any_block = true;
            }
            E::Start(C::Strong, _) => {
                flush!();
                bold = true;
            }
            E::End(C::Strong) => {
                flush!();
                bold = false;
            }
            E::Start(C::Emphasis, _) => {
                flush!();
                italic = true;
            }
            E::End(C::Emphasis) => {
                flush!();
                italic = false;
            }
            E::Start(C::Insert, _) => {
                flush!();
                underline = true;
            }
            E::End(C::Insert) => {
                flush!();
                underline = false;
            }
            E::Start(C::Delete, _) => {
                flush!();
                strikeout = true;
            }
            E::End(C::Delete) => {
                flush!();
                strikeout = false;
            }
            E::Str(s) => {
                if buffer.is_empty() {
                    buf_bold = bold;
                    buf_italic = italic;
                    buf_underline = underline;
                    buf_strikeout = strikeout;
                }
                buffer.push_str(s.as_ref());
            }
            E::LeftSingleQuote => buffer.push('\u{2018}'),
            E::RightSingleQuote => buffer.push('\u{2019}'),
            E::LeftDoubleQuote => buffer.push('\u{201C}'),
            E::RightDoubleQuote => buffer.push('\u{201D}'),
            E::Ellipsis => buffer.push('\u{2026}'),
            E::EnDash => buffer.push('\u{2013}'),
            E::EmDash => buffer.push('\u{2014}'),
            E::NonBreakingSpace => buffer.push('\u{00A0}'),
            // Exotic djot constructs (images, tables, footnotes, links, code blocks, ...)
            // contribute no text of their own here — see this function's doc comment.
            _ => {}
        }
    }
    flush!();
    paragraph
}

/// Append `text` to `paragraph` as one or more runs, splitting on embedded `\n` into
/// `<w:br/>`-separated runs — the same pattern `render_code_block` uses for a fenced block's
/// own line breaks.
fn append_formatted_text(
    mut paragraph: docx_rs::Paragraph,
    text: &str,
    bold: bool,
    italic: bool,
    underline: bool,
    strikeout: bool,
) -> docx_rs::Paragraph {
    use docx_rs::*;
    for (i, line) in text.split('\n').enumerate() {
        let mut run = Run::new();
        if i > 0 {
            run = run.add_break(BreakType::TextWrapping);
        }
        if !line.is_empty() {
            run = run.add_text(line);
        }
        if bold {
            run = run.bold();
        }
        if italic {
            run = run.italic();
        }
        if underline {
            run = run.underline("single");
        }
        if strikeout {
            run = run.strike();
        }
        paragraph = paragraph.add_run(run);
    }
    paragraph
}

/// One comment boundary event, resolved to a local character index inside the one inline
/// piece it falls in — see `markers_for_piece`.
enum Marker<'a> {
    Start(&'a PreparedSpan),
    End(&'a PreparedSpan),
}

/// The comments open or closing somewhere inside one block, and the bookkeeping needed to
/// prove every prepared comment found a home by the end of the document walk.
///
/// Built once per export (`build_docx`) and threaded by shared reference through
/// `render_frame_content`/`render_block` — `None` at call sites that render content outside
/// the document's addressable text (footnote bodies, table cells; see `render_block`'s doc
/// comment for why those are out of scope for comment ranges).
struct CommentEmitState<'a> {
    prepared: &'a [PreparedSpan],
    started: std::cell::RefCell<HashSet<usize>>,
    ended: std::cell::RefCell<HashSet<usize>>,
}

/// The prepared comments whose range starts, respectively ends, somewhere inside one block —
/// see `CommentEmitState::window_for_block`.
struct BlockCommentWindow<'a> {
    starts: Vec<&'a PreparedSpan>,
    ends: Vec<&'a PreparedSpan>,
}

impl<'a> CommentEmitState<'a> {
    fn new(prepared: &'a [PreparedSpan]) -> Self {
        Self {
            prepared,
            started: std::cell::RefCell::new(HashSet::new()),
            ended: std::cell::RefCell::new(HashSet::new()),
        }
    }

    /// Comments whose start, respectively end, falls inside `[block_start, block_end)` — or,
    /// for a genuinely empty block (`block_start == block_end`, e.g. a blank paragraph),
    /// comments collapsed to exactly that point. Blocks are visited in non-decreasing
    /// document-position order by every call site that passes `Some(state)`, so a thread
    /// spanning several blocks (its start block and end block differ) opens in the first and
    /// closes in the last with nothing to do in between — no extra state needed beyond this
    /// per-block filter.
    fn window_for_block(&self, block_start: u32, block_end: u32) -> BlockCommentWindow<'a> {
        let empty = block_start == block_end;
        let mut starts: Vec<&'a PreparedSpan> = self
            .prepared
            .iter()
            .filter(|c| {
                (block_start <= c.start && c.start < block_end) || (empty && c.start == block_start)
            })
            .collect();
        starts.sort_by_key(|c| (c.start, c.id));
        let mut ends: Vec<&'a PreparedSpan> = self
            .prepared
            .iter()
            .filter(|c| {
                (block_start < c.end && c.end <= block_end) || (empty && c.end == block_end)
            })
            .collect();
        ends.sort_by_key(|c| (c.end, c.id));
        BlockCommentWindow { starts, ends }
    }

    fn mark_started(&self, id: usize) {
        self.started.borrow_mut().insert(id);
    }

    fn mark_ended(&self, id: usize) {
        self.ended.borrow_mut().insert(id);
    }

    /// Every prepared comment must have been both opened and closed exactly once by the time
    /// the whole document walk finishes, or its range never intersected any block this writer
    /// visited — out of bounds, or targeting a footnote body/table cell (deliberately outside
    /// the addressable-text walk; see `render_block`'s doc comment) — and it would otherwise
    /// vanish from the output with no trace at all. Surfaced here as one loud, actionable
    /// `Err` naming every orphan, rather than a `.docx` that silently opens with fewer
    /// comments than the caller asked for.
    fn ensure_all_anchored(&self) -> Result<()> {
        let started = self.started.borrow();
        let ended = self.ended.borrow();
        // `required` only. A round-trip mark that found no home degrades re-import to matching
        // by type and title, a designed fallback, and is not worth refusing to write the
        // manuscript over — see `PreparedSpan::required`. A *point* mark additionally never
        // reaches a closing boundary at all (`apply_marker` emits both halves at the start), so
        // it would be reported here on every single export if this did not filter.
        let missing: Vec<String> = self
            .prepared
            .iter()
            .filter(|c| c.required && (!started.contains(&c.id) || !ended.contains(&c.id)))
            .map(|c| format!("{} [{}, {})", c.uid, c.start, c.end))
            .collect();
        if missing.is_empty() {
            Ok(())
        } else {
            Err(anyhow!(
                "{} comment(s) could not be anchored to any exported text (range outside the \
                 document, or targeting a footnote body/table cell, neither of which carries \
                 comment ranges): {}",
                missing.len(),
                missing.join(", ")
            ))
        }
    }
}

/// Comment markers landing inside one inline piece spanning `[piece_start, piece_end)`,
/// resolved to a local index (`0..=piece_end-piece_start`) into that piece's own content —
/// the same offset a `Run`'s text has to be split at (via `.chars()`, never a byte index).
///
/// A `Start` marker's local index only ever lands in `0..piece_len` (never `piece_len` itself
/// — `window_for_block`'s `starts` test is `c.start < block_end`, strictly-less, and the same
/// strictness carries down per piece here); an `End` marker's only ever lands in `1..=piece_len`
/// (never `0`). So for an atomic one-character piece (an image or footnote reference — see
/// `AddressableInlinePiece`'s doc comment for why those are always exactly one character),
/// every marker sits at either `0` (before the piece) or `1` (after it) — there is never a
/// true *mid*-piece split to perform for one of those, only placement around it.
///
/// Sorted by `(local index, End-before-Start, comment id)`: at an exact tie — a thread ending
/// right where another starts, or two replies of the same thread opening/closing together —
/// closing what is ending before opening what is starting keeps the emitted XML from nesting
/// one comment's range inside another's for zero shared characters.
fn markers_for_piece<'a>(
    window: &BlockCommentWindow<'a>,
    piece_start: u32,
    piece_end: u32,
) -> Vec<(u32, Marker<'a>)> {
    let mut out: Vec<(u32, Marker<'a>)> = Vec::new();
    for &c in &window.starts {
        if piece_start <= c.start && c.start < piece_end {
            out.push((c.start - piece_start, Marker::Start(c)));
        }
    }
    for &c in &window.ends {
        if piece_start < c.end && c.end <= piece_end {
            out.push((c.end - piece_start, Marker::End(c)));
        }
    }
    // Three ranks, not two. `End` before `Start` at an exact tie is the original rule; the split
    // within `Start` puts a row's point mark at the front of its paragraph rather than inside a
    // comment range that opens on the same character. Mirrors `export_odt_uc::markers_for_piece`.
    out.sort_by_key(|(idx, m)| {
        let (kind_rank, id) = match m {
            Marker::End(c) => (0u8, c.id),
            Marker::Start(c) if !c.required => (1u8, c.id),
            Marker::Start(c) => (2u8, c.id),
        };
        (*idx, kind_rank, id)
    });
    out
}

/// Common surface between `docx_rs::Paragraph` and `docx_rs::Hyperlink`: both accept the same
/// three child kinds this writer interleaves (runs and comment range markers), through
/// identically-named but differently-typed builder methods with no shared trait in `docx-rs`
/// itself. A comment boundary can land inside a hyperlink's own text —
/// `Docx::update_dependencies` (the auto-collector) walks a `Hyperlink`'s own children for
/// `CommentStart` exactly as it walks a `Paragraph`'s — so the run splitter below has to build
/// into either container, and this trait is what lets it do that with one function instead of
/// two near-duplicate copies.
trait InlineHost: Sized {
    fn host_add_run(self, run: docx_rs::Run) -> Self;
    fn host_add_comment_start(self, comment: docx_rs::Comment) -> Self;
    fn host_add_comment_end(self, id: usize) -> Self;
    fn host_add_bookmark_start(self, id: usize, name: &str) -> Self;
    fn host_add_bookmark_end(self, id: usize) -> Self;
}

impl InlineHost for docx_rs::Paragraph {
    fn host_add_run(self, run: docx_rs::Run) -> Self {
        self.add_run(run)
    }
    fn host_add_comment_start(self, comment: docx_rs::Comment) -> Self {
        self.add_comment_start(comment)
    }
    fn host_add_comment_end(self, id: usize) -> Self {
        self.add_comment_end(id)
    }
    fn host_add_bookmark_start(self, id: usize, name: &str) -> Self {
        self.add_bookmark_start(id, name)
    }
    fn host_add_bookmark_end(self, id: usize) -> Self {
        self.add_bookmark_end(id)
    }
}

impl InlineHost for docx_rs::Hyperlink {
    fn host_add_run(self, run: docx_rs::Run) -> Self {
        self.add_run(run)
    }
    fn host_add_comment_start(self, comment: docx_rs::Comment) -> Self {
        self.add_comment_start(comment)
    }
    fn host_add_comment_end(self, id: usize) -> Self {
        self.add_comment_end(id)
    }
    fn host_add_bookmark_start(self, id: usize, name: &str) -> Self {
        self.add_bookmark_start(id, name)
    }
    fn host_add_bookmark_end(self, id: usize) -> Self {
        self.add_bookmark_end(id)
    }
}

fn apply_marker<H: InlineHost>(host: H, marker: &Marker<'_>, state: &CommentEmitState<'_>) -> H {
    match marker {
        Marker::Start(c) => {
            state.mark_started(c.id);
            match &c.emit {
                SpanEmit::Comment { comment, .. } => host.host_add_comment_start(comment.clone()),
                SpanEmit::Mark {
                    bookmark_id,
                    name,
                    point,
                } => {
                    let host = host.host_add_bookmark_start(*bookmark_id, name);
                    // OOXML has no self-closing bookmark: a zero-length one is its start
                    // immediately followed by its end. Emitted here rather than waiting for a
                    // closing boundary that never comes — `window_for_block`'s `ends` test is
                    // strictly greater than `block_start`, so an empty range is only ever
                    // selected as a start.
                    if *point {
                        host.host_add_bookmark_end(*bookmark_id)
                    } else {
                        host
                    }
                }
            }
        }
        Marker::End(c) => {
            state.mark_ended(c.id);
            match &c.emit {
                SpanEmit::Comment { .. } => host.host_add_comment_end(c.id),
                SpanEmit::Mark { bookmark_id, .. } => host.host_add_bookmark_end(*bookmark_id),
            }
        }
    }
}

pub struct ExportDocxUseCase {
    uow_factory: Box<dyn ExportDocxUnitOfWorkFactoryTrait>,
    dto: ExportDocxDto,
}

impl ExportDocxUseCase {
    pub fn new(
        uow_factory: Box<dyn ExportDocxUnitOfWorkFactoryTrait>,
        dto: &ExportDocxDto,
    ) -> Self {
        ExportDocxUseCase {
            uow_factory,
            dto: dto.clone(),
        }
    }
}

impl LongOperation for ExportDocxUseCase {
    type Output = ExportDocxResultDto;

    fn execute(
        &self,
        progress_callback: Box<dyn Fn(common::long_operation::OperationProgress) + Send>,
        cancel_flag: Arc<AtomicBool>,
    ) -> Result<Self::Output> {
        // Validate output path
        let output_path = std::path::Path::new(&self.dto.output_path);
        if let Some(parent) = output_path.parent()
            && !parent.as_os_str().is_empty()
            && !parent.exists()
        {
            return Err(anyhow!(
                "Output directory does not exist: '{}'",
                parent.display()
            ));
        }

        progress_callback(common::long_operation::OperationProgress::new(
            0.0,
            Some("Starting DOCX export...".to_string()),
        ));

        let uow = self.uow_factory.create();
        uow.begin_transaction()?;

        let build_result = self.build_docx(
            &*uow,
            progress_callback.as_ref(),
            Some(cancel_flag.as_ref()),
        );

        uow.end_transaction()?;

        let (docx, paragraph_count, prepared_comments) = build_result?;

        progress_callback(common::long_operation::OperationProgress::new(
            90.0,
            Some("Writing DOCX file...".to_string()),
        ));

        // Write to file
        let file = std::fs::File::create(&self.dto.output_path).map_err(|e| {
            anyhow!(
                "Failed to create output file '{}': {}",
                self.dto.output_path,
                e
            )
        })?;
        let mut xml_docx = docx.build();
        patch_comment_extras(&mut xml_docx, &prepared_comments)?;
        xml_docx
            .pack(file)
            .map_err(|e| anyhow!("Failed to write DOCX: {}", e))?;

        progress_callback(common::long_operation::OperationProgress::new(
            100.0,
            Some("completed".to_string()),
        ));

        Ok(ExportDocxResultDto {
            file_path: self.dto.output_path.clone(),
            paragraph_count,
        })
    }
}

/// One unit-step of left indentation, in twips (1/20 pt). 720 twips = 0.5",
/// the conventional Word indent step used for both blockquote nesting and list
/// indentation.
const INDENT_STEP_TWIPS: i32 = 720;

/// Word style ids for an epigraph's two paragraph kinds. Ids, not display names: the id is
/// what a paragraph references, the name is what the style panel shows.
const EPIGRAPH_STYLE_ID: &str = "Epigraph";
const EPIGRAPH_ATTRIBUTION_STYLE_ID: &str = "EpigraphAttribution";

/// The style id an ordinary blockquote's paragraphs carry.
///
/// Indentation alone cannot say "this is a quotation" — an indent is a measurement, and every
/// reader that meets one has to guess whether it means a quote, a verse, or a writer who
/// pressed Tab. So a quotation is named the same way an epigraph is, and for the same reason:
/// it is the only thing in the file that still says so after the paragraph has been through an
/// editor, which is what lets `document_ingest`'s scanners read a blockquote *back* as a
/// blockquote rather than as italic-looking body text.
///
/// `Quote` is also Word's own built-in id for exactly this, so a paragraph carrying it lands on
/// the style a Word user already has rather than on a private invention of ours. The declaration
/// below still ships a definition, because `docx-rs` writes no built-in styles at all (same
/// reason `heading_style` exists).
const QUOTE_STYLE_ID: &str = "Quote";

/// Hanging indent applied to numbered/bulleted/task paragraphs so the marker
/// sits in the gutter and the text aligns, in twips.
const HANGING_TWIPS: i32 = 360;

/// Twips per logical pixel. `Block::fmt_top_margin` / `fmt_text_indent` are in
/// the document model's own unit — logical (CSS) pixels at 96 dpi, matching the
/// editor's layout engine — so 1440/96 = 15 twips per px.
const TWIPS_PER_PX: i64 = 15;

/// Convert a block's logical-pixel spacing to twips, clamped.
///
/// These values come from a `{key=value}` block attribute in the document, so
/// they are file-controlled and may be absurd. Doing the arithmetic in `i64` and
/// clamping at the end is what keeps a huge value from wrapping through `i32`
/// into a negative — and then into an enormous `u32` — instead of saturating.
fn px_to_twips(px: i64) -> i32 {
    px.saturating_mul(TWIPS_PER_PX).clamp(0, i32::MAX as i64) as i32
}

/// Light-grey fill behind code blocks, as an `RRGGBB` hex string.
const CODE_BLOCK_FILL: &str = "F5F5F5";

/// A rendered top-level document child. The DOCX builder consumes `self` and
/// returns a new value on every `add_*`, so we cannot thread a `&mut Docx`
/// through the recursive frame walk; instead each block/table is rendered into
/// one of these and applied to the document in a final pass.
enum DocxElement {
    Paragraph(Box<docx_rs::Paragraph>),
    Table(Box<docx_rs::Table>),
}

/// Accumulates the numbering definitions referenced by list paragraphs.
///
/// Each `List` entity maps to its own numbering instance so that ordered
/// counters restart per list (two separate ordered lists each begin at 1).
/// Definitions are registered on the `Docx` after the whole tree is walked.
#[derive(Default)]
struct NumberingBuilder {
    /// `List` entity id -> assigned numbering id.
    map: HashMap<EntityId, usize>,
    defs: Vec<(docx_rs::AbstractNumbering, docx_rs::Numbering)>,
}

impl NumberingBuilder {
    /// Return the numbering id for `list`, creating its abstract-numbering and
    /// numbering definitions on first use.
    fn get_or_create(&mut self, list_id: EntityId, list: &List) -> usize {
        if let Some(&id) = self.map.get(&list_id) {
            return id;
        }
        // Numbering ids are 1-based; `map.len()` is the count assigned so far.
        let id = self.map.len() + 1;
        let abstract_num = build_abstract_numbering(id, list);
        let numbering = docx_rs::Numbering::new(id, id);
        self.defs.push((abstract_num, numbering));
        self.map.insert(list_id, id);
        id
    }
}

impl ExportDocxUseCase {
    /// Assemble the in-memory DOCX document from the store, performing no file
    /// I/O. Returns the document together with the number of top-level elements
    /// (paragraphs and tables) emitted, which is reported as `paragraph_count`, and every
    /// prepared comment thread — `execute` needs the latter for `patch_comment_extras`, which
    /// runs after `Docx::build()` (this function stops short of that; see this module's
    /// "Comment ranges" note at the top for why the raw-XML step has to come after `build()`).
    ///
    /// `execute` uses it and then packs the result to disk; the controller
    /// exposes a file-less variant for tests via [`Self::build_document`].
    pub(crate) fn build_docx(
        &self,
        uow: &dyn ExportDocxUnitOfWorkTrait,
        progress_callback: &dyn Fn(common::long_operation::OperationProgress),
        cancel_flag: Option<&AtomicBool>,
    ) -> Result<(docx_rs::Docx, i64, Vec<PreparedSpan>)> {
        use docx_rs::*;

        // Step 1: Get Root and Document
        let root = uow
            .get_root(&ROOT_ENTITY_ID)?
            .ok_or_else(|| anyhow!("Root entity not found"))?;

        let doc_ids = uow.get_root_relationship(
            &root.id,
            &common::direct_access::root::RootRelationshipField::Document,
        )?;
        let doc_id = *doc_ids
            .first()
            .ok_or_else(|| anyhow!("Root has no associated Document"))?;

        let frame_ids = uow.get_document_relationship(
            &doc_id,
            &common::direct_access::document::DocumentRelationshipField::Frames,
        )?;

        // Collect all cell frame IDs so we can skip them in the main walk; they
        // are rendered as part of their owning table.
        let table_ids = uow.get_document_relationship(
            &doc_id,
            &common::direct_access::document::DocumentRelationshipField::Tables,
        )?;
        let mut cell_frame_ids: HashSet<EntityId> = HashSet::new();
        for tid in &table_ids {
            let cell_ids = uow.get_table_relationship(
                tid,
                &common::direct_access::table::TableRelationshipField::Cells,
            )?;
            let cells_opt = uow.get_table_cell_multi(&cell_ids)?;
            for cell in cells_opt.into_iter().flatten() {
                if let Some(cf_id) = cell.cell_frame {
                    cell_frame_ids.insert(cf_id);
                }
            }
        }

        progress_callback(common::long_operation::OperationProgress::new(
            10.0,
            Some("Walking document tree...".to_string()),
        ));

        let notes = crate::footnotes::Footnotes::build(&uow.store());

        // Resolved once, up front, so every render call below shares the exact same id
        // assignment. `None` when the caller supplied no comments at all — every render call
        // site threads that straight through, so a plain export (no `comments` option set)
        // never pays for the per-block window computation.
        let prepared_comments = prepare_spans(&self.dto.options.comments, &self.dto.options.marks)?;
        let comment_state: Option<CommentEmitState<'_>> = if prepared_comments.is_empty() {
            None
        } else {
            Some(CommentEmitState::new(&prepared_comments))
        };

        // Render every note's body first, while `note_paragraphs` is still
        // empty — so a note that cites another note produces an empty inner
        // footnote rather than recursing. Word has no nested footnote either.
        let note_paragraphs: NoteParagraphs = {
            let mut built: NoteParagraphs = std::collections::HashMap::new();
            let mut note_numbering = NumberingBuilder::default();
            for (_, label, frame_id) in notes.in_print_order() {
                let block_ids = uow.get_frame_relationship(
                    &frame_id,
                    &common::direct_access::frame::FrameRelationshipField::Blocks,
                )?;
                let blocks_opt = uow.get_block_multi(&block_ids)?;
                let mut blocks: Vec<Block> = blocks_opt.into_iter().flatten().collect();
                blocks.sort_by_key(|b| b.document_position);
                let mut paragraphs = Vec::with_capacity(blocks.len());
                // A throwaway state, scoped to this ONE note's own body — never
                // the shared main-walk state below. A citation found in here is
                // necessarily nested (inside a definition frame), so it must
                // never be marked "emitted" against the label's real, resolved
                // citation out in the manuscript; doing so would make that real
                // citation look like a repeat and silently swap its footnote for
                // a bare marker with no note underneath it.
                let body_footnote_state = FootnoteRefState::new(&notes);
                for block in &blocks {
                    paragraphs.push(self.render_block(
                        uow,
                        block,
                        0,
                        None,
                        &mut note_numbering,
                        &std::collections::HashMap::new(),
                        &body_footnote_state,
                        // Footnote bodies render in this separate pre-pass, before the main
                        // walk even starts, and are not part of the document's addressable
                        // text (`to_addressable_text` never descends into a note definition)
                        // — so a comment's char offset could never legitimately resolve
                        // inside one. Deliberately out of scope; see `render_block`'s doc
                        // comment.
                        None,
                    )?);
                }
                built.insert(label, paragraphs);
            }
            built
        };

        let mut numbering = NumberingBuilder::default();
        let mut elements: Vec<DocxElement> = Vec::new();
        // Shared across the WHOLE main walk (every top-level frame, every
        // table cell reached from it): a label's real footnote must be
        // defined at most once across the entire document, not once per frame.
        let footnote_state = FootnoteRefState::new(&notes);

        let total_frames = frame_ids.len().max(1);
        for (frame_idx, frame_id) in frame_ids.iter().enumerate() {
            check_cancelled(cancel_flag)?;

            // Skip cell frames — rendered as part of their table.
            if cell_frame_ids.contains(frame_id) {
                continue;
            }

            let frame = uow.get_frame(frame_id)?;
            let Some(frame) = frame else {
                continue;
            };

            // Skip note bodies: a definition is a top-level frame, so this
            // walk would otherwise render it as ordinary prose in the middle of
            // the chapter, at the point the definition happened to be typed.
            if notes.is_definition(frame.id) {
                continue;
            }
            // Only top-level frames are walked here. Sub-frames (blockquotes,
            // nested content) are reached recursively from their parent's
            // `child_order`; rendering them again at the top level would
            // duplicate their content.
            if frame.parent_frame.is_some() {
                continue;
            }

            // A table anchor frame contributes one table.
            if let Some(table_id) = frame.table {
                let table = self.render_table_docx(
                    uow,
                    &table_id,
                    &mut numbering,
                    &note_paragraphs,
                    &footnote_state,
                )?;
                elements.push(DocxElement::Table(Box::new(table)));
                continue;
            }

            self.render_frame_content(
                uow,
                &frame,
                &cell_frame_ids,
                0,
                None,
                &mut numbering,
                &note_paragraphs,
                cancel_flag,
                &mut elements,
                &footnote_state,
                comment_state.as_ref(),
            )?;

            let pct = 10.0 + (frame_idx as f32 / total_frames as f32) * 70.0;
            progress_callback(common::long_operation::OperationProgress::new(
                pct,
                Some(format!(
                    "Processing frame {}/{}",
                    frame_idx + 1,
                    total_frames
                )),
            ));
        }

        // Every prepared comment must have found a home somewhere in the walk just finished —
        // see `CommentEmitState::ensure_all_anchored`'s doc comment for what "must" buys here.
        if let Some(state) = &comment_state {
            state.ensure_all_anchored()?;
        }

        progress_callback(common::long_operation::OperationProgress::new(
            85.0,
            Some("Assembling document...".to_string()),
        ));

        let paragraph_count = elements.len() as i64;

        let mut docx = Docx::new();
        // Real named styles, so an epigraph is restylable in Word's style panel rather
        // than being a paragraph that merely happens to be indented. Declared always:
        // an unused style costs a few bytes and a conditional declaration is one more
        // thing to get out of step with the paragraphs that reference it.
        docx = docx
            .add_style(
                Style::new(EPIGRAPH_STYLE_ID, StyleType::Paragraph)
                    .name("Epigraph")
                    .italic()
                    .indent(Some(INDENT_STEP_TWIPS), None, None, None),
            )
            .add_style(
                Style::new(EPIGRAPH_ATTRIBUTION_STYLE_ID, StyleType::Paragraph)
                    .name("Epigraph Attribution")
                    .indent(Some(INDENT_STEP_TWIPS), None, None, None)
                    .align(AlignmentType::Right),
            )
            // Not italic, unlike the epigraph above: an epigraph is set apart as quoted
            // matter opening a chapter, while a quotation inside a scene is the writer's
            // own running text and takes the manuscript's face. Indent is the whole of
            // what it adds — the *name* is what this style is for.
            .add_style(
                Style::new(QUOTE_STYLE_ID, StyleType::Paragraph)
                    .name("Quote")
                    .indent(Some(INDENT_STEP_TWIPS), None, None, None),
            );
        // …and the heading styles the heading paragraphs below reference by id. docx-rs
        // ships no built-in styles at all, so without this every `Heading1` in the file is
        // a dangling reference the reader resolves from its own catalogue — which is how a
        // book title asked to be a title and arrived as whatever Word had lying around.
        for (i, h) in self
            .dto
            .options
            .resolved_heading_styles()
            .iter()
            .enumerate()
        {
            docx = docx.add_style(heading_style(i + 1, h));
        }
        // Register numbering definitions before the body so the referenced ids
        // resolve.
        for (abstract_num, num) in numbering.defs {
            docx = docx.add_abstract_numbering(abstract_num).add_numbering(num);
        }
        for element in elements {
            docx = match element {
                DocxElement::Paragraph(p) => docx.add_paragraph(*p),
                DocxElement::Table(t) => docx.add_table(*t),
            };
        }

        // Page geometry + base typography + running header, from the caller's options.
        docx = self.apply_document_options(docx);

        Ok((docx, paragraph_count, prepared_comments))
    }

    /// Apply the document-wide export options (page size, margins, default font/size, and an
    /// optional page-number running header) onto the assembled `Docx`. A default
    /// [`common::parser_tools::DocxExportOptions`] leaves the docx-rs built-in defaults untouched.
    fn apply_document_options(&self, mut docx: docx_rs::Docx) -> docx_rs::Docx {
        use docx_rs::*;
        let o = &self.dto.options;

        if let (Some(w), Some(h)) = (o.page_width_twips, o.page_height_twips) {
            docx = docx.page_size(w, h);
        }
        if o.margin_top_twips.is_some()
            || o.margin_bottom_twips.is_some()
            || o.margin_left_twips.is_some()
            || o.margin_right_twips.is_some()
        {
            // docx-rs's PageMargin defaults each edge to 1440 twips (1"), so an unset edge
            // keeps that conventional default rather than collapsing to zero.
            let mut m = PageMargin::new();
            m = m.top(o.margin_top_twips.unwrap_or(1440));
            m = m.bottom(o.margin_bottom_twips.unwrap_or(1440));
            m = m.left(o.margin_left_twips.unwrap_or(1440));
            m = m.right(o.margin_right_twips.unwrap_or(1440));
            docx = docx.page_margin(m);
        }
        if let Some(family) = &o.font_family {
            docx = docx.default_fonts(
                RunFonts::new()
                    .ascii(family)
                    .hi_ansi(family)
                    .cs(family)
                    .east_asia(family),
            );
        }
        if let Some(half_pt) = o.font_half_points {
            docx = docx.default_size(half_pt);
        }
        if o.page_numbers {
            let mut header_para = Paragraph::new().align(AlignmentType::Right);
            if let Some(text) = &o.running_header
                && !text.trim().is_empty()
            {
                header_para =
                    header_para.add_run(Run::new().add_text(format!("{}   ", text.trim())));
            }
            header_para = header_para.add_page_num(PageNum::new());
            docx = docx.header(Header::new().add_paragraph(header_para));
        }
        docx
    }

    /// Build the document without any file I/O, using a no-op progress callback
    /// and no cancellation. Intended for callers (notably tests) that want to
    /// inspect the produced structure directly.
    pub(crate) fn build_document(&self) -> Result<(docx_rs::Docx, i64)> {
        let uow = self.uow_factory.create();
        uow.begin_transaction()?;
        let result = self.build_docx(&*uow, &|_progress| {}, None);
        uow.end_transaction()?;
        let (docx, paragraph_count, _prepared_comments) = result?;
        Ok((docx, paragraph_count))
    }

    /// As [`Self::build_document`], but also runs the post-`build()` raw-XML comment patch
    /// (`w15:done`, `w:initials`, the uid attribute — see this module's "Comment ranges" note)
    /// and returns the packable [`docx_rs::XMLDocx`] instead of the pre-`build()`
    /// [`docx_rs::Docx`]. Intended for tests that assert on those three fields, none of which
    /// the bare builder struct exposes — they only exist in the packed XML bytes.
    pub(crate) fn build_document_xml(&self) -> Result<docx_rs::XMLDocx> {
        let uow = self.uow_factory.create();
        uow.begin_transaction()?;
        let result = self.build_docx(&*uow, &|_progress| {}, None);
        uow.end_transaction()?;
        let (docx, _paragraph_count, prepared_comments) = result?;
        let mut xml_docx = docx.build();
        patch_comment_extras(&mut xml_docx, &prepared_comments)?;
        Ok(xml_docx)
    }

    /// Walk a frame's `child_order`, appending rendered paragraphs/tables to
    /// `out`. `quote_depth` is the current blockquote nesting level (0 at the
    /// document body), used to compute left indentation.
    ///
    /// `comments` is threaded straight through every recursive call — including into a
    /// blockquote sub-frame, which *is* part of the document's addressable text — but is
    /// never passed down into `render_table_docx`'s own cell walk (that call always hands
    /// its cells `None`; see `render_block`'s doc comment for why table cells are out of
    /// scope for comment ranges).
    #[allow(clippy::too_many_arguments)]
    fn render_frame_content(
        &self,
        uow: &dyn ExportDocxUnitOfWorkTrait,
        frame: &Frame,
        cell_frame_ids: &HashSet<EntityId>,
        quote_depth: usize,
        semantic: Option<&SemanticRole>,
        numbering: &mut NumberingBuilder,
        notes: &NoteParagraphs,
        cancel_flag: Option<&AtomicBool>,
        out: &mut Vec<DocxElement>,
        footnote_state: &FootnoteRefState,
        comments: Option<&CommentEmitState<'_>>,
    ) -> Result<()> {
        if !frame.child_order.is_empty() {
            for &entry in &frame.child_order {
                check_cancelled(cancel_flag)?;
                // `child_order` encodes block ids as positive and sub-frame ids
                // as negated. Entity ids are 1-based, so a 0 entry is malformed;
                // skip it rather than dispatching it as the sub-frame `-0`.
                if entry == 0 {
                    continue;
                }
                if entry > 0 {
                    // Positive: a block id.
                    let block_id = entry as EntityId;
                    if let Some(block) = uow.get_block(&block_id)? {
                        let paragraph = self.render_block(
                            uow,
                            &block,
                            quote_depth,
                            semantic,
                            numbering,
                            notes,
                            footnote_state,
                            comments,
                        )?;
                        out.push(DocxElement::Paragraph(Box::new(paragraph)));
                    }
                } else {
                    // Negative: a negated sub-frame id.
                    let sub_frame_id = (-entry) as EntityId;
                    if cell_frame_ids.contains(&sub_frame_id) {
                        continue;
                    }
                    if let Some(sub_frame) = uow.get_frame(&sub_frame_id)? {
                        // Table anchor sub-frame.
                        if let Some(table_id) = sub_frame.table {
                            let table = self.render_table_docx(
                                uow,
                                &table_id,
                                numbering,
                                notes,
                                footnote_state,
                            )?;
                            out.push(DocxElement::Table(Box::new(table)));
                            continue;
                        }
                        // A blockquote sub-frame deepens the indent; any other
                        // sub-frame is rendered inline at the same depth.
                        let sub_depth = if sub_frame.fmt_is_blockquote == Some(true) {
                            quote_depth + 1
                        } else {
                            quote_depth
                        };
                        let sub_semantic = if sub_frame.fmt_is_blockquote == Some(true) {
                            sub_frame.fmt_semantic_role.as_ref()
                        } else {
                            semantic
                        };
                        self.render_frame_content(
                            uow,
                            &sub_frame,
                            cell_frame_ids,
                            sub_depth,
                            sub_semantic,
                            numbering,
                            notes,
                            cancel_flag,
                            out,
                            footnote_state,
                            comments,
                        )?;
                    }
                }
            }
        } else {
            // Fallback: no child_order recorded — iterate the Blocks
            // relationship in document order.
            let block_ids = uow.get_frame_relationship(
                &frame.id,
                &common::direct_access::frame::FrameRelationshipField::Blocks,
            )?;
            if block_ids.is_empty() {
                return Ok(());
            }
            let blocks_opt = uow.get_block_multi(&block_ids)?;
            let mut blocks: Vec<Block> = blocks_opt.into_iter().flatten().collect();
            blocks.sort_by_key(|b| b.document_position);
            for block in &blocks {
                check_cancelled(cancel_flag)?;
                let paragraph = self.render_block(
                    uow,
                    block,
                    quote_depth,
                    semantic,
                    numbering,
                    notes,
                    footnote_state,
                    comments,
                )?;
                out.push(DocxElement::Paragraph(Box::new(paragraph)));
            }
        }
        Ok(())
    }

    /// Render a single block into one DOCX paragraph.
    ///
    /// Dispatch priority mirrors the djot exporter: code block, then heading,
    /// then list item, then plain paragraph.
    ///
    /// `comments` is `Some` only from call sites reached while walking the document's
    /// addressable text — the main body walk and, recursively, its blockquote sub-frames.
    /// It is always `None` for a footnote body (rendered in a separate pre-pass, before the
    /// main walk starts, over content `to_addressable_text` never descends into) and for
    /// table-cell content (represented in the addressable text by the table's one
    /// `TABLE_ANCHOR` sentinel, never by the cells' own prose) — a `DocumentComment`'s
    /// character offset can therefore never legitimately resolve inside either, and this
    /// writer does not pretend otherwise. A code block is also out of scope: it renders
    /// through `render_code_block` below, which builds its own runs directly from `pieces`
    /// and never reaches `add_inline_content`, the only place comment markers are placed —
    /// inline comments on a fenced code block are not a case the app this crate was built for
    /// asks for, and folding one in would mean re-deriving `render_code_block`'s line-joining
    /// under the same split logic used by `add_inline_content` for no exercised caller.
    #[allow(clippy::too_many_arguments)]
    fn render_block(
        &self,
        uow: &dyn ExportDocxUnitOfWorkTrait,
        block: &Block,
        quote_depth: usize,
        semantic: Option<&SemanticRole>,
        numbering: &mut NumberingBuilder,
        notes: &NoteParagraphs,
        footnote_state: &FootnoteRefState,
        comments: Option<&CommentEmitState<'_>>,
    ) -> Result<docx_rs::Paragraph> {
        use docx_rs::*;

        let block_text = block_content_via_store(block, &uow.store());
        let elements = common::format_runs_query::inline_segments_for_block(
            &uow.store(),
            block.id,
            &block_text,
        );
        // `elements` and `addressable` are built from the exact same `merge_runs_and_anchors`
        // pieces, one InlineSegment/AddressableInlinePiece per piece, in the same order — see
        // `addressable_inline_pieces_for_block`'s own doc comment. Zipping them is what lets
        // every downstream call reach a piece's char-space `[start, end)` without re-deriving
        // it from format-run byte offsets (exactly the bug class that accessor exists to
        // close).
        let addressable = common::format_runs_query::addressable_inline_pieces_for_block(
            &uow.store(),
            block,
            &block_text,
        );
        debug_assert_eq!(
            elements.len(),
            addressable.len(),
            "inline_segments_for_block and addressable_inline_pieces_for_block must stay in \
             lockstep — both are views over the same merge_runs_and_anchors() pieces"
        );
        let pieces: Vec<(InlineSegment, u32, u32)> = elements
            .into_iter()
            .zip(addressable.iter())
            .map(|(elem, piece)| (elem, piece.start, piece.end))
            .collect();

        let quote_indent = quote_depth as i32 * INDENT_STEP_TWIPS;

        // --- Code block ------------------------------------------------------
        if block.fmt_is_code_block == Some(true) {
            return Ok(render_code_block(&pieces, quote_indent));
        }

        // The comments whose range opens or closes somewhere inside this one block —
        // computed once per block, then narrowed further per inline piece inside
        // `add_inline_content`. `None` when this call site is out of scope (see this
        // function's doc comment) or the export carries no comments at all.
        let comment_window = comments.map(|state| {
            // Same cast `addressable_inline_pieces_for_block` makes on this exact value, and
            // for the same reason: a document large enough to overflow `u32` chars would
            // already have overflowed the rope it lives in.
            let block_start = block_document_position(block, &uow.store()) as u32;
            let block_end = block_start + block_text.chars().count() as u32;
            (state, state.window_for_block(block_start, block_end))
        });

        // --- Resolve list membership ----------------------------------------
        let list_ids = uow.get_block_relationship(
            &block.id,
            &common::direct_access::block::BlockRelationshipField::List,
        )?;
        let list = match list_ids.first() {
            Some(list_id) => uow.get_list(list_id)?.map(|l| (*list_id, l)),
            None => None,
        };

        let mut paragraph = Paragraph::new();

        // Common paragraph-level formatting. Heading style is applied in the
        // dispatch below so it does not interfere with list/code handling.
        if let Some(lh) = block.fmt_line_height {
            // thousandths → 240ths: 1000 = single (240), 1500 = 1.5 (360).
            let twips = (lh as f64 / 1000.0 * 240.0) as i32;
            paragraph = paragraph.line_spacing(
                LineSpacing::new()
                    .line_rule(LineSpacingType::Auto)
                    .line(twips),
            );
        }
        if block.fmt_non_breakable_lines == Some(true) {
            paragraph = paragraph.keep_lines(true);
        }
        // Set here, in the common section, so it survives whichever of the three branches
        // below claims the block: `<w:pageBreakBefore/>` and `<w:pStyle/>` are independent
        // children of `<w:pPr>`, so applying a style afterwards cannot drop it.
        if block.fmt_page_break_before == Some(true) {
            paragraph = paragraph.page_break_before(true);
        }
        if let Some(alignment) = &block.fmt_alignment {
            paragraph = paragraph.align(map_alignment(alignment));
        }
        // Per-block RTL → a paragraph-level `<w:bidi/>`. This is the only bidi primitive
        // docx-rs exposes (no run-level `rtl`, no section-level `<w:bidi/>`), but it correctly
        // right-orders a right-to-left paragraph — and it is applied to every paragraph
        // (headings included), independent of the manuscript options, so a document that only
        // mixes in a few RTL scenes still exports them correctly through plain `to_docx`.
        if block.fmt_direction == Some(common::entities::TextDirection::RightToLeft) {
            paragraph.property = paragraph.property.bidi(true);
        }

        let is_task = matches!(
            block.fmt_marker,
            Some(MarkerType::Checked) | Some(MarkerType::Unchecked)
        );

        if let Some(level) = block.fmt_heading_level {
            // Heading takes priority over list membership (mirrors djot).
            let style_name = format!("Heading{}", level.clamp(1, 6));
            paragraph = paragraph.style(&style_name);
            if quote_indent > 0 {
                paragraph = paragraph.indent(Some(quote_indent), None, None, None);
            }
            // A heading does not take the document's body spacing — its style carries its
            // own — but its *own* space-above is a block-level instruction and has to
            // survive, because that is how a title page drops its title down the page.
            // `apply_body_style` handles this for ordinary paragraphs; a heading never
            // reaches it.
            if let Some(before) = block.fmt_top_margin.filter(|&t| t > 0) {
                let mut ls = LineSpacing::new().before(px_to_twips(before) as u32);
                if let Some(lh) = block.fmt_line_height {
                    ls = ls
                        .line_rule(LineSpacingType::Auto)
                        .line((lh as f64 / 1000.0 * 240.0) as i32);
                }
                paragraph = paragraph.line_spacing(ls);
            }
        } else if let Some((list_id, list_entity)) = &list {
            let level = list_entity.indent.clamp(0, 8) as usize;
            if is_task {
                // Task items carry a checkbox glyph instead of an auto-number;
                // they are indented like a list item.
                let left = quote_indent + INDENT_STEP_TWIPS * (level as i32 + 1);
                paragraph = paragraph.indent(
                    Some(left),
                    Some(SpecialIndentType::Hanging(HANGING_TWIPS)),
                    None,
                    None,
                );
                let glyph = if block.fmt_marker == Some(MarkerType::Checked) {
                    "\u{2612} " //                } else {
                    "\u{2610} " //                };
                paragraph = paragraph.add_run(Run::new().add_text(glyph));
            } else {
                let num_id = numbering.get_or_create(*list_id, list_entity);
                paragraph = paragraph.numbering(NumberingId::new(num_id), IndentLevel::new(level));
                // A blockquoted list needs an explicit left indent on top of
                // the numbering geometry; an un-quoted list relies on the
                // numbering definition's own indent.
                if quote_indent > 0 {
                    let left = quote_indent + INDENT_STEP_TWIPS * (level as i32 + 1);
                    paragraph = paragraph.indent(
                        Some(left),
                        Some(SpecialIndentType::Hanging(HANGING_TWIPS)),
                        None,
                        None,
                    );
                }
            }
        } else {
            // Plain body paragraph: manuscript typography (line spacing, first-line indent,
            // paragraph spacing, alignment) from the export options, over any blockquote indent.
            paragraph = self.apply_body_style(paragraph, block, quote_indent);
            // An epigraph's paragraphs carry its named style. Which of the two is
            // decided by the alignment the author already gave the line: the attribution
            // is the right-aligned one, which is the convention the editor writes and
            // every other writer renders — so nothing extra has to be recorded to tell
            // a quotation's last line from its source line.
            //
            // An ordinary blockquote is named too, one step down: `quote_depth` is the
            // nesting level, so any paragraph inside a quotation gets `Quote` whatever its
            // depth. The direct indent `apply_body_style` just applied stays on the
            // paragraph and wins over the style's own, which is what keeps a *nested*
            // quote visibly deeper than the one containing it.
            if let Some(SemanticRole::Epigraph) = semantic {
                paragraph = paragraph.style(if block.fmt_alignment == Some(Alignment::Right) {
                    EPIGRAPH_ATTRIBUTION_STYLE_ID
                } else {
                    EPIGRAPH_STYLE_ID
                });
            } else if quote_depth > 0 {
                paragraph = paragraph.style(QUOTE_STYLE_ID);
            }
        }

        Ok(add_inline_content(
            paragraph,
            &pieces,
            &self.dto.options.images,
            notes,
            footnote_state,
            comment_window
                .as_ref()
                .map(|(state, window)| (*state, window)),
        ))
    }

    /// Apply the manuscript body-paragraph options to a plain paragraph. Each piece is applied
    /// only when the corresponding option is set (and the block didn't already carry its own),
    /// so a default [`common::parser_tools::DocxExportOptions`] leaves the paragraph exactly as plain `to_docx`
    /// produced it — including keeping any blockquote left indent.
    fn apply_body_style(
        &self,
        mut p: docx_rs::Paragraph,
        block: &Block,
        quote_indent: i32,
    ) -> docx_rs::Paragraph {
        use docx_rs::*;
        let o = &self.dto.options;
        let rtl = block.fmt_direction == Some(common::entities::TextDirection::RightToLeft);

        // Combined line spacing: line height (unless the block set its own) + space-after.
        let mut ls = LineSpacing::new();
        let mut ls_used = false;
        if block.fmt_line_height.is_none()
            && let Some(line) = o.line_spacing_twips
        {
            ls = ls.line_rule(LineSpacingType::Auto).line(line);
            ls_used = true;
        }
        if let Some(after) = o.paragraph_spacing_after_twips.filter(|&a| a > 0) {
            ls = ls.after(after as u32);
            ls_used = true;
        }
        // A block's own space-above, e.g. the gap a blank-line scene break puts
        // before the paragraph that follows it. Stacks with the document-wide
        // space-after of the previous paragraph rather than replacing it.
        if let Some(before) = block.fmt_top_margin.filter(|&t| t > 0) {
            ls = ls.before(px_to_twips(before) as u32);
            ls_used = true;
        }
        if ls_used {
            p = p.line_spacing(ls);
        }

        // Indent: any blockquote left indent + a first-line indent. A block that
        // carries its own `fmt_text_indent` overrides the document-wide default,
        // which is how a scene break suppresses the indent on the next paragraph
        // (`text_indent=0`) exactly as print typography expects.
        let first_line = match block.fmt_text_indent {
            Some(ti) => (ti > 0).then(|| px_to_twips(ti)),
            None => o.first_line_indent_twips.filter(|&f| f > 0),
        };
        let left = (quote_indent > 0).then_some(quote_indent);
        if left.is_some() || first_line.is_some() {
            p = p.indent(
                left,
                first_line.map(SpecialIndentType::FirstLine),
                None,
                None,
            );
        }

        // Alignment (only when the block didn't carry its own, and only when the options ask
        // for it — a plain LTR export leaves the docx default so existing behaviour is intact).
        if block.fmt_alignment.is_none() {
            let align = if o.justify {
                Some(AlignmentType::Justified)
            } else if rtl {
                Some(AlignmentType::Right)
            } else {
                None
            };
            if let Some(a) = align {
                p = p.align(a);
            }
        }
        p
    }

    fn render_table_docx(
        &self,
        uow: &dyn ExportDocxUnitOfWorkTrait,
        table_id: &EntityId,
        numbering: &mut NumberingBuilder,
        notes: &NoteParagraphs,
        footnote_state: &FootnoteRefState,
    ) -> Result<docx_rs::Table> {
        use docx_rs::*;

        let table = uow
            .get_table(table_id)?
            .ok_or_else(|| anyhow!("Table not found"))?;

        let cell_ids = uow.get_table_relationship(
            table_id,
            &common::direct_access::table::TableRelationshipField::Cells,
        )?;
        let cells_opt = uow.get_table_cell_multi(&cell_ids)?;
        let mut cells: Vec<common::entities::TableCell> = cells_opt.into_iter().flatten().collect();
        cells.sort_by(|a, b| a.row.cmp(&b.row).then(a.column.cmp(&b.column)));

        // Build a grid to track which cells are covered by spans.
        let rows = table.rows as usize;
        let cols = table.columns as usize;
        let mut covered = vec![vec![false; cols]; rows];

        // Build column grid widths.
        let grid: Vec<usize> = table.column_widths.iter().map(|w| *w as usize).collect();

        let mut docx_rows: Vec<TableRow> = Vec::new();

        for r in 0..rows {
            let mut docx_cells: Vec<docx_rs::TableCell> = Vec::new();

            for c in 0..cols {
                if covered[r][c] {
                    // Position covered by a row/column span from another cell.
                    // A vertically merged continuation still needs a <w:tc>
                    // with vMerge continue; a column span simply omits the cell.
                    let needs_vmerge_continue = r > 0 && {
                        cells.iter().any(|cell| {
                            cell.column == c as i64
                                && cell.row < r as i64
                                && (cell.row + cell.row_span) > r as i64
                        })
                    };
                    if needs_vmerge_continue {
                        let cont_cell =
                            docx_rs::TableCell::new().vertical_merge(VMergeType::Continue);
                        docx_cells.push(cont_cell);
                    }
                    continue;
                }

                let cell = cells
                    .iter()
                    .find(|cell| cell.row == r as i64 && cell.column == c as i64);

                if let Some(cell) = cell {
                    let mut docx_cell = docx_rs::TableCell::new();

                    // Spans are `i64`; clamp to >= 1 before any `as usize` so a
                    // malformed (0 or negative) span can never wrap to a huge
                    // `usize` and blow up the coverage loop or the grid span.
                    let row_span = cell.row_span.max(1) as usize;
                    let col_span = cell.column_span.max(1) as usize;

                    if col_span > 1 {
                        docx_cell = docx_cell.grid_span(col_span);
                    }
                    if row_span > 1 {
                        docx_cell = docx_cell.vertical_merge(VMergeType::Restart);
                    }

                    // Render the cell's frame as a sequence of paragraphs/tables.
                    if let Some(cf_id) = cell.cell_frame
                        && let Some(cell_frame) = uow.get_frame(&cf_id)?
                    {
                        let mut cell_elements: Vec<DocxElement> = Vec::new();
                        // The document-level cell-frame skip set does not apply
                        // inside a cell, so pass an empty set here.
                        self.render_frame_content(
                            uow,
                            &cell_frame,
                            &HashSet::new(),
                            0,
                            None,
                            numbering,
                            notes,
                            None,
                            &mut cell_elements,
                            footnote_state,
                            // Table cell content is not part of the document's addressable
                            // text (`to_addressable_text` represents a whole table as one
                            // `TABLE_ANCHOR` sentinel, never its cells' own prose) — see
                            // `render_block`'s doc comment for why comment ranges therefore
                            // never reach inside a cell.
                            None,
                        )?;
                        for element in cell_elements {
                            docx_cell = match element {
                                DocxElement::Paragraph(p) => docx_cell.add_paragraph(*p),
                                DocxElement::Table(t) => docx_cell.add_table(*t),
                            };
                        }
                    }

                    docx_cells.push(docx_cell);

                    // Mark spanned cells as covered.
                    for sr in 0..row_span {
                        for sc in 0..col_span {
                            if sr == 0 && sc == 0 {
                                continue;
                            }
                            if r + sr < rows && c + sc < cols {
                                covered[r + sr][c + sc] = true;
                            }
                        }
                    }
                } else {
                    // Empty cell — no TableCell entity at this position.
                    let docx_cell = docx_rs::TableCell::new().add_paragraph(Paragraph::new());
                    docx_cells.push(docx_cell);
                }
            }

            docx_rows.push(TableRow::new(docx_cells));
        }

        let mut docx_table = docx_rs::Table::new(docx_rows);
        if !grid.is_empty() {
            docx_table = docx_table.set_grid(grid);
        }

        Ok(docx_table)
    }
}

/// Return `Err` if a cancellation flag is present and set.
fn check_cancelled(cancel_flag: Option<&AtomicBool>) -> Result<()> {
    if let Some(flag) = cancel_flag
        && flag.load(Ordering::Relaxed)
    {
        return Err(anyhow!("Operation was cancelled"));
    }
    Ok(())
}

/// Map the model's paragraph alignment to docx-rs.
fn map_alignment(alignment: &Alignment) -> docx_rs::AlignmentType {
    use docx_rs::AlignmentType;
    match alignment {
        Alignment::Left => AlignmentType::Left,
        Alignment::Right => AlignmentType::Right,
        Alignment::Center => AlignmentType::Center,
        Alignment::Justify => AlignmentType::Justified,
    }
}

/// Build the `HeadingN` paragraph style definition for one level.
///
/// `outline_lvl` is what makes the result more than cosmetic: it is the field Word's
/// navigation pane and its automatic table of contents both read, so a document whose
/// headings carry it becomes navigable rather than merely large-and-bold.
fn heading_style(level: usize, h: &common::parser_tools::DocxHeadingStyle) -> docx_rs::Style {
    use docx_rs::*;
    let mut style = Style::new(format!("Heading{level}"), StyleType::Paragraph)
        .name(format!("heading {level}"))
        // Zero-based, and clamped to Word's nine outline levels.
        .outline_lvl(level.clamp(1, 9) - 1);
    if let Some(size) = h.size_half_points {
        style = style.size(size);
    }
    if h.bold {
        style = style.bold();
    }
    if h.italic {
        style = style.italic();
    }
    if let Some(a) = &h.alignment {
        style = style.align(map_alignment(a));
    }
    if h.space_before_twips.is_some() || h.space_after_twips.is_some() {
        let mut ls = LineSpacing::new();
        if let Some(before) = h.space_before_twips {
            ls = ls.before(before.max(0) as u32);
        }
        if let Some(after) = h.space_after_twips {
            ls = ls.after(after.max(0) as u32);
        }
        style = style.line_spacing(ls);
    }
    // `Style` exposes no builder for these two, but its `paragraph_property` is public
    // and *is* written out by its XML builder — the same door `render_block` already
    // goes through for `bidi`.
    if h.keep_with_next {
        style.paragraph_property = style.paragraph_property.keep_next(true);
    }
    if h.page_break_before {
        style.paragraph_property = style.paragraph_property.page_break_before(true);
    }
    style
}

/// Render a fenced/code block as a single monospaced, shaded paragraph.
///
/// Inline formatting is dropped (only the raw text matters, mirroring djot).
/// Embedded newlines become soft line breaks so a multi-line block stays one
/// paragraph.
///
/// Takes the same `(InlineSegment, start, end)` pieces `add_inline_content` does, but ignores
/// the char-space bounds entirely — a code block never reaches `add_inline_content` (see
/// `render_block`'s doc comment on why comment ranges do not extend to code blocks), so
/// nothing here ever reads the two offset fields. Sharing the tuple's shape just keeps
/// `render_block` from maintaining two differently-shaped element lists per block.
fn render_code_block(
    pieces: &[(InlineSegment, u32, u32)],
    quote_indent: i32,
) -> docx_rs::Paragraph {
    use docx_rs::*;

    let mut raw = String::new();
    for (elem, _, _) in pieces {
        if let InlineContent::Text(t) = &elem.content {
            raw.push_str(t);
        }
    }

    let mut paragraph = Paragraph::new().keep_lines(true);
    if quote_indent > 0 {
        paragraph = paragraph.indent(Some(quote_indent), None, None, None);
    }

    for (idx, line) in raw.split('\n').enumerate() {
        let mut run = Run::new()
            .fonts(RunFonts::new().ascii("Courier New").hi_ansi("Courier New"))
            .shading(
                Shading::new()
                    .shd_type(ShdType::Clear)
                    .fill(CODE_BLOCK_FILL),
            );
        if idx > 0 {
            run = run.add_break(BreakType::TextWrapping);
        }
        if !line.is_empty() {
            run = run.add_text(line);
        }
        paragraph = paragraph.add_run(run);
    }

    paragraph
}

/// Embed an inline image as a real DOCX drawing.
///
/// Returns `None` when the caller supplied no bytes for this `src`, or when
/// those bytes are not a decodable image — the run then falls back to alt text.
/// An unreadable picture must never fail a manuscript export.
///
/// **Why the image is re-encoded as PNG.** docx-rs writes every embedded image
/// to `word/media/{id}.png` (`image_collector.rs`) regardless of what the bytes
/// actually are, so handing it a JPEG produces a package whose part is named and
/// typed `png` but contains JPEG — a file Word refuses to render. Its own
/// `Pic::new` avoids that by transcoding through the `image` crate, but it
/// `.expect()`s on a decode failure, which would turn a corrupt user file into a
/// panic. This does the same conversion fallibly.
fn build_image_run(
    name: &str,
    alt: &str,
    width: i64,
    height: i64,
    images: &ExportImages,
) -> Option<docx_rs::Run> {
    use docx_rs::*;
    use image::GenericImageView;

    let bytes = &images.get(name)?.bytes;
    let decoded = image::load_from_memory(bytes).ok()?;
    let (natural_w, natural_h) = decoded.dimensions();

    let mut png = std::io::Cursor::new(Vec::new());
    decoded.write_to(&mut png, image::ImageFormat::Png).ok()?;

    // OOXML measures drawings in EMUs: 914400 per inch, and a pixel is 1/96".
    // Display size, when the document carries one, wins over the file's own
    // dimensions — that is what a resize in the editor means.
    const EMU_PER_PX: u32 = 9525;
    let display_w = if width > 0 { width as u32 } else { natural_w };
    let display_h = if height > 0 { height as u32 } else { natural_h };

    let pic = Pic::new_with_dimensions(png.into_inner(), natural_w, natural_h)
        .size(display_w * EMU_PER_PX, display_h * EMU_PER_PX);

    // ⚠ Alt text is lost here, and cannot currently be preserved: OOXML carries
    // it on `wp:docPr/@descr`, but docx-rs's builder for that element accepts
    // only `id` and `name` (`xml_builder/drawing.rs`). Emitting it as an
    // adjacent text run was considered and rejected — it would print the
    // description into the manuscript. Fixing this properly needs an upstream
    // change; until then a DOCX export is the one backend where an image's
    // description does not travel.
    let _ = alt;

    Some(Run::new().add_image(pic))
}

/// Build a DOCX run for one inline segment, applying its character formatting.
/// Returns `None` for segments that contribute no text.
fn build_run(
    elem: &InlineSegment,
    images: &ExportImages,
    notes: &std::collections::HashMap<String, Vec<docx_rs::Paragraph>>,
    footnote_state: &FootnoteRefState,
) -> Option<docx_rs::Run> {
    use docx_rs::*;

    // A real OOXML footnote: Word numbers it, places it at the foot of the page
    // it lands on, and renumbers when the text reflows. A reference whose body
    // this document does not hold still gets its note — an empty one — because
    // dropping the run entirely would delete the marker from the sentence.
    //
    // That is the FIRST citation of a label. A repeat must not go through here
    // again — see `FootnoteRefState`'s doc for why a second
    // `add_footnote_reference` call would corrupt, not duplicate, the package.
    // It gets a plain run instead, carrying the number the first citation
    // already earned, styled as "FootnoteReference" so it still reads as a
    // footnote mark even though it opens no second note.
    if let InlineContent::FootnoteRef { label } = &elem.content {
        if footnote_state.emitted.borrow_mut().insert(label.clone()) {
            let mut footnote = Footnote::new();
            for paragraph in notes.get(label).cloned().unwrap_or_default() {
                footnote = footnote.add_content(paragraph);
            }
            return Some(Run::new().add_footnote_reference(footnote));
        }
        let marker = footnote_state.numbers.marker(label);
        let mut run = Run::new().add_text(marker);
        run.run_property = run.run_property.style("FootnoteReference");
        return Some(run);
    }

    let text = match &elem.content {
        // Handled above, before any of the text machinery: a reference has no
        // text of its own, and its whole rendering is the run it returns there.
        InlineContent::FootnoteRef { .. } => return None,
        InlineContent::Text(t) => t.clone(),
        InlineContent::Image {
            name,
            alt,
            width,
            height,
            ..
        } => {
            if let Some(run) = build_image_run(name, alt, *width, *height, images) {
                return Some(run);
            }
            // No bytes, or undecodable: degrade to the description rather than
            // to a bracketed filename, which means nothing to a reader.
            if alt.is_empty() {
                return None;
            }
            alt.clone()
        }
        InlineContent::Empty => return None,
    };
    if text.is_empty() {
        return None;
    }
    Some(text_run_with_format(&text, elem))
}

/// Build a run carrying `text`, formatted per `elem`'s `fmt_*` fields.
///
/// Split out of [`build_run`]'s tail so `add_inline_content` can call it directly for a
/// *substring* of a text segment — the piece straddling a comment boundary — without routing
/// back through `build_run`'s footnote/image handling, neither of which a plain text segment
/// ever touches anyway.
fn text_run_with_format(text: &str, elem: &InlineSegment) -> docx_rs::Run {
    use docx_rs::*;
    let mut run = Run::new().add_text(text);
    if elem.fmt_font_bold == Some(true) {
        run = run.bold();
    }
    if elem.fmt_font_italic == Some(true) {
        run = run.italic();
    }
    if elem.fmt_font_underline == Some(true) {
        run = run.underline("single");
    }
    if elem.fmt_font_strikeout == Some(true) {
        run = run.strike();
    }
    if elem.fmt_font_family.as_deref() == Some("monospace") {
        run = run.fonts(RunFonts::new().ascii("Courier New").hi_ansi("Courier New"));
    }
    run
}

/// One inline piece, resolved to whether/how it contributes a run.
struct RenderedPiece<'p> {
    elem: &'p InlineSegment,
    start: u32,
    end: u32,
    /// The run `build_run` would emit for the whole piece — `None` for content it drops
    /// entirely (e.g. an inline image with neither embeddable bytes nor alt text). Kept even
    /// when `None`: a comment boundary sitting exactly at a run-less piece's position still
    /// needs somewhere to attach its marker, and dropping the piece outright would silently
    /// lose that comment instead of anchoring it (`CommentEmitState::ensure_all_anchored`
    /// exists specifically to catch the alternative — a comment that reaches no piece at all).
    run: Option<docx_rs::Run>,
}

/// Append the inline content of a block to `paragraph`: build one [`RenderedPiece`] per
/// source piece (applying `build_run`'s footnote/image side effects exactly once each, same
/// as before comment support existed), group consecutive same-`href` pieces under one
/// `<w:hyperlink>`, and — when `comments` is `Some` — split whichever run or hyperlink child
/// straddles a comment boundary, interleaving `CommentRangeStart`/`CommentRangeEnd` at the
/// right point.
///
/// A comment boundary can land: **mid-run** (a `Start`/`End` index strictly between two chars
/// of one text piece — the general case `markers_for_piece` resolves per piece); **inside a
/// hyperlink's own children** (a marker for a piece that happens to share an `href` with its
/// neighbours goes through `Hyperlink::add_comment_start`/`add_comment_end`, exactly mirroring
/// `Paragraph`'s own methods — see [`InlineHost`]); and two comments can **overlap** in one
/// block, including sharing the exact same range (a thread's replies always do — see
/// `PreparedSpan`'s doc comment) — `markers_for_piece` already returns every marker that
/// falls in a piece, in a stable order, so overlapping ranges just interleave correctly with
/// no special-casing here.
fn add_inline_content(
    mut paragraph: docx_rs::Paragraph,
    pieces: &[(InlineSegment, u32, u32)],
    images: &ExportImages,
    notes: &std::collections::HashMap<String, Vec<docx_rs::Paragraph>>,
    footnote_state: &FootnoteRefState,
    comments: Option<(&CommentEmitState<'_>, &BlockCommentWindow<'_>)>,
) -> docx_rs::Paragraph {
    use docx_rs::*;

    let rendered: Vec<RenderedPiece<'_>> = pieces
        .iter()
        .map(|(elem, start, end)| RenderedPiece {
            elem,
            start: *start,
            end: *end,
            run: build_run(elem, images, notes, footnote_state),
        })
        .collect();

    if rendered.is_empty() {
        // A genuinely empty block (e.g. a blank paragraph) has no piece to wrap a marker
        // around. A comment collapsed to exactly this point (`start == end == this block's
        // position` — the only way `window_for_block` puts anything in `starts`/`ends` for an
        // empty block) still needs to be anchored, or `ensure_all_anchored` fails the export
        // for a thread that had every right to exist.
        if let Some((state, window)) = comments {
            // Through `apply_marker` rather than calling the builder directly, so this branch
            // cannot forget a span kind: a round-trip mark landing on a blank paragraph writes
            // its bookmark here exactly as it would mid-run.
            for &c in &window.starts {
                paragraph = apply_marker(paragraph, &Marker::Start(c), state);
            }
            // Closed from `ends`, NOT from `starts`. They are different sets: a comment can
            // start in this block and end in a later one, or end here having started earlier.
            // Closing whatever happens to start here emits `commentRangeEnd` for a range that
            // is still open — and, worse, never emits one for a range that really did end
            // here, leaving it unterminated in the file.
            for &c in window.ends.iter().rev() {
                paragraph = apply_marker(paragraph, &Marker::End(c), state);
            }
        }
        return paragraph;
    }

    // Coalesce consecutive pieces sharing the same href into one hyperlink group, the same
    // grouping `add_inline_content` always did — a run-less piece (see `RenderedPiece::run`)
    // still participates by its own `href`, same as any other.
    enum Group {
        Plain(usize),
        Link(String, std::ops::Range<usize>),
    }
    let mut groups: Vec<Group> = Vec::new();
    for (i, piece) in rendered.iter().enumerate() {
        match &piece.elem.fmt_anchor_href {
            Some(href) if !href.is_empty() => {
                if let Some(Group::Link(open_href, range)) = groups.last_mut()
                    && open_href == href
                {
                    range.end = i + 1;
                    continue;
                }
                groups.push(Group::Link(href.clone(), i..i + 1));
            }
            _ => groups.push(Group::Plain(i)),
        }
    }

    for group in groups {
        match group {
            Group::Plain(i) => {
                paragraph = append_piece(paragraph, &rendered[i], comments);
            }
            Group::Link(href, range) => {
                let mut link = Hyperlink::new(href, HyperlinkType::External);
                for i in range {
                    link = append_piece(link, &rendered[i], comments);
                }
                paragraph = paragraph.add_hyperlink(link);
            }
        }
    }

    paragraph
}

/// Append one [`RenderedPiece`] to `host` (a paragraph, or a hyperlink being built up inside
/// one), splitting its run at any comment boundary `markers_for_piece` finds inside it.
fn append_piece<H: InlineHost>(
    mut host: H,
    piece: &RenderedPiece<'_>,
    comments: Option<(&CommentEmitState<'_>, &BlockCommentWindow<'_>)>,
) -> H {
    let Some((state, window)) = comments else {
        return match &piece.run {
            Some(run) => host.host_add_run(run.clone()),
            None => host,
        };
    };
    let markers = markers_for_piece(window, piece.start, piece.end);
    if markers.is_empty() {
        return match &piece.run {
            Some(run) => host.host_add_run(run.clone()),
            None => host,
        };
    }

    if let InlineContent::Text(text) = &piece.elem.content {
        // The general, mid-run case: slice the text at each marker's local char index —
        // `.chars()`, never a byte index, since `markers_for_piece`'s indices are character
        // offsets and this text can hold any UTF-8.
        let chars: Vec<char> = text.chars().collect();
        let mut cursor = 0usize;
        for (idx, marker) in &markers {
            let local = (*idx as usize).min(chars.len());
            if local > cursor {
                let slice: String = chars[cursor..local].iter().collect();
                host = host.host_add_run(text_run_with_format(&slice, piece.elem));
                cursor = local;
            }
            host = apply_marker(host, marker, state);
        }
        if cursor < chars.len() {
            let slice: String = chars[cursor..].iter().collect();
            host = host.host_add_run(text_run_with_format(&slice, piece.elem));
        }
    } else {
        // Atomic content (image, footnote reference, or a run-less piece): every marker sits
        // at local index `0` (before) or the piece's own length (after) — see
        // `markers_for_piece`'s doc comment — so there is only ever placement around the one
        // run, never a true split.
        for (idx, marker) in &markers {
            if *idx == 0 {
                host = apply_marker(host, marker, state);
            }
        }
        if let Some(run) = &piece.run {
            host = host.host_add_run(run.clone());
        }
        for (idx, marker) in &markers {
            if *idx != 0 {
                host = apply_marker(host, marker, state);
            }
        }
    }
    host
}

/// Build a complete abstract-numbering definition (levels 0..=8) for `list`.
///
/// Levels beyond the list's own `indent` are defined too so any nesting level
/// resolves; they all share the list's style.
fn build_abstract_numbering(id: usize, list: &List) -> docx_rs::AbstractNumbering {
    let mut abstract_num = docx_rs::AbstractNumbering::new(id);
    for level in 0..=8usize {
        abstract_num = abstract_num.add_level(build_level(level, list));
    }
    abstract_num
}

/// Build one numbering level for `list` at the given nesting `level`.
fn build_level(level: usize, list: &List) -> docx_rs::Level {
    use docx_rs::*;

    let (format, text) = match list.style {
        ListStyle::Decimal => ("decimal", ordered_level_text(level, list)),
        ListStyle::LowerAlpha => ("lowerLetter", ordered_level_text(level, list)),
        ListStyle::UpperAlpha => ("upperLetter", ordered_level_text(level, list)),
        ListStyle::LowerRoman => ("lowerRoman", ordered_level_text(level, list)),
        ListStyle::UpperRoman => ("upperRoman", ordered_level_text(level, list)),
        ListStyle::Disc => ("bullet", "\u{2022}".to_string()), //        ListStyle::Circle => ("bullet", "\u{25CB}".to_string()), //        ListStyle::Square => ("bullet", "\u{25AA}".to_string()), //    };

    let left = INDENT_STEP_TWIPS * (level as i32 + 1);
    Level::new(
        level,
        Start::new(1),
        NumberFormat::new(format),
        LevelText::new(text),
        LevelJc::new("left"),
    )
    .indent(
        Some(left),
        Some(SpecialIndentType::Hanging(HANGING_TWIPS)),
        None,
        None,
    )
}

/// `LevelText` for an ordered list level, e.g. `"1."` or `"(a)"`, honouring the
/// list's recorded prefix/suffix. The `%N` placeholder is 1-based on the level.
fn ordered_level_text(level: usize, list: &List) -> String {
    let suffix = if list.suffix.is_empty() {
        "."
    } else {
        list.suffix.as_str()
    };
    format!("{}%{}{}", list.prefix, level + 1, suffix)
}

// ── Raw-XML comment patch ────────────────────────────────────────────────────────────
//
// Three things this writer needs are unreachable through `docx-rs` 0.4.22's public builder
// API — verified against its actual source, not assumed (see each patch's own comment below
// for the exact line of reasoning):
//
//  - `w15:done` (the resolved flag): `Docx::build()`'s auto-collector
//    (`push_comment_and_comment_extended` in `documents/mod.rs`) always constructs
//    `CommentExtended::new(para_id)`, which starts `done: false`, and never calls the type's
//    own `.done()`. There is no way to hand the collector a resolved thread.
//  - `w:initials`: `docx_rs::Comment` carries no such field at all, and its `BuildXML` impl
//    hardcodes the empty string (`.open_comment(&self.id.to_string(), &self.author, &self.date,
//    "")` in `documents/elements/comment.rs`).
//  - The uid: there is no extension point on `Comment`/`CommentExtended` for arbitrary
//    caller data at all.
//
// So this module builds ordinary `docx_rs::Comment`s (author, date, one body paragraph) through
// the public API, then rewrites the raw `word/comments.xml` / `word/commentsExtended.xml`
// bytes `Docx::build()` hands back — `XMLDocx::comments`/`comments_extended` are `pub Vec<u8>`,
// already fully serialized, and `XMLDocx::pack` writes them out completely unconditionally
// (`zipper::zip`), so a patch here reaches the packed file with nothing further downstream
// able to overwrite it.

/// The three raw-XML gaps closed here, keyed as described in each field's own doc comment.
/// See this module's "Raw-XML comment patch" note above for why `docx-rs` leaves them closed
/// through its public API at all.
fn patch_comment_extras(xml_docx: &mut docx_rs::XMLDocx, spans: &[PreparedSpan]) -> Result<()> {
    // Comments only. Round-trip marks share the prepared list (see `PreparedSpan`) but write
    // bookmarks in the body, contribute nothing to `word/comments.xml`, and would otherwise
    // throw off the count check below by exactly the number of marks in the export.
    let prepared: Vec<&PreparedSpan> = spans.iter().filter(|s| s.as_comment().is_some()).collect();
    if prepared.is_empty() {
        return Ok(());
    }

    let comments_text = String::from_utf8(std::mem::take(&mut xml_docx.comments))
        .map_err(|e| anyhow!("word/comments.xml was not valid UTF-8: {e}"))?;
    let comments_extended_text = String::from_utf8(std::mem::take(&mut xml_docx.comments_extended))
        .map_err(|e| anyhow!("word/commentsExtended.xml was not valid UTF-8: {e}"))?;

    let by_id: HashMap<usize, &PreparedSpan> = prepared.iter().map(|c| (c.id, *c)).collect();

    // A private-namespace attribute in an undeclared prefix is well-formed XML but a
    // namespace *error* — strict readers (LibreOffice included) reject the whole part rather
    // than merely ignoring the one attribute they don't recognise — so the prefix has to be
    // declared on the root element before anything below can use it.
    let comments_text = declare_skrb_namespace(comments_text)?;

    // Correlate each comment's stable `w:id` to its body paragraph's *actual* `w14:paraId` —
    // see this function's doc comment on the uid/`w15:done` patches below for why the actual
    // value, not the one `prepare_comments` originally asked for, is what has to be used.
    // Every prepared comment has exactly one body paragraph (`render_comment_body`'s doc
    // comment explains why more than one would corrupt the file), so a lazy `.*?` search for
    // the first `w14:paraId` after each comment's own opening tag always lands on the right
    // one — never a later comment's.
    let id_and_para_re =
        Regex::new(r#"(?s)<w:comment\s+w:id="(\d+)"[^>]*>.*?w14:paraId="([0-9a-fA-F]{8})""#)
            .expect("static regex is valid");
    let mut actual_para_id: HashMap<usize, String> = HashMap::new();
    for caps in id_and_para_re.captures_iter(&comments_text) {
        let id: usize = caps[1]
            .parse()
            .expect("\\d+ capture is always a valid usize");
        actual_para_id.insert(id, caps[2].to_string());
    }
    if actual_para_id.len() != prepared.len() {
        return Err(anyhow!(
            "expected {} comment(s) in word/comments.xml, found {} well-formed enough to \
             correlate a w:id to a body paragraph's w14:paraId — the raw-XML patch step \
             (w15:done / w:initials / uid) cannot proceed on a shape it doesn't recognise",
            prepared.len(),
            actual_para_id.len()
        ));
    }

    // `w:initials` + the uid attribute, keyed by `w:id` — a plain `usize` `docx-rs` never
    // rewrites (unlike a paragraph id; see `prepare_comments`'s doc comment), so no read-back
    // is needed for this half.
    let initials_re = Regex::new(r#"(<w:comment\s+w:id="(\d+)"[^>]*?)w:initials="""#)
        .expect("static regex is valid");
    let comments_text = initials_re
        .replace_all(&comments_text, |caps: &regex::Captures<'_>| {
            let id: usize = caps[2]
                .parse()
                .expect("\\d+ capture is always a valid usize");
            let pc = by_id
                .get(&id)
                .expect("every w:id captured here was assigned by prepare_comments");
            let (author_initials, _, _) = pc
                .as_comment()
                .expect("by_id holds comments only — marks are filtered out above");
            format!(
                r#"{}w:initials="{}" skrb:uid="{}""#,
                &caps[1],
                xml_attr_escape(author_initials),
                xml_attr_escape(&pc.uid),
            )
        })
        .into_owned();

    // `w15:done`, keyed by the *actual* paraId read back above — this is the field the
    // paraId-rewrite hazard actually bites: a `commentEx` entry is matched to its `<w:comment>`
    // purely by `w15:paraId` equalling the body paragraph's real `w14:paraId`, and that is
    // exactly the value `Docx::build()` may have reassigned.
    let resolved_para_ids: HashSet<&str> = prepared
        .iter()
        .filter(|c| c.as_comment().is_some_and(|(_, resolved, _)| resolved))
        .filter_map(|c| actual_para_id.get(&c.id).map(String::as_str))
        .collect();
    let done_re =
        Regex::new(r#"(<w15:commentEx\s+w15:paraId="([0-9a-fA-F]{8})"[^>]*?)w15:done="0""#)
            .expect("static regex is valid");
    let comments_extended_text = done_re
        .replace_all(&comments_extended_text, |caps: &regex::Captures<'_>| {
            let done = if resolved_para_ids.contains(&caps[2]) {
                "1"
            } else {
                "0"
            };
            format!(r#"{}w15:done="{}""#, &caps[1], done)
        })
        .into_owned();

    xml_docx.comments = comments_text.into_bytes();
    xml_docx.comments_extended = comments_extended_text.into_bytes();
    Ok(())
}

/// Skribisto's own extension namespace, used only to carry
/// [`common::parser_tools::DocumentComment::uid`] on a `<w:comment>` — see
/// `patch_comment_extras`. Versioned so a future incompatible shape change
/// does not get misread as the current one by an older writer or reader sharing this crate.
const SKRB_NAMESPACE_URI: &str = "urn:ferntech:text-document:comment:1";

/// Declare [`SKRB_NAMESPACE_URI`] under the `skrb` prefix on `comments.xml`'s root element —
/// the same element that already declares `xmlns:o`, `xmlns:w`, etc. (see `Comments::build_to`
/// in `docx-rs`, `xml_builder/comments.rs`). Errors rather than silently no-opping if the root
/// tag is not found in the expected shape, since a silent no-op here would leave every
/// `skrb:uid` attribute a namespace error nothing downstream would explain.
fn declare_skrb_namespace(comments_text: String) -> Result<String> {
    let patched = comments_text.replacen(
        "<w:comments ",
        &format!(r#"<w:comments xmlns:skrb="{SKRB_NAMESPACE_URI}" "#),
        1,
    );
    if patched == comments_text {
        return Err(anyhow!(
            "word/comments.xml did not start with the expected '<w:comments ' root element — \
             cannot declare the skrb: namespace the uid attribute needs"
        ));
    }
    Ok(patched)
}

/// Escape `s` for use inside a double-quoted XML attribute value. `docx-rs`'s own writer
/// (`xml-rs`) escapes everything it writes; this hand-rolled escaper exists only for the two
/// attribute values this module injects directly as text (`w:initials`, `skrb:uid`) rather
/// than through that writer.
fn xml_attr_escape(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '"' => out.push_str("&quot;"),
            // Dropped, not escaped. These are illegal in XML 1.0 *in any form* — there is no
            // character reference that makes them legal — so emitting one produces a file no
            // parser will open, and `&#x1;` would be just as fatal as the raw byte. Word will
            // happily let an author paste one into a comment, and `w:initials` is written
            // from exactly that text. `odt_render::xml_escape` already drops them; this is the
            // same rule, and the two must not disagree about which files they can write.
            '\u{0}'..='\u{8}' | '\u{b}' | '\u{c}' | '\u{e}'..='\u{1f}' => {}
            _ => out.push(c),
        }
    }
    out
}