rhwp 0.9.0

HWP/HWPX document engine for Rust applications, WebAssembly, and CLI automation
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
//! 머리말/꼬리말 생성·조회·텍스트 편집 관련 native 메서드

use super::clipboard::{
    clip_paragraph_text_range_for_clipboard, strip_structural_controls_for_text_clipboard,
};
use super::formatting::{
    char_shape_mods_affect_text_flow, para_shape_mods_affect_text_flow, restore_para_meta,
};
use crate::document_core::helpers::{
    build_tab_def_from_json, json_has_border_keys, json_has_tab_keys, parse_char_shape_mods,
    parse_json_i16_array, parse_para_shape_mods,
};
use crate::document_core::{
    header_footer_apply_from_u8, header_footer_apply_to_u8, ClipboardData, DocumentCore,
};
use crate::error::HwpError;
use crate::model::control::Control;
use crate::model::event::DocumentEvent;
use crate::model::header_footer::{Footer, Header, HeaderFooterApply};
use crate::model::paragraph::{ParaMeta, Paragraph};
use crate::renderer::composer::{reflow_line_segs, restamp_indentation, ParagraphBox};

/// HeaderFooterApply → 표시 레이블
fn apply_label(a: HeaderFooterApply) -> &'static str {
    match a {
        HeaderFooterApply::Both => "양 쪽",
        HeaderFooterApply::Even => "짝수 쪽",
        HeaderFooterApply::Odd => "홀수 쪽",
    }
}

impl DocumentCore {
    /// 머리말/꼬리말 정의를 편집할 대표 페이지(구역 첫 페이지)를 반환한다.
    ///
    /// 반환: JSON `{"ok":true,"pageIndex":N,"sectionIdx":N}`
    pub fn get_header_footer_preview_page_native(
        &self,
        section_idx: usize,
    ) -> Result<String, HwpError> {
        let page_index = self.header_footer_preview_page_for_section(section_idx)?;
        Ok(format!(
            "{{\"ok\":true,\"pageIndex\":{},\"sectionIdx\":{}}}",
            page_index, section_idx
        ))
    }

    /// 머리말/꼬리말 조회 — JSON 반환
    ///
    /// 존재하면: `{"ok":true,"exists":true,"applyTo":0,"paraCount":N,"text":"..."}`
    /// 없으면: `{"ok":true,"exists":false}`
    pub fn get_header_footer_native(
        &self,
        section_idx: usize,
        is_header: bool,
        apply_to: u8,
    ) -> Result<String, HwpError> {
        if section_idx >= self.document.sections.len() {
            return Err(HwpError::RenderError(format!(
                "구역 인덱스 {} 범위 초과 (총 {}개)",
                section_idx,
                self.document.sections.len()
            )));
        }
        let apply = header_footer_apply_from_u8(apply_to);
        if let Some((pi, ci)) = self.find_header_footer_control(section_idx, is_header, apply) {
            let section = &self.document.sections[section_idx];
            let ctrl = &section.paragraphs[pi].controls[ci];
            let (paragraphs, at) = match ctrl {
                Control::Header(h) => (&h.paragraphs, h.apply_to),
                Control::Footer(f) => (&f.paragraphs, f.apply_to),
                _ => unreachable!(),
            };
            let text: String = paragraphs
                .iter()
                .map(|p| p.text.clone())
                .collect::<Vec<_>>()
                .join("\n");
            let kind = if is_header { "header" } else { "footer" };
            let label = apply_label(at);
            Ok(format!(
                "{{\"ok\":true,\"exists\":true,\"kind\":\"{}\",\"applyTo\":{},\"label\":\"{}\",\"paraIndex\":{},\"controlIndex\":{},\"paraCount\":{},\"text\":\"{}\"}}",
                kind, header_footer_apply_to_u8(at), label, pi, ci, paragraphs.len(),
                super::super::helpers::json_escape(&text)
            ))
        } else {
            Ok(format!("{{\"ok\":true,\"exists\":false}}"))
        }
    }

    /// 머리말/꼬리말 생성 — 빈 문단 1개 포함
    ///
    /// 이미 같은 apply_to의 머리말/꼬리말이 있으면 에러.
    /// 구역의 첫 번째 문단(SectionDef 컨트롤이 있는 문단)에 컨트롤을 추가한다.
    pub fn create_header_footer_native(
        &mut self,
        section_idx: usize,
        is_header: bool,
        apply_to: u8,
    ) -> Result<String, HwpError> {
        if section_idx >= self.document.sections.len() {
            return Err(HwpError::RenderError(format!(
                "구역 인덱스 {} 범위 초과 (총 {}개)",
                section_idx,
                self.document.sections.len()
            )));
        }
        let apply = header_footer_apply_from_u8(apply_to);
        if self
            .find_header_footer_control(section_idx, is_header, apply)
            .is_some()
        {
            let kind = if is_header { "머리말" } else { "꼬리말" };
            return Err(HwpError::RenderError(format!(
                "이미 {}({})이 존재합니다",
                kind,
                apply_label(apply)
            )));
        }

        // 새 머리말/꼬리말도 본문과 같은 문서 기본 문단 모양(0번)을 사용한다.
        // blank2010의 0번 모양은 양쪽 정렬이다. 합성 HF에는 저장 LINE_SEG를 미리
        // 만들지 않아 파일명·쪽번호 같은 동적 필드가 현재 문서 문맥으로 해석되게 한다.
        let empty_para = Paragraph::default();

        // 컨트롤 생성
        let ctrl = if is_header {
            Control::Header(Box::new(Header {
                apply_to: apply,
                paragraphs: vec![empty_para],
                raw_attr: apply_to as u32,
                raw_ctrl_extra: Vec::new(),
                ..Default::default()
            }))
        } else {
            Control::Footer(Box::new(Footer {
                apply_to: apply,
                paragraphs: vec![empty_para],
                raw_attr: apply_to as u32,
                raw_ctrl_extra: Vec::new(),
                ..Default::default()
            }))
        };

        // 구역의 첫 번째 문단에 컨트롤 추가 (SectionDef 컨트롤이 있는 곳)
        let section = &mut self.document.sections[section_idx];
        if section.paragraphs.is_empty() {
            return Err(HwpError::RenderError("구역에 문단이 없습니다".to_string()));
        }
        section.paragraphs[0].controls.push(ctrl);
        // [#3214] controls 만 늘리면 ctrl_data_records 와의 인덱스 대응이 깨져, 이후 같은
        // 문단에 각주·미주·수식을 삽입할 때 ctrl_data_records.insert 가 범위를 넘어 패닉한다.
        section.paragraphs[0].align_ctrl_data_records();
        // 컨트롤 1개 = UTF-16 8 code units → char_count 갱신
        section.paragraphs[0].char_count += 8;
        section.raw_stream = None;

        // 재페이지네이션 (머리말/꼬리말이 추가되면 페이지 레이아웃에 영향)
        self.mark_section_dirty(section_idx);
        self.paginate_if_needed();

        // 생성된 컨트롤 위치 반환
        let (pi, ci) = self
            .find_header_footer_control(section_idx, is_header, apply)
            .expect("방금 생성한 컨트롤을 찾을 수 없음");

        let kind = if is_header { "header" } else { "footer" };
        let label = apply_label(apply);
        Ok(format!(
            "{{\"ok\":true,\"kind\":\"{}\",\"applyTo\":{},\"label\":\"{}\",\"paraIndex\":{},\"controlIndex\":{}}}",
            kind, apply_to, label, pi, ci
        ))
    }

    /// 머리말/꼬리말 내부 문단에 대한 가변 참조를 얻는다.
    fn get_hf_paragraph_mut(
        &mut self,
        section_idx: usize,
        is_header: bool,
        apply_to: u8,
        hf_para_idx: usize,
    ) -> Result<&mut Paragraph, HwpError> {
        let apply = header_footer_apply_from_u8(apply_to);
        let (pi, ci) = self
            .find_header_footer_control(section_idx, is_header, apply)
            .ok_or_else(|| {
                let kind = if is_header { "머리말" } else { "꼬리말" };
                HwpError::RenderError(format!(
                    "{}({})이 존재하지 않습니다",
                    kind,
                    apply_label(apply)
                ))
            })?;

        let ctrl = &mut self.document.sections[section_idx].paragraphs[pi].controls[ci];
        match ctrl {
            Control::Header(h) => {
                if hf_para_idx >= h.paragraphs.len() {
                    return Err(HwpError::RenderError(format!(
                        "머리말 문단 인덱스 {} 범위 초과 (총 {}개)",
                        hf_para_idx,
                        h.paragraphs.len()
                    )));
                }
                Ok(&mut h.paragraphs[hf_para_idx])
            }
            Control::Footer(f) => {
                if hf_para_idx >= f.paragraphs.len() {
                    return Err(HwpError::RenderError(format!(
                        "꼬리말 문단 인덱스 {} 범위 초과 (총 {}개)",
                        hf_para_idx,
                        f.paragraphs.len()
                    )));
                }
                Ok(&mut f.paragraphs[hf_para_idx])
            }
            _ => Err(HwpError::RenderError(
                "컨트롤이 머리말/꼬리말이 아닙니다".to_string(),
            )),
        }
    }

    /// 머리말/꼬리말 내부 문단에 대한 불변 참조를 얻는다.
    fn get_hf_paragraph_ref(
        &self,
        section_idx: usize,
        is_header: bool,
        apply_to: u8,
        hf_para_idx: usize,
    ) -> Option<&Paragraph> {
        let apply = header_footer_apply_from_u8(apply_to);
        let (pi, ci) = self.find_header_footer_control(section_idx, is_header, apply)?;
        let ctrl = &self.document.sections[section_idx].paragraphs[pi].controls[ci];
        match ctrl {
            Control::Header(h) => h.paragraphs.get(hf_para_idx),
            Control::Footer(f) => f.paragraphs.get(hf_para_idx),
            _ => None,
        }
    }

    /// 머리말/꼬리말 정의의 전체 문단 슬라이스를 얻는다.
    pub(crate) fn get_hf_paragraphs_ref(
        &self,
        section_idx: usize,
        is_header: bool,
        apply_to: u8,
    ) -> Result<&[Paragraph], HwpError> {
        let apply = header_footer_apply_from_u8(apply_to);
        let (pi, ci) = self
            .find_header_footer_control(section_idx, is_header, apply)
            .ok_or_else(|| {
                HwpError::RenderError("머리말/꼬리말 정의를 찾을 수 없음".to_string())
            })?;
        match &self.document.sections[section_idx].paragraphs[pi].controls[ci] {
            Control::Header(header) => Ok(&header.paragraphs),
            Control::Footer(footer) => Ok(&footer.paragraphs),
            _ => Err(HwpError::RenderError(
                "컨트롤이 머리말/꼬리말이 아닙니다".to_string(),
            )),
        }
    }

    /// 머리말/꼬리말 정의의 전체 문단 벡터를 얻는다.
    fn get_hf_paragraphs_mut(
        &mut self,
        section_idx: usize,
        is_header: bool,
        apply_to: u8,
    ) -> Result<&mut Vec<Paragraph>, HwpError> {
        let apply = header_footer_apply_from_u8(apply_to);
        let (pi, ci) = self
            .find_header_footer_control(section_idx, is_header, apply)
            .ok_or_else(|| {
                HwpError::RenderError("머리말/꼬리말 정의를 찾을 수 없음".to_string())
            })?;
        match &mut self.document.sections[section_idx].paragraphs[pi].controls[ci] {
            Control::Header(header) => Ok(&mut header.paragraphs),
            Control::Footer(footer) => Ok(&mut footer.paragraphs),
            _ => Err(HwpError::RenderError(
                "컨트롤이 머리말/꼬리말이 아닙니다".to_string(),
            )),
        }
    }

    /// 머리말/꼬리말 내 텍스트 삽입
    pub fn insert_text_in_header_footer_native(
        &mut self,
        section_idx: usize,
        is_header: bool,
        apply_to: u8,
        hf_para_idx: usize,
        char_offset: usize,
        text: &str,
    ) -> Result<String, HwpError> {
        if section_idx >= self.document.sections.len() {
            return Err(HwpError::RenderError(format!(
                "구역 인덱스 {} 범위 초과 (총 {}개)",
                section_idx,
                self.document.sections.len()
            )));
        }

        let hf_para = self.get_hf_paragraph_mut(section_idx, is_header, apply_to, hf_para_idx)?;
        let new_chars_count = text.chars().count();
        let inserted_at = hf_para.insert_text_at(char_offset, text);

        // 리플로우 (머리말/꼬리말 영역 폭 기반)
        self.reflow_hf_paragraph(section_idx, is_header, apply_to, hf_para_idx);

        // raw 스트림 무효화, 재페이지네이션
        self.document.sections[section_idx].raw_stream = None;
        self.mark_section_dirty(section_idx);
        self.paginate_if_needed();

        let new_offset = inserted_at + new_chars_count;
        self.event_log
            .push(DocumentEvent::HeaderFooterTextReplaced {
                section: section_idx,
                is_header,
                apply_to,
                start_para: hf_para_idx,
                start_offset: inserted_at,
                end_para: hf_para_idx,
                end_offset: inserted_at,
                inserted_end_para: hf_para_idx,
                inserted_end_offset: new_offset,
            });
        Ok(super::super::helpers::json_ok_with(&format!(
            "\"charOffset\":{}",
            new_offset
        )))
    }

    /// 머리말/꼬리말 내 텍스트 삭제
    pub fn delete_text_in_header_footer_native(
        &mut self,
        section_idx: usize,
        is_header: bool,
        apply_to: u8,
        hf_para_idx: usize,
        char_offset: usize,
        count: usize,
    ) -> Result<String, HwpError> {
        if section_idx >= self.document.sections.len() {
            return Err(HwpError::RenderError(format!(
                "구역 인덱스 {} 범위 초과 (총 {}개)",
                section_idx,
                self.document.sections.len()
            )));
        }

        let hf_para = self.get_hf_paragraph_mut(section_idx, is_header, apply_to, hf_para_idx)?;
        // [Task #2337] undo 재삽입용으로 삭제될 텍스트를 먼저 확보한다. char 단위 슬라이스는
        // delete_text_at 의 클램핑(text_len - char_offset)과 동일 범위이며, Rust char 경계로
        // 잘라 studio(UTF-16) 측 조인 모호성을 피한다. 역연산 삭제 커맨드가 재삽입에 쓴다.
        let actual_offset = char_offset.min(hf_para.text.chars().count());
        let deleted_text: String = hf_para
            .text
            .chars()
            .skip(actual_offset)
            .take(count)
            .collect();
        hf_para.delete_text_at(actual_offset, count);

        // 리플로우
        self.reflow_hf_paragraph(section_idx, is_header, apply_to, hf_para_idx);

        // raw 스트림 무효화, 재페이지네이션
        self.document.sections[section_idx].raw_stream = None;
        self.mark_section_dirty(section_idx);
        self.paginate_if_needed();

        let deleted_count = deleted_text.chars().count();
        self.event_log
            .push(DocumentEvent::HeaderFooterTextReplaced {
                section: section_idx,
                is_header,
                apply_to,
                start_para: hf_para_idx,
                start_offset: actual_offset,
                end_para: hf_para_idx,
                end_offset: actual_offset + deleted_count,
                inserted_end_para: hf_para_idx,
                inserted_end_offset: actual_offset,
            });
        Ok(super::super::helpers::json_ok_with(&format!(
            "\"charOffset\":{},\"deletedText\":\"{}\"",
            actual_offset,
            super::super::helpers::json_escape(&deleted_text)
        )))
    }

    /// 머리말/꼬리말 내 문단 분할 (Enter 키)
    pub fn split_paragraph_in_header_footer_native(
        &mut self,
        section_idx: usize,
        is_header: bool,
        apply_to: u8,
        hf_para_idx: usize,
        char_offset: usize,
        restore_meta: Option<ParaMeta>,
    ) -> Result<String, HwpError> {
        if section_idx >= self.document.sections.len() {
            return Err(HwpError::RenderError(format!(
                "구역 인덱스 {} 범위 초과",
                section_idx
            )));
        }

        let apply = header_footer_apply_from_u8(apply_to);
        let (pi, ci) = self
            .find_header_footer_control(section_idx, is_header, apply)
            .ok_or_else(|| {
                let kind = if is_header { "머리말" } else { "꼬리말" };
                HwpError::RenderError(format!("{}이 존재하지 않습니다", kind))
            })?;

        // 문단 분할
        let new_para = {
            let ctrl = &mut self.document.sections[section_idx].paragraphs[pi].controls[ci];
            let paragraphs = match ctrl {
                Control::Header(h) => &mut h.paragraphs,
                Control::Footer(f) => &mut f.paragraphs,
                _ => return Err(HwpError::RenderError("컨트롤 타입 불일치".to_string())),
            };
            if hf_para_idx >= paragraphs.len() {
                return Err(HwpError::RenderError(format!(
                    "문단 인덱스 {} 범위 초과",
                    hf_para_idx
                )));
            }
            let mut new_para = paragraphs[hf_para_idx].split_at(char_offset);
            if let Some(meta) = restore_meta {
                restore_para_meta(&mut new_para, meta, &self.document.doc_info.para_shapes);
            }
            new_para
        };

        // 새 문단 삽입
        let new_para_idx = hf_para_idx + 1;
        {
            let ctrl = &mut self.document.sections[section_idx].paragraphs[pi].controls[ci];
            let paragraphs = match ctrl {
                Control::Header(h) => &mut h.paragraphs,
                Control::Footer(f) => &mut f.paragraphs,
                _ => unreachable!(),
            };
            paragraphs.insert(new_para_idx, new_para);
        }

        // 리플로우
        self.reflow_hf_paragraph(section_idx, is_header, apply_to, hf_para_idx);
        self.reflow_hf_paragraph(section_idx, is_header, apply_to, new_para_idx);

        self.document.sections[section_idx].raw_stream = None;
        self.mark_section_dirty(section_idx);
        self.paginate_if_needed();

        self.event_log.push(DocumentEvent::ParagraphSplit {
            section: section_idx,
            para: hf_para_idx,
            offset: char_offset,
        });
        Ok(super::super::helpers::json_ok_with(&format!(
            "\"hfParaIndex\":{},\"charOffset\":0",
            new_para_idx
        )))
    }

    /// 머리말/꼬리말 내 문단 병합 (Backspace at start)
    pub fn merge_paragraph_in_header_footer_native(
        &mut self,
        section_idx: usize,
        is_header: bool,
        apply_to: u8,
        hf_para_idx: usize,
    ) -> Result<String, HwpError> {
        if section_idx >= self.document.sections.len() {
            return Err(HwpError::RenderError(format!(
                "구역 인덱스 {} 범위 초과",
                section_idx
            )));
        }
        if hf_para_idx == 0 {
            return Err(HwpError::RenderError(
                "첫 번째 문단은 이전 문단과 병합할 수 없습니다".to_string(),
            ));
        }

        let apply = header_footer_apply_from_u8(apply_to);
        let (pi, ci) = self
            .find_header_footer_control(section_idx, is_header, apply)
            .ok_or_else(|| {
                let kind = if is_header { "머리말" } else { "꼬리말" };
                HwpError::RenderError(format!("{}이 존재하지 않습니다", kind))
            })?;

        // 병합
        let merge_offset;
        let removed_meta;
        {
            let ctrl = &mut self.document.sections[section_idx].paragraphs[pi].controls[ci];
            let paragraphs = match ctrl {
                Control::Header(h) => &mut h.paragraphs,
                Control::Footer(f) => &mut f.paragraphs,
                _ => return Err(HwpError::RenderError("컨트롤 타입 불일치".to_string())),
            };
            if hf_para_idx >= paragraphs.len() {
                return Err(HwpError::RenderError(format!(
                    "문단 인덱스 {} 범위 초과",
                    hf_para_idx
                )));
            }
            merge_offset = paragraphs[hf_para_idx - 1].text.chars().count();
            let removed = paragraphs.remove(hf_para_idx);
            removed_meta = super::super::helpers::removed_para_meta_field(&removed.capture_meta());
            paragraphs[hf_para_idx - 1].merge_from(&removed);
        }

        let prev_idx = hf_para_idx - 1;
        self.reflow_hf_paragraph(section_idx, is_header, apply_to, prev_idx);

        self.document.sections[section_idx].raw_stream = None;
        self.mark_section_dirty(section_idx);
        self.paginate_if_needed();

        self.event_log.push(DocumentEvent::ParagraphMerged {
            section: section_idx,
            para: hf_para_idx,
        });
        Ok(super::super::helpers::json_ok_with(&format!(
            "\"hfParaIndex\":{},\"charOffset\":{}{}",
            prev_idx, merge_offset, removed_meta
        )))
    }

    /// 머리말/꼬리말 문단의 정보를 반환한다 (문단 수, 현재 문단 텍스트 길이 등).
    pub fn get_header_footer_para_info_native(
        &self,
        section_idx: usize,
        is_header: bool,
        apply_to: u8,
        hf_para_idx: usize,
    ) -> Result<String, HwpError> {
        if section_idx >= self.document.sections.len() {
            return Err(HwpError::RenderError(format!(
                "구역 인덱스 {} 범위 초과",
                section_idx
            )));
        }
        let apply = header_footer_apply_from_u8(apply_to);
        let (pi, ci) = self
            .find_header_footer_control(section_idx, is_header, apply)
            .ok_or_else(|| {
                let kind = if is_header { "머리말" } else { "꼬리말" };
                HwpError::RenderError(format!("{}이 존재하지 않습니다", kind))
            })?;

        let ctrl = &self.document.sections[section_idx].paragraphs[pi].controls[ci];
        let paragraphs = match ctrl {
            Control::Header(h) => &h.paragraphs,
            Control::Footer(f) => &f.paragraphs,
            _ => return Err(HwpError::RenderError("컨트롤 타입 불일치".to_string())),
        };

        let para_count = paragraphs.len();
        let (char_count, text) = if let Some(paragraph) = paragraphs.get(hf_para_idx) {
            (paragraph.text.chars().count(), paragraph.text.as_str())
        } else {
            (0, "")
        };

        Ok(format!(
            "{{\"ok\":true,\"paraCount\":{},\"charCount\":{},\"text\":\"{}\"}}",
            para_count,
            char_count,
            super::super::helpers::json_escape(text)
        ))
    }

    /// 머리말/꼬리말의 선택 범위를 평문으로 원자 치환한다.
    ///
    /// 범위는 문단/문자 사전식 순서로 정렬하고 모든 경계를 mutation 전에 검증한다.
    /// `replacement_text`의 줄바꿈은 새 HF 문단으로 보존한다.
    #[allow(clippy::too_many_arguments)]
    pub fn replace_range_in_header_footer_native(
        &mut self,
        section_idx: usize,
        is_header: bool,
        apply_to: u8,
        start_hf_para_idx: usize,
        start_char_offset: usize,
        end_hf_para_idx: usize,
        end_char_offset: usize,
        replacement_text: &str,
    ) -> Result<String, HwpError> {
        let ((start_para, start_offset), (end_para, end_offset)) =
            if (start_hf_para_idx, start_char_offset) > (end_hf_para_idx, end_char_offset) {
                (
                    (end_hf_para_idx, end_char_offset),
                    (start_hf_para_idx, start_char_offset),
                )
            } else {
                (
                    (start_hf_para_idx, start_char_offset),
                    (end_hf_para_idx, end_char_offset),
                )
            };

        {
            let paragraphs = self.get_hf_paragraphs_ref(section_idx, is_header, apply_to)?;
            if start_para >= paragraphs.len() || end_para >= paragraphs.len() {
                return Err(HwpError::RenderError(format!(
                    "머리말/꼬리말 문단 범위 초과 (start={}, end={}, total={})",
                    start_para,
                    end_para,
                    paragraphs.len()
                )));
            }
            let start_len = paragraphs[start_para].text.chars().count();
            let end_len = paragraphs[end_para].text.chars().count();
            if start_offset > start_len || end_offset > end_len {
                return Err(HwpError::RenderError(format!(
                    "머리말/꼬리말 문자 범위 초과 (start={}/{}, end={}/{})",
                    start_offset, start_len, end_offset, end_len
                )));
            }
        }

        let normalized = replacement_text.replace("\r\n", "\n").replace('\r', "\n");
        let lines: Vec<&str> = normalized.split('\n').collect();
        let (cursor_para, cursor_offset);
        {
            let paragraphs = self.get_hf_paragraphs_mut(section_idx, is_header, apply_to)?;

            // 끝 문단의 선택 뒤 suffix를 서식·인라인 컨트롤과 함께 보존한다.
            let suffix = {
                let mut end_snapshot = paragraphs[end_para].clone();
                end_snapshot.split_at(end_offset)
            };

            // 시작 문단은 선택 앞 prefix만 남긴다. 다문단이면 선택에 포함된 나머지
            // 문단을 제거하고 이 prefix가 결과의 첫 문단을 소유한다.
            let _discarded_tail = paragraphs[start_para].split_at(start_offset);
            if end_para > start_para {
                paragraphs.drain((start_para + 1)..=end_para);
            }

            paragraphs[start_para].insert_text_at(start_offset, lines[0]);
            let mut result_para = start_para;
            if lines.len() == 1 {
                cursor_offset = start_offset + lines[0].chars().count();
            } else {
                for line in lines.iter().skip(1) {
                    let mut next = Paragraph::new_empty_like(&paragraphs[result_para]);
                    next.insert_text_at(0, line);
                    result_para += 1;
                    paragraphs.insert(result_para, next);
                }
                cursor_offset = lines.last().map(|line| line.chars().count()).unwrap_or(0);
            }
            paragraphs[result_para].merge_from(&suffix);
            cursor_para = result_para;
        }

        let para_count = self
            .get_hf_paragraphs_ref(section_idx, is_header, apply_to)?
            .len();
        for hf_para_idx in 0..para_count {
            self.reflow_hf_paragraph(section_idx, is_header, apply_to, hf_para_idx);
        }
        self.document.sections[section_idx].raw_stream = None;
        self.rebuild_section(section_idx);
        self.event_log
            .push(DocumentEvent::HeaderFooterTextReplaced {
                section: section_idx,
                is_header,
                apply_to,
                start_para,
                start_offset,
                end_para,
                end_offset,
                inserted_end_para: cursor_para,
                inserted_end_offset: cursor_offset,
            });

        Ok(super::super::helpers::json_ok_with(&format!(
            "\"hfParaIndex\":{},\"charOffset\":{}",
            cursor_para, cursor_offset
        )))
    }

    /// 머리말/꼬리말 선택 범위를 내부 클립보드에 복사한다.
    #[allow(clippy::too_many_arguments)]
    pub fn copy_selection_in_header_footer_native(
        &mut self,
        section_idx: usize,
        is_header: bool,
        apply_to: u8,
        start_hf_para_idx: usize,
        start_char_offset: usize,
        end_hf_para_idx: usize,
        end_char_offset: usize,
    ) -> Result<String, HwpError> {
        if (start_hf_para_idx, start_char_offset) > (end_hf_para_idx, end_char_offset) {
            return Err(HwpError::RenderError(
                "시작 위치가 끝 위치보다 뒤에 있음".to_string(),
            ));
        }

        let mut clip_paragraphs = {
            let paragraphs = self.get_hf_paragraphs_ref(section_idx, is_header, apply_to)?;
            if start_hf_para_idx >= paragraphs.len() || end_hf_para_idx >= paragraphs.len() {
                return Err(HwpError::RenderError(format!(
                    "머리말/꼬리말 문단 범위 초과 (start={}, end={}, total={})",
                    start_hf_para_idx,
                    end_hf_para_idx,
                    paragraphs.len()
                )));
            }
            let start_len = paragraphs[start_hf_para_idx].text.chars().count();
            let end_len = paragraphs[end_hf_para_idx].text.chars().count();
            if start_char_offset > start_len || end_char_offset > end_len {
                return Err(HwpError::RenderError(
                    "머리말/꼬리말 문자 범위 초과".to_string(),
                ));
            }

            let mut selected = Vec::new();
            if start_hf_para_idx == end_hf_para_idx {
                selected.push(clip_paragraph_text_range_for_clipboard(
                    &paragraphs[start_hf_para_idx],
                    start_char_offset,
                    end_char_offset,
                ));
            } else {
                selected.push(clip_paragraph_text_range_for_clipboard(
                    &paragraphs[start_hf_para_idx],
                    start_char_offset,
                    start_len,
                ));
                selected.extend(
                    paragraphs[(start_hf_para_idx + 1)..end_hf_para_idx]
                        .iter()
                        .cloned(),
                );
                selected.push(clip_paragraph_text_range_for_clipboard(
                    &paragraphs[end_hf_para_idx],
                    0,
                    end_char_offset,
                ));
            }
            selected
        };

        for paragraph in &mut clip_paragraphs {
            strip_structural_controls_for_text_clipboard(paragraph);
        }
        let plain_text = clip_paragraphs
            .iter()
            .map(|paragraph| paragraph.text.as_str())
            .collect::<Vec<_>>()
            .join("\n");
        let escaped = super::super::helpers::json_escape(&plain_text);
        self.clipboard = Some(ClipboardData {
            paragraphs: clip_paragraphs,
            plain_text,
            copied_table_text_reflowed: false,
        });
        Ok(super::super::helpers::json_ok_with(&format!(
            "\"text\":\"{}\"",
            escaped
        )))
    }

    /// 머리말/꼬리말 캐럿 위치의 글자 속성을 조회한다.
    pub fn get_char_properties_in_header_footer_native(
        &self,
        section_idx: usize,
        is_header: bool,
        apply_to: u8,
        hf_para_idx: usize,
        char_offset: usize,
    ) -> Result<String, HwpError> {
        let paragraph = self
            .get_hf_paragraph_ref(section_idx, is_header, apply_to, hf_para_idx)
            .ok_or_else(|| {
                HwpError::RenderError("머리말/꼬리말 문단을 찾을 수 없음".to_string())
            })?;
        if char_offset > paragraph.text.chars().count() {
            return Err(HwpError::RenderError(
                "머리말/꼬리말 문자 범위 초과".to_string(),
            ));
        }
        Ok(self.build_char_properties_json(paragraph, char_offset))
    }

    /// 머리말/꼬리말의 단일·다문단 선택 범위에 글자 서식을 적용한다.
    #[allow(clippy::too_many_arguments)]
    pub fn apply_char_format_in_header_footer_native(
        &mut self,
        section_idx: usize,
        is_header: bool,
        apply_to: u8,
        start_hf_para_idx: usize,
        start_char_offset: usize,
        end_hf_para_idx: usize,
        end_char_offset: usize,
        props_json: &str,
    ) -> Result<String, HwpError> {
        if (start_hf_para_idx, start_char_offset) > (end_hf_para_idx, end_char_offset) {
            return Err(HwpError::RenderError(
                "시작 위치가 끝 위치보다 뒤에 있음".to_string(),
            ));
        }
        {
            let paragraphs = self.get_hf_paragraphs_ref(section_idx, is_header, apply_to)?;
            if start_hf_para_idx >= paragraphs.len() || end_hf_para_idx >= paragraphs.len() {
                return Err(HwpError::RenderError(
                    "머리말/꼬리말 문단 범위 초과".to_string(),
                ));
            }
            if start_char_offset > paragraphs[start_hf_para_idx].text.chars().count()
                || end_char_offset > paragraphs[end_hf_para_idx].text.chars().count()
            {
                return Err(HwpError::RenderError(
                    "머리말/꼬리말 문자 범위 초과".to_string(),
                ));
            }
        }

        let mut mods = parse_char_shape_mods(props_json);
        if json_has_border_keys(props_json) {
            mods.border_fill_id = Some(self.create_border_fill_from_json(props_json));
        }

        let affects_flow = char_shape_mods_affect_text_flow(&mods);
        let mut changed_paragraphs = Vec::new();
        for hf_para_idx in start_hf_para_idx..=end_hf_para_idx {
            let paragraph_len = self
                .get_hf_paragraph_ref(section_idx, is_header, apply_to, hf_para_idx)
                .map(|paragraph| paragraph.text.chars().count())
                .unwrap_or(0);
            let range_start = if hf_para_idx == start_hf_para_idx {
                start_char_offset
            } else {
                0
            };
            let range_end = if hf_para_idx == end_hf_para_idx {
                end_char_offset
            } else {
                paragraph_len
            };
            if range_end <= range_start {
                continue;
            }

            let base_ids = self
                .get_hf_paragraph_ref(section_idx, is_header, apply_to, hf_para_idx)
                .ok_or_else(|| {
                    HwpError::RenderError(format!("머리말/꼬리말 문단 {hf_para_idx} 누락"))
                })?
                .char_shape_ids_in_range(range_start, range_end);
            let ids = self.document.modified_char_shape_ids(base_ids, &mods);
            self.get_hf_paragraph_mut(section_idx, is_header, apply_to, hf_para_idx)?
                .try_map_char_shape_range(range_start, range_end, |id| {
                    ids.get(&id).copied().ok_or_else(|| {
                        HwpError::RenderError(format!("글자 모양 변환 ID {id} 누락"))
                    })
                })?;
            changed_paragraphs.push((hf_para_idx, range_start, range_end));
        }

        if affects_flow {
            for (hf_para_idx, _, _) in &changed_paragraphs {
                self.reflow_hf_paragraph(section_idx, is_header, apply_to, *hf_para_idx);
            }
        }
        self.document.sections[section_idx].raw_stream = None;
        self.rebuild_section(section_idx);
        for (hf_para_idx, range_start, range_end) in changed_paragraphs {
            self.event_log.push(DocumentEvent::CharFormatChanged {
                section: section_idx,
                para: hf_para_idx,
                start: range_start,
                end: range_end,
            });
        }
        Ok("{\"ok\":true}".to_string())
    }

    /// 머리말/꼬리말 삭제 (컨트롤 자체를 제거)
    pub fn delete_header_footer_native(
        &mut self,
        section_idx: usize,
        is_header: bool,
        apply_to: u8,
    ) -> Result<String, HwpError> {
        if section_idx >= self.document.sections.len() {
            return Err(HwpError::RenderError(format!(
                "구역 인덱스 {} 범위 초과 (총 {}개)",
                section_idx,
                self.document.sections.len()
            )));
        }
        let apply = header_footer_apply_from_u8(apply_to);
        let (pi, ci) = self
            .find_header_footer_control(section_idx, is_header, apply)
            .ok_or_else(|| {
                let kind = if is_header { "머리말" } else { "꼬리말" };
                HwpError::RenderError(format!(
                    "{}({})이 존재하지 않습니다",
                    kind,
                    apply_label(apply)
                ))
            })?;

        self.document.sections[section_idx].paragraphs[pi]
            .controls
            .remove(ci);
        // 컨트롤 1개 = UTF-16 8 code units → char_count 갱신
        self.document.sections[section_idx].paragraphs[pi].char_count =
            self.document.sections[section_idx].paragraphs[pi]
                .char_count
                .saturating_sub(8);
        self.document.sections[section_idx].raw_stream = None;
        self.mark_section_dirty(section_idx);
        self.paginate_if_needed();

        Ok(format!("{{\"ok\":true}}"))
    }

    /// 문서 전체의 머리말/꼬리말 목록을 반환한다.
    ///
    /// JSON: `{"ok":true,"items":[{"sectionIdx":N,"isHeader":bool,"applyTo":N,"label":"..."},...],
    ///         "currentIndex":N}`
    /// currentSectionIdx/currentIsHeader/currentApplyTo로 현재 편집 중인 항목의 인덱스를 반환.
    pub fn get_header_footer_list_native(
        &self,
        current_section_idx: usize,
        current_is_header: bool,
        current_apply_to: u8,
    ) -> Result<String, HwpError> {
        let mut items = Vec::new();
        let mut current_index: i32 = -1;
        let current_apply = header_footer_apply_from_u8(current_apply_to);

        for (si, section) in self.document.sections.iter().enumerate() {
            for (pi, para) in section.paragraphs.iter().enumerate() {
                for (ci, ctrl) in para.controls.iter().enumerate() {
                    let (is_header, apply) = match ctrl {
                        Control::Header(h) => (true, h.apply_to),
                        Control::Footer(f) => (false, f.apply_to),
                        _ => continue,
                    };
                    let kind = if is_header { "머리말" } else { "꼬리말" };
                    let label = apply_label(apply);
                    let at = header_footer_apply_to_u8(apply);

                    if si == current_section_idx
                        && is_header == current_is_header
                        && apply == current_apply
                    {
                        current_index = items.len() as i32;
                    }

                    items.push(format!(
                        "{{\"sectionIdx\":{},\"isHeader\":{},\"applyTo\":{},\"label\":\"{}({})\"}}",
                        si, is_header, at, kind, label
                    ));
                }
            }
        }

        Ok(format!(
            "{{\"ok\":true,\"items\":[{}],\"currentIndex\":{}}}",
            items.join(","),
            current_index
        ))
    }

    /// 페이지 단위로 이전/다음 머리말·꼬리말로 이동한다.
    ///
    /// 현재 페이지에서 direction 방향으로 탐색하여 머리말/꼬리말이 있는 다음 페이지를 찾는다.
    /// 홀수/짝수 페이지에 따라 다른 컨트롤(apply_to)을 반환할 수 있다.
    ///
    /// 반환: JSON `{"ok":true,"pageIndex":N,"sectionIdx":N,"isHeader":bool,"applyTo":N}`
    /// 또는 더 이상 이동할 페이지가 없으면 `{"ok":false}`
    pub fn navigate_header_footer_by_page_native(
        &self,
        current_page: u32,
        is_header: bool,
        direction: i32, // -1 또는 +1
    ) -> Result<String, HwpError> {
        let total = self.page_count();
        if total == 0 {
            return Ok("{\"ok\":false}".to_string());
        }

        // 현재 페이지의 머리말/꼬리말 참조 (동일 컨트롤 스킵용)
        let current_ref = if let Ok((pc, _, _)) = self.find_page(current_page) {
            if is_header {
                pc.active_header.clone()
            } else {
                pc.active_footer.clone()
            }
        } else {
            None
        };

        let mut page = current_page as i64 + direction as i64;
        while page >= 0 && page < total as i64 {
            let p = page as u32;
            if let Ok((pc, _, _)) = self.find_page(p) {
                let hf_ref = if is_header {
                    &pc.active_header
                } else {
                    &pc.active_footer
                };
                if let Some(hf) = hf_ref {
                    // 다른 컨트롤이거나, 같은 컨트롤이라도 다른 페이지이면 이동 대상
                    let is_different_control = match &current_ref {
                        Some(cr) => {
                            cr.para_index != hf.para_index
                                || cr.control_index != hf.control_index
                                || cr.source_section_index != hf.source_section_index
                        }
                        None => true,
                    };
                    // 같은 컨트롤이라도 페이지가 달라지면 이동
                    let section_idx = hf.source_section_index;
                    let para_idx = hf.para_index;
                    let ctrl_idx = hf.control_index;

                    // apply_to 추출
                    let apply_to = if let Some(section) = self.document.sections.get(section_idx) {
                        if let Some(para) = section.paragraphs.get(para_idx) {
                            if let Some(ctrl) = para.controls.get(ctrl_idx) {
                                match ctrl {
                                    Control::Header(h) => header_footer_apply_to_u8(h.apply_to),
                                    Control::Footer(f) => header_footer_apply_to_u8(f.apply_to),
                                    _ => 0,
                                }
                            } else {
                                0
                            }
                        } else {
                            0
                        }
                    } else {
                        0
                    };

                    return Ok(format!(
                        "{{\"ok\":true,\"pageIndex\":{},\"sectionIdx\":{},\"isHeader\":{},\"applyTo\":{}}}",
                        p, section_idx, is_header, apply_to
                    ));
                }
            }
            page += direction as i64;
        }

        Ok("{\"ok\":false}".to_string())
    }

    /// 특정 페이지의 머리말/꼬리말 감추기를 토글한다.
    ///
    /// 반환: JSON `{"ok":true,"hidden":bool}`
    pub fn toggle_hide_header_footer_native(
        &mut self,
        page_num: u32,
        is_header: bool,
    ) -> Result<String, HwpError> {
        let total = self.page_count();
        if page_num >= total {
            return Err(HwpError::RenderError(format!(
                "페이지 인덱스 {} 범위 초과 (총 {}개)",
                page_num, total
            )));
        }
        let key = (page_num, is_header);
        let hidden = if self.hidden_header_footer.contains(&key) {
            self.hidden_header_footer.remove(&key);
            false
        } else {
            self.hidden_header_footer.insert(key);
            true
        };
        // 숨김 상태는 page tree와 두 파생 표현 모두에 반영되므로 한 페이지의
        // 캐시 계보를 원자적으로 무효화한다.
        self.invalidate_page_tree_cache_page(page_num);
        Ok(format!("{{\"ok\":true,\"hidden\":{}}}", hidden))
    }

    /// 머리말/꼬리말 문단 리플로우
    pub(crate) fn reflow_hf_paragraph(
        &mut self,
        section_idx: usize,
        is_header: bool,
        apply_to: u8,
        hf_para_idx: usize,
    ) {
        use crate::renderer::hwpunit_to_px;

        // 머리말/꼬리말 영역 폭 = 페이지 텍스트 영역 폭
        let available_width = {
            let section = &self.document.sections[section_idx];
            let page_def = &section.section_def.page_def;
            let text_width =
                page_def.width as i32 - page_def.margin_left as i32 - page_def.margin_right as i32;
            hwpunit_to_px(text_width, self.dpi)
        };

        // [#4324] 호출부(apply_para_format_in_hf_native)가 이 직전에
        // find_or_create_para_shape 로 새 para_shape 를 만들 수 있다. 캐시된
        // self.styles 는 직전 rebuild_section 스냅샷이라 그 새 id 를 포함하지 않을 수
        // 있어(margin_left/right 가 0.0 으로 폴백) 여백을 무시한 폭으로 리플로우해버린다.
        // formatting.rs 의 reflow_cell_paragraph(twin, text_editing.rs)와 동일하게
        // doc_info 에서 매번 새로 resolve 한다.
        let styles = self.resolve_render_styles();

        // 문단 여백 적용
        let para_shape_id =
            match self.get_hf_paragraph_ref(section_idx, is_header, apply_to, hf_para_idx) {
                Some(p) => p.para_shape_id,
                None => return,
            };
        let para_style = styles.para_styles.get(para_shape_id as usize);
        let margin_left = para_style.map(|s| s.margin_left).unwrap_or(0.0);
        let margin_right = para_style.map(|s| s.margin_right).unwrap_or(0.0);
        let final_width = (available_width - margin_left - margin_right).max(0.0);

        // 가변 참조로 리플로우 실행
        let apply = header_footer_apply_from_u8(apply_to);
        if let Some((pi, ci)) = self.find_header_footer_control(section_idx, is_header, apply) {
            let ctrl = &mut self.document.sections[section_idx].paragraphs[pi].controls[ci];
            let paragraphs = match ctrl {
                Control::Header(h) => &mut h.paragraphs,
                Control::Footer(f) => &mut f.paragraphs,
                _ => return,
            };
            if let Some(para) = paragraphs.get_mut(hf_para_idx) {
                // 머리말/꼬리말 본문 상자 — 본문 열과 별개 흐름이므로 미스냅.
                reflow_line_segs(
                    para,
                    ParagraphBox::content_width_px(final_width, self.dpi),
                    &styles,
                    self.dpi,
                );
            }
        }
    }

    /// 머리말/꼬리말 문단의 문단 속성을 조회한다.
    pub fn get_para_properties_in_hf_native(
        &self,
        section_idx: usize,
        is_header: bool,
        apply_to: u8,
        hf_para_idx: usize,
    ) -> Result<String, HwpError> {
        let para = self
            .get_hf_paragraph_ref(section_idx, is_header, apply_to, hf_para_idx)
            .ok_or_else(|| {
                HwpError::RenderError("머리말/꼬리말 문단을 찾을 수 없음".to_string())
            })?;
        Ok(self.build_para_properties_json(para.para_shape_id, section_idx))
    }

    /// 머리말/꼬리말 문단에 문단 서식을 적용한다.
    pub fn apply_para_format_in_hf_native(
        &mut self,
        section_idx: usize,
        is_header: bool,
        apply_to: u8,
        hf_para_idx: usize,
        props_json: &str,
    ) -> Result<String, HwpError> {
        // 현재 para_shape_id 조회
        let base_id = {
            let para = self
                .get_hf_paragraph_ref(section_idx, is_header, apply_to, hf_para_idx)
                .ok_or_else(|| {
                    HwpError::RenderError("머리말/꼬리말 문단을 찾을 수 없음".to_string())
                })?;
            para.para_shape_id
        };

        let mut mods = parse_para_shape_mods(props_json);

        // 탭 설정 변경 처리
        if json_has_tab_keys(props_json) {
            let base_tab_def_id = self
                .document
                .doc_info
                .para_shapes
                .get(base_id as usize)
                .map(|ps| ps.tab_def_id)
                .unwrap_or(0);
            let new_td = build_tab_def_from_json(
                props_json,
                base_tab_def_id,
                &self.document.doc_info.tab_defs,
            );
            let new_tab_id = self.document.find_or_create_tab_def(new_td);
            mods.tab_def_id = Some(new_tab_id);
        }

        // 테두리/배경 변경 처리
        if json_has_border_keys(props_json) {
            let bf_id = self.create_border_fill_from_json(props_json);
            mods.border_fill_id = Some(bf_id);
        }
        if let Some(arr) = parse_json_i16_array(props_json, "borderSpacing", 4) {
            mods.border_spacing = Some([arr[0], arr[1], arr[2], arr[3]]);
        }

        let new_id = self.document.find_or_create_para_shape(base_id, &mods);
        let (old_indent, new_indent) = self.para_shape_indents(base_id, new_id);

        // para_shape_id 갱신
        {
            let para = self.get_hf_paragraph_mut(section_idx, is_header, apply_to, hf_para_idx)?;
            para.para_shape_id = new_id;
            restamp_indentation(&mut para.line_segs, old_indent, new_indent);
        }

        // 줄바꿈에 영향을 주는 변경 시 LineSeg 재계산.
        //
        // [#4324] formatting.rs의 apply_para_format_native/apply_para_format_in_cell_native
        // 와 동일한 게이트 결함 — 줄간격만 보고 여백/들여쓰기/줄나눔 단위를 놓쳤다.
        // para_shape_mods_affect_text_flow(formatting.rs:16 부근)로 판정을 통일한다.
        if para_shape_mods_affect_text_flow(&mods) {
            self.reflow_hf_paragraph(section_idx, is_header, apply_to, hf_para_idx);
        }

        self.document.sections[section_idx].raw_stream = None;
        self.rebuild_section(section_idx);
        self.event_log.push(DocumentEvent::ParaFormatChanged {
            section: section_idx,
            para: 0,
        });
        Ok("{\"ok\":true}".to_string())
    }

    /// 머리말/꼬리말 문단에 필드 마커를 삽입한다.
    /// field_type: 1=쪽번호(\u{0015}), 2=총쪽수(\u{0016}), 3=파일이름(\u{0017})
    pub fn insert_field_in_hf_native(
        &mut self,
        section_idx: usize,
        is_header: bool,
        apply_to: u8,
        hf_para_idx: usize,
        char_offset: usize,
        field_type: u8,
    ) -> Result<String, HwpError> {
        let marker = match field_type {
            1 => "\u{0015}", // 현재 쪽번호
            2 => "\u{0016}", // 총 쪽수
            3 => "\u{0017}", // 파일 이름
            _ => {
                return Err(HwpError::RenderError(format!(
                    "알 수 없는 필드 타입: {}",
                    field_type
                )))
            }
        };

        let hf_para = self.get_hf_paragraph_mut(section_idx, is_header, apply_to, hf_para_idx)?;
        // 반환·이벤트는 실제로 삽입된 위치를 쓴다 — 요청 값과 다를 수 있다.
        let inserted_at = hf_para.insert_text_at(char_offset, marker);

        self.reflow_hf_paragraph(section_idx, is_header, apply_to, hf_para_idx);

        self.document.sections[section_idx].raw_stream = None;
        self.mark_section_dirty(section_idx);
        self.paginate_if_needed();

        let new_offset = inserted_at + 1;
        self.event_log
            .push(DocumentEvent::HeaderFooterTextReplaced {
                section: section_idx,
                is_header,
                apply_to,
                start_para: hf_para_idx,
                start_offset: inserted_at,
                end_para: hf_para_idx,
                end_offset: inserted_at,
                inserted_end_para: hf_para_idx,
                inserted_end_offset: new_offset,
            });
        Ok(super::super::helpers::json_ok_with(&format!(
            "\"charOffset\":{},\"insertedAt\":{},\"insertedLength\":1",
            new_offset, inserted_at
        )))
    }

    /// 머리말/꼬리말 마당(템플릿)을 적용한다.
    ///
    /// template_id:
    /// - 0: 빈 머리말/꼬리말
    /// - 1: 왼쪽 쪽번호 (기본)
    /// - 2: 가운데 쪽번호 (기본)
    /// - 3: 오른쪽 쪽번호 (기본)
    /// - 4: 쪽번호(왼)+파일이름(오) (기본)
    /// - 5: 파일이름(왼)+쪽번호(오) (기본)
    /// - 6~10: 위 1~5와 동일 배치, 볼드+밑줄 스타일
    pub fn apply_hf_template_native(
        &mut self,
        section_idx: usize,
        is_header: bool,
        apply_to: u8,
        template_id: u8,
    ) -> Result<String, HwpError> {
        if section_idx >= self.document.sections.len() {
            return Err(HwpError::RenderError(format!(
                "구역 인덱스 {} 범위 초과",
                section_idx
            )));
        }
        if template_id > 10 {
            return Err(HwpError::RenderError(format!(
                "알 수 없는 템플릿 ID: {}",
                template_id
            )));
        }

        let apply = header_footer_apply_from_u8(apply_to);

        // 1) 기존 HF가 있으면 삭제
        if self
            .find_header_footer_control(section_idx, is_header, apply)
            .is_some()
        {
            self.delete_header_footer_native(section_idx, is_header, apply_to)?;
        }

        // 2) 새 HF 생성 (빈 문단 1개)
        self.create_header_footer_native(section_idx, is_header, apply_to)?;

        // 빈 템플릿이면 여기서 종료
        if template_id == 0 {
            self.mark_section_dirty(section_idx);
            self.paginate_if_needed();
            return Ok("{\"ok\":true}".to_string());
        }

        // 3) 배치/스타일 결정
        let layout = if template_id <= 5 {
            template_id
        } else {
            template_id - 5
        };
        let styled = template_id > 5; // bold + underline

        // 4) 텍스트 내용 결정
        let text = match layout {
            1 => "\u{0015}".to_string(),           // 왼쪽 쪽번호
            2 => "\u{0015}".to_string(),           // 가운데 쪽번호
            3 => "\u{0015}".to_string(),           // 오른쪽 쪽번호
            4 => "\u{0015}\t\u{0017}".to_string(), // 쪽번호(왼) + 탭 + 파일이름(오)
            5 => "\u{0017}\t\u{0015}".to_string(), // 파일이름(왼) + 탭 + 쪽번호(오)
            _ => String::new(),
        };

        // 5) 정렬 결정
        use crate::model::style::{
            Alignment, CharShapeMods, ParaShapeMods, TabDef, TabItem, UnderlineType,
        };

        let alignment = match layout {
            1 => Alignment::Left,
            2 => Alignment::Center,
            3 => Alignment::Right,
            4 | 5 => Alignment::Left, // 탭으로 오른쪽 배치
            _ => Alignment::Left,
        };

        // 6) 텍스트 삽입 — 탭은 스트림 8칸이다. `insert_text_at` 이 그 폭으로 char_offsets 와
        //    char_count 를 함께 맞춘다(바이트 위치를 쓰면 탭 뒤 글자가 7칸 당겨진다).
        {
            let hf_para = self.get_hf_paragraph_mut(section_idx, is_header, apply_to, 0)?;
            hf_para.insert_text_at(0, &text);
        }

        // 7) 문단 정렬 적용
        let base_para_id = {
            let para = self
                .get_hf_paragraph_ref(section_idx, is_header, apply_to, 0)
                .unwrap();
            para.para_shape_id
        };
        let mut para_mods = ParaShapeMods::default();
        para_mods.alignment = Some(alignment);

        // 8) 좌+우 배치 템플릿: 오른쪽 정렬 탭 추가
        if layout == 4 || layout == 5 {
            let section = &self.document.sections[section_idx];
            let page_def = &section.section_def.page_def;
            let text_width =
                page_def.width as i32 - page_def.margin_left as i32 - page_def.margin_right as i32;

            let new_td = TabDef {
                raw_data: None,
                attr: 0,
                tabs: vec![TabItem {
                    position: text_width as u32,
                    tab_type: 1, // 오른쪽 정렬 탭
                    fill_type: 0,
                }],
                auto_tab_left: false,
                auto_tab_right: false,
            };
            let tab_id = self.document.find_or_create_tab_def(new_td);
            para_mods.tab_def_id = Some(tab_id);
        }

        let new_para_id = self
            .document
            .find_or_create_para_shape(base_para_id, &para_mods);
        {
            let hf_para = self.get_hf_paragraph_mut(section_idx, is_header, apply_to, 0)?;
            hf_para.para_shape_id = new_para_id;
        }

        // 9) 볼드+밑줄 스타일 적용
        if styled {
            let base_char_id = {
                let para = self
                    .get_hf_paragraph_ref(section_idx, is_header, apply_to, 0)
                    .unwrap();
                para.char_shapes
                    .first()
                    .map(|cs| cs.char_shape_id)
                    .unwrap_or(0)
            };
            let mut char_mods = CharShapeMods::default();
            char_mods.bold = Some(true);
            char_mods.underline_type = Some(UnderlineType::Bottom);
            let new_char_id = self
                .document
                .find_or_create_char_shape(base_char_id, &char_mods);

            // 새 머리말 문단(`Paragraph::default()`)은 글자 모양 목록이 비어 있다. 기존 항목만
            // 바꾸면 어느 글자에도 붙지 않으므로 문단 전체를 새 모양 하나로 둔다.
            self.get_hf_paragraph_mut(section_idx, is_header, apply_to, 0)?
                .set_single_char_shape(new_char_id);
        }

        // 10) 리플로우 + 스타일 재해소 + 재페이지네이션
        self.reflow_hf_paragraph(section_idx, is_header, apply_to, 0);
        self.document.sections[section_idx].raw_stream = None;
        self.rebuild_section(section_idx);

        Ok("{\"ok\":true}".to_string())
    }
}

/// 머리말/꼬리말 필드 마커(쪽 번호 U+0015 · 전체 쪽수 U+0016 · 파일 이름 U+0017).
fn is_hf_field_marker(ch: char) -> bool {
    matches!(ch, '\u{0015}'..='\u{0017}')
}

/// 저장할 문서에 머리말/꼬리말 필드 마커가 있는지 — 없으면 저장 사본을 만들 필요가 없다.
pub(crate) fn has_header_footer_field_markers(document: &crate::model::document::Document) -> bool {
    document
        .sections
        .iter()
        .flat_map(|section| section.paragraphs.iter())
        .flat_map(|para| para.controls.iter())
        .flat_map(|ctrl| match ctrl {
            Control::Header(header) => header.paragraphs.as_slice(),
            Control::Footer(footer) => footer.paragraphs.as_slice(),
            _ => &[],
        })
        .any(|para| para.text.chars().any(is_hf_field_marker))
}

/// 저장 사본의 머리말/꼬리말 필드 마커를 한컴이 만든 머리말과 같은 컨트롤로 바꾼다.
///
/// 편집 중에는 필드가 마커 한 글자다 — 되돌리기(#3212)·캐럿(#3216)·파일 이름 갱신(#1144)이
/// 모두 그 한 글자에 기대므로 편집 문서는 그대로 두고 저장 사본에서만 바꾼다. 마커를 그대로
/// 내보내면 HWP 에는 짝 없는 제어 코드 유닛이 남아 문단이 깨지고, HWPX 에서는 사라진다.
///
/// - 쪽 번호·전체 쪽수 → 자동 번호(`atno`). 파서가 만드는 꼴대로 자리표 공백 한 글자에
///   컨트롤 몫 8칸을 준다.
/// - 파일 이름 → 파일 경로 필드(`%pat`, 명령 `$F`). 필드 글자는 지금 파일 이름이다 —
///   한글도 저장할 때 그 값으로 갱신한다. HWPX 매개변수는 한글 2024 가 만든 머리말
///   (`Prop=8`·`Command=$F`·`Format=$F`)을 따른다. HWP5 에는 그 자리가 없다(#4396).
pub(crate) fn lower_header_footer_field_markers(
    document: &mut crate::model::document::Document,
    file_name: &str,
    hwpx: bool,
) {
    if !has_header_footer_field_markers(document) {
        return;
    }
    let mut max_field_id = 0;
    for para in document
        .sections
        .iter()
        .flat_map(|section| section.paragraphs.iter())
    {
        crate::document_core::queries::field_query::collect_max_field_id(para, &mut max_field_id);
    }
    let mut next_field_id = max_field_id.saturating_add(1);

    let hf_paragraphs = document
        .sections
        .iter_mut()
        .flat_map(|section| section.paragraphs.iter_mut())
        .flat_map(|para| para.controls.iter_mut())
        .flat_map(|ctrl| match ctrl {
            Control::Header(header) => header.paragraphs.iter_mut(),
            Control::Footer(footer) => footer.paragraphs.iter_mut(),
            _ => Default::default(),
        });
    for para in hf_paragraphs {
        let markers: Vec<(usize, char)> = para
            .text
            .chars()
            .enumerate()
            .filter(|(_, ch)| is_hf_field_marker(*ch))
            .collect();
        if markers.is_empty() {
            continue;
        }
        // 새로 만든 머리말 문단(`Paragraph::default()`)은 문단 끝 1칸 없이 센다. HWPX 저장기는
        // char_count 에서 컨트롤 슬롯 수를 추정하므로(문단 끝 포함 전제) 그 칸을 채운다.
        // 텍스트 뒤에 남는 것은 8칸 슬롯뿐이라 나머지가 0 이면 문단 끝이 빠진 것이다.
        let text_end = para
            .char_offsets
            .last()
            .zip(para.text.chars().last())
            .map_or(0, |(offset, ch)| offset + Paragraph::char_stream_len(ch));
        if para.char_count.saturating_sub(text_end) % 8 == 0 {
            para.char_count += 1;
        }
        // 뒤 마커부터 바꿔야 앞 마커의 글자 위치가 그대로다.
        for (idx, marker) in markers.into_iter().rev() {
            // 마커 앞(같은 자리 포함)에 놓인 컨트롤 수가 새 컨트롤의 차례다.
            let ctrl_idx = para
                .control_text_positions()
                .into_iter()
                .filter(|pos| *pos <= idx)
                .count();
            for range in &mut para.field_ranges {
                if range.control_idx >= ctrl_idx {
                    range.control_idx += 1;
                }
            }
            let ctrl = if marker == '\u{0017}' {
                let end = insert_field_text(para, idx, file_name);
                para.field_ranges.push(crate::model::paragraph::FieldRange {
                    start_char_idx: idx,
                    end_char_idx: end,
                    control_idx: ctrl_idx,
                    ..Default::default()
                });
                let field = path_field(next_field_id, hwpx);
                next_field_id = next_field_id.saturating_add(1);
                Control::Field(field)
            } else {
                insert_auto_number_placeholder(para, idx);
                Control::AutoNumber(crate::model::control::AutoNumber {
                    number_type: if marker == '\u{0015}' {
                        crate::model::control::AutoNumberType::Page
                    } else {
                        crate::model::control::AutoNumberType::TotalPage
                    },
                    number: 1,
                    assigned_number: 1,
                    ..Default::default()
                })
            };
            para.align_ctrl_data_records();
            para.controls.insert(ctrl_idx, ctrl);
            para.ctrl_data_records.insert(ctrl_idx, None);
        }
    }
}

/// `idx` 의 마커를 자동 번호 자리표 공백으로 바꾸고 컨트롤 몫 8칸을 채운다 — 파서가
/// `0x0012` 를 읽어 만드는 꼴(자리표 한 글자, 다음 글자는 8칸 뒤)과 같다.
///
/// 마커와 공백은 둘 다 1바이트·1유닛이라 제자리에서 바꾼다. 지우고 다시 넣으면 바로 뒤에
/// 이미 바꾼 파일 이름 필드의 시작 슬롯이 그 자리에 붙고, `insert_text_at` 은 필드 시작
/// 앞을 가리지 않아 공백이 필드 안으로 들어간다.
fn insert_auto_number_placeholder(para: &mut Paragraph, idx: usize) {
    const EXTRA: u32 = 7;
    let Some((byte, _)) = para.text.char_indices().nth(idx) else {
        return;
    };
    para.text.replace_range(byte..byte + 1, " ");
    let slot = para.char_offsets[idx];
    for offset in &mut para.char_offsets[idx + 1..] {
        *offset += EXTRA;
    }
    para.shift_position_metadata_for_stream_insertion(slot + 1, EXTRA);
    para.char_count += EXTRA;
}

/// `idx` 의 마커를 필드 글자로 바꾸고 앞뒤에 필드 시작·끝 슬롯(각 8칸)을 둔다. 필드 끝
/// 글자 위치를 돌려준다.
///
/// 글자를 마커 앞에 넣고 나서 마커를 지운다 — 그래야 글자가 마커 자리에 붙는다. 먼저
/// 지우면 바로 뒤 파일 이름 필드의 시작 슬롯이 그 자리에 붙어 글자가 그 필드 안으로
/// 들어간다.
fn insert_field_text(para: &mut Paragraph, idx: usize, text: &str) -> usize {
    let at = para.insert_text_at(idx, text);
    let end = at + text.chars().count();
    para.shift_for_control_slot_insert(end);
    para.shift_for_control_slot_insert(at);
    para.char_count += 16;
    para.delete_text_at(end, 1);
    end
}

fn path_field(field_id: u32, hwpx: bool) -> crate::model::control::Field {
    use crate::model::control::{Field, FieldType, Parameter, ParameterList};
    const COMMAND: &str = "$F";
    let string_param = |name: &str| Parameter::String {
        name: Some(name.to_string()),
        value: COMMAND.to_string(),
        preserve_space: false,
    };
    Field {
        field_type: FieldType::Path,
        command: COMMAND.to_string(),
        field_id,
        ctrl_id: crate::parser::tags::FIELD_PATH,
        parameters: if hwpx {
            ParameterList {
                name: Some(String::new()),
                items: vec![
                    Parameter::Integer {
                        name: Some("Prop".to_string()),
                        value: 8,
                    },
                    string_param("Command"),
                    string_param("Format"),
                ],
            }
        } else {
            ParameterList::default()
        },
        ..Default::default()
    }
}

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

    fn make_test_core() -> DocumentCore {
        use crate::model::document::{Document, Section, SectionDef};
        use crate::model::page::PageDef;
        let mut doc = Document::default();
        let section = Section {
            section_def: SectionDef {
                page_def: PageDef {
                    width: 59528,  // A4 폭
                    height: 84188, // A4 높이
                    margin_left: 8504,
                    margin_right: 8504,
                    margin_top: 5668,
                    margin_bottom: 4252,
                    margin_header: 4252,
                    margin_footer: 4252,
                    ..Default::default()
                },
                ..Default::default()
            },
            paragraphs: vec![Paragraph::default()],
            trailing_lists: None,
            raw_stream: None,
            raw_provenance: None,
        };
        doc.sections.push(section);
        let mut core = DocumentCore::new_empty();
        core.document = doc;
        core
    }

    #[test]
    fn test_create_and_get_header() {
        let mut core = make_test_core();

        // 머리말이 없는지 확인
        let result = core.get_header_footer_native(0, true, 0).unwrap();
        assert!(result.contains("\"exists\":false"));

        // 머리말 생성
        let result = core.create_header_footer_native(0, true, 0).unwrap();
        assert!(result.contains("\"ok\":true"));
        assert!(result.contains("\"kind\":\"header\""));

        // 머리말이 있는지 확인
        let result = core.get_header_footer_native(0, true, 0).unwrap();
        assert!(result.contains("\"exists\":true"));
        assert!(result.contains("\"paraCount\":1"));
    }

    #[test]
    fn test_create_and_get_footer() {
        let mut core = make_test_core();

        let result = core.create_header_footer_native(0, false, 0).unwrap();
        assert!(result.contains("\"kind\":\"footer\""));

        let result = core.get_header_footer_native(0, false, 0).unwrap();
        assert!(result.contains("\"exists\":true"));
    }

    #[test]
    fn test_duplicate_create_fails() {
        let mut core = make_test_core();
        core.create_header_footer_native(0, true, 0).unwrap();
        let result = core.create_header_footer_native(0, true, 0);
        assert!(result.is_err());
    }

    #[test]
    fn test_insert_text_in_header() {
        let mut core = make_test_core();
        core.create_header_footer_native(0, true, 0).unwrap();

        let result = core
            .insert_text_in_header_footer_native(0, true, 0, 0, 0, "Hello")
            .unwrap();
        assert!(result.contains("\"charOffset\":5"));

        let result = core.get_header_footer_native(0, true, 0).unwrap();
        assert!(result.contains("Hello"));

        let info = core
            .get_header_footer_para_info_native(0, true, 0, 0)
            .unwrap();
        let value: serde_json::Value = serde_json::from_str(&info).unwrap();
        assert_eq!(value["charCount"], 5);
        assert_eq!(value["text"], "Hello");
    }

    /// 필드 삽입의 반환 오프셋은 실제로 삽입된 자리를 가리킨다.
    ///
    /// 반환값이 요청 값을 그대로 되돌려 주면 undo 가 존재하지 않는 자리를 지우려 해
    /// 무언 no-op 이 된다 (Task #3216).
    #[test]
    fn field_insert_reports_where_the_marker_actually_landed() {
        let mut core = make_test_core();
        core.create_header_footer_native(0, true, 0).unwrap();
        core.insert_field_in_hf_native(0, true, 0, 0, 0, 3)
            .expect("file-name field");

        let result = core
            .insert_field_in_hf_native(0, true, 0, 0, 1, 1)
            .expect("page-number field after the file-name marker");
        assert!(result.contains("\"charOffset\":2"), "{result}");
        assert!(result.contains("\"insertedAt\":1"), "{result}");
        assert!(result.contains("\"insertedLength\":1"), "{result}");

        let info = core
            .get_header_footer_para_info_native(0, true, 0, 0)
            .unwrap();
        assert!(info.contains("\"charCount\":2"), "{info}");
    }

    /// 커서 좌표와 실제 텍스트 삽입 좌표가 다를 때에도 history가 지울 위치를
    /// 정확히 받는다. trailing inline control 뒤의 위치는 cursor에서 유효하지만
    /// 모델 텍스트에는 없으므로 `charOffset - 요청 offset`으로 길이를 계산하면 안 된다.
    #[test]
    fn field_insert_reports_actual_offset_separately_from_cursor_offset() {
        let mut core = make_test_core();
        core.create_header_footer_native(0, true, 0).unwrap();
        {
            let para = core.get_hf_paragraph_mut(0, true, 0, 0).unwrap();
            para.text = "A".to_string();
            para.char_offsets = vec![0];
            para.controls.push(Control::Footnote(Box::default()));
        }

        // 텍스트 1자 뒤의 inline control까지 지나간 커서 좌표. 실제 marker는
        // text index 1에 들어가지만, 커서는 여전히 control 뒤 위치 2를 가리킨다.
        let result = core
            .insert_field_in_hf_native(0, true, 0, 0, 2, 1)
            .expect("field after trailing inline control");
        assert!(result.contains("\"charOffset\":2"), "{result}");
        assert!(result.contains("\"insertedAt\":1"), "{result}");
        assert!(result.contains("\"insertedLength\":1"), "{result}");

        core.delete_text_in_header_footer_native(0, true, 0, 0, 1, 1)
            .expect("undo removes the marker at insertedAt");
        let content = core.get_header_footer_native(0, true, 0).unwrap();
        assert!(content.contains("\"text\":\"A\""), "{content}");
    }

    #[test]
    fn test_delete_text_in_header() {
        let mut core = make_test_core();
        core.create_header_footer_native(0, true, 0).unwrap();
        core.insert_text_in_header_footer_native(0, true, 0, 0, 0, "Hello World")
            .unwrap();

        let result = core
            .delete_text_in_header_footer_native(0, true, 0, 0, 5, 6)
            .unwrap();
        assert!(result.contains("\"charOffset\":5"));

        let result = core.get_header_footer_native(0, true, 0).unwrap();
        assert!(result.contains("Hello"));
    }

    #[test]
    fn test_split_merge_paragraph_in_header() {
        let mut core = make_test_core();
        core.create_header_footer_native(0, true, 0).unwrap();
        core.insert_text_in_header_footer_native(0, true, 0, 0, 0, "HelloWorld")
            .unwrap();

        // 문단 분할
        let result = core
            .split_paragraph_in_header_footer_native(0, true, 0, 0, 5, None)
            .unwrap();
        assert!(result.contains("\"hfParaIndex\":1"));
        assert!(result.contains("\"charOffset\":0"));

        // 문단 수 확인
        let result = core
            .get_header_footer_para_info_native(0, true, 0, 0)
            .unwrap();
        assert!(result.contains("\"paraCount\":2"));

        // 문단 병합
        let result = core
            .merge_paragraph_in_header_footer_native(0, true, 0, 1)
            .unwrap();
        assert!(result.contains("\"hfParaIndex\":0"));
        assert!(result.contains("\"charOffset\":5"));

        // 문단 수 확인
        let result = core
            .get_header_footer_para_info_native(0, true, 0, 0)
            .unwrap();
        assert!(result.contains("\"paraCount\":1"));
    }

    /// 머리말 문단 병합의 undo 가 사라진 문단의 스코프 메타데이터를 되돌리는지 (Task #2342).
    #[test]
    fn merge_paragraph_in_header_undo_restores_removed_paragraph_meta() {
        use crate::document_core::helpers::removed_para_meta_of;
        use crate::model::paragraph::NumberingRestart;

        let mut core = make_test_core();
        core.create_header_footer_native(0, true, 0).unwrap();
        core.insert_text_in_header_footer_native(0, true, 0, 0, 0, "HelloWorld")
            .unwrap();
        core.split_paragraph_in_header_footer_native(0, true, 0, 0, 5, None)
            .unwrap();

        let second = core.get_hf_paragraph_mut(0, true, 0, 1).unwrap();
        second.para_shape_id = 20;
        second.style_id = 5;
        second.numbering_restart = Some(NumberingRestart::ContinuePrevious);
        second.raw_header_extra = vec![0, 0, 0, 0, 0, 0, 0xBB, 0xBB, 0xBB, 0xBB];

        let merged = core
            .merge_paragraph_in_header_footer_native(0, true, 0, 1)
            .unwrap();
        let meta = removed_para_meta_of(&merged);
        core.split_paragraph_in_header_footer_native(0, true, 0, 0, 5, Some(meta))
            .unwrap();

        let restored = core.get_hf_paragraph_mut(0, true, 0, 1).unwrap();
        assert_eq!(restored.text, "World");
        assert_eq!(restored.para_shape_id, 20);
        assert_eq!(restored.style_id, 5);
        assert_eq!(
            restored.numbering_restart,
            Some(NumberingRestart::ContinuePrevious)
        );
        assert_eq!(
            restored.raw_header_extra,
            vec![0, 0, 0, 0, 0, 0, 0xBB, 0xBB, 0xBB, 0xBB]
        );
    }

    #[test]
    fn test_delete_header_footer() {
        let mut core = make_test_core();
        core.create_header_footer_native(0, true, 0).unwrap();
        core.insert_text_in_header_footer_native(0, true, 0, 0, 0, "머리말 텍스트")
            .unwrap();

        let result = core.delete_header_footer_native(0, true, 0).unwrap();
        assert!(result.contains("\"ok\":true"));

        let result = core.get_header_footer_native(0, true, 0).unwrap();
        assert!(result.contains("\"exists\":false"));
    }

    #[test]
    fn test_delete_nonexistent_fails() {
        let mut core = make_test_core();
        let result = core.delete_header_footer_native(0, true, 0);
        assert!(result.is_err());
    }

    #[test]
    fn test_get_header_footer_list() {
        let mut core = make_test_core();
        core.create_header_footer_native(0, true, 0).unwrap();
        core.create_header_footer_native(0, false, 0).unwrap();

        let result = core.get_header_footer_list_native(0, true, 0).unwrap();
        assert!(result.contains("\"currentIndex\":0"));
        assert!(result.contains("머리말(양 쪽)"));
        assert!(result.contains("꼬리말(양 쪽)"));

        let result = core.get_header_footer_list_native(0, false, 0).unwrap();
        assert!(result.contains("\"currentIndex\":1"));
    }

    #[test]
    fn test_odd_even_header() {
        let mut core = make_test_core();

        // 양쪽 머리말 생성
        core.create_header_footer_native(0, true, 0).unwrap();
        // 홀수 머리말 생성
        core.create_header_footer_native(0, true, 2).unwrap();

        // 양쪽만 조회
        let result = core.get_header_footer_native(0, true, 0).unwrap();
        assert!(result.contains("\"exists\":true"));
        assert!(result.contains("양 쪽"));

        // 홀수만 조회
        let result = core.get_header_footer_native(0, true, 2).unwrap();
        assert!(result.contains("\"exists\":true"));
        assert!(result.contains("홀수 쪽"));

        // 짝수는 없음
        let result = core.get_header_footer_native(0, true, 1).unwrap();
        assert!(result.contains("\"exists\":false"));
    }

    #[test]
    #[ignore] // 진단용 테스트 — 로컬 파일 의존
    fn test_p222_header_structure() {
        let data = std::fs::read("samples/p222.hwp").expect("samples/p222.hwp 파일 읽기 실패");
        let mut core = DocumentCore::from_bytes(&data).expect("문서 로드 실패");

        let num_sections = core.document.sections.len();
        eprintln!("=== p222.hwp 머리말 구조 진단 ===");
        eprintln!("구역 수: {}", num_sections);
        eprintln!("전체 페이지 수: {}", core.page_count());

        for si in 0..num_sections {
            let section = &core.document.sections[si];
            eprintln!(
                "\n--- 구역 {} (문단 {}개) ---",
                si,
                section.paragraphs.len()
            );
            for (pi, para) in section.paragraphs.iter().enumerate() {
                for (ci, ctrl) in para.controls.iter().enumerate() {
                    match ctrl {
                        Control::Header(h) => {
                            eprintln!(
                                "  머리말: para[{}].ctrl[{}] apply_to={:?} 문단수={} 텍스트=[{}]",
                                pi,
                                ci,
                                h.apply_to,
                                h.paragraphs.len(),
                                h.paragraphs
                                    .iter()
                                    .map(|p| p.text.clone())
                                    .collect::<Vec<_>>()
                                    .join("|")
                            );
                        }
                        Control::Footer(f) => {
                            eprintln!(
                                "  꼬리말: para[{}].ctrl[{}] apply_to={:?} 문단수={} 텍스트=[{}]",
                                pi,
                                ci,
                                f.apply_to,
                                f.paragraphs.len(),
                                f.paragraphs
                                    .iter()
                                    .map(|p| p.text.clone())
                                    .collect::<Vec<_>>()
                                    .join("|")
                            );
                        }
                        _ => {}
                    }
                }
            }
        }

        // 각 페이지의 active_header/footer 확인
        eprintln!("\n--- 페이지별 active header/footer ---");
        for page_num in 0..core.page_count() {
            if let Ok((pc, _, _)) = core.find_page(page_num) {
                let hdr = if let Some(ref h) = pc.active_header {
                    format!(
                        "sec={} para={} ctrl={}",
                        h.source_section_index, h.para_index, h.control_index
                    )
                } else {
                    "없음".to_string()
                };
                let ftr = if let Some(ref f) = pc.active_footer {
                    format!(
                        "sec={} para={} ctrl={}",
                        f.source_section_index, f.para_index, f.control_index
                    )
                } else {
                    "없음".to_string()
                };
                eprintln!("  페이지 {}: header=[{}] footer=[{}]", page_num, hdr, ftr);
            }
        }

        // 편집 시나리오: 7페이지(인덱스6), 8페이지(인덱스7) 머리말 구조 확인
        for apply_to_val in [0u8, 1, 2] {
            for sec_idx in 0..num_sections {
                let result = core
                    .get_header_footer_native(sec_idx, true, apply_to_val)
                    .unwrap();
                if result.contains("\"exists\":true") {
                    eprintln!(
                        "  get_header_footer(sec={}, is_header=true, apply_to={}) => {}",
                        sec_idx, apply_to_val, result
                    );
                }
            }
        }

        // 페이지 6(7p), 7(8p)의 hitTestHeaderFooter 시뮬레이션
        eprintln!("\n--- hitTestHeaderFooter + 텍스트 삽입 시뮬레이션 ---");
        for page in [6u32, 7] {
            // hitTestHeaderFooter 호출 (x=100, y=20 — 머리말 영역 가정)
            let hf_hit = core.hit_test_header_footer_native(page, 100.0, 20.0);
            eprintln!(
                "  페이지 {} hitTestHeaderFooter(100,20) => {:?}",
                page, hf_hit
            );

            // 더 넓은 영역으로도 시도 (y=50)
            let hf_hit2 = core.hit_test_header_footer_native(page, 200.0, 50.0);
            eprintln!(
                "  페이지 {} hitTestHeaderFooter(200,50) => {:?}",
                page, hf_hit2
            );
        }

        // 실제 페이지 정보에서 active_header의 apply_to 직접 확인
        eprintln!("\n--- active_header apply_to 직접 확인 ---");
        for page in [6u32, 7] {
            if let Ok((pc, _, _)) = core.find_page(page) {
                if let Some(ref hdr) = pc.active_header {
                    let sec = hdr.source_section_index;
                    let pi = hdr.para_index;
                    let ci = hdr.control_index;
                    if let Some(section) = core.document.sections.get(sec) {
                        if let Some(para) = section.paragraphs.get(pi) {
                            if let Some(ctrl) = para.controls.get(ci) {
                                let apply_to = match ctrl {
                                    Control::Header(h) => header_footer_apply_to_u8(h.apply_to),
                                    Control::Footer(f) => header_footer_apply_to_u8(f.apply_to),
                                    _ => 255,
                                };
                                eprintln!(
                                    "  페이지 {} → sec={}, para={}, ctrl={}, apply_to={}",
                                    page, sec, pi, ci, apply_to
                                );
                                // 이 apply_to로 텍스트 삽입 가능한지 확인
                                let result = core.insert_text_in_header_footer_native(
                                    sec, true, apply_to, 0, 0, "T",
                                );
                                eprintln!("    insert_text => {:?}", result);
                            }
                        }
                    }
                } else {
                    eprintln!("  페이지 {} → active_header 없음", page);
                }
            }
        }

        // 텍스트 삽입 테스트
        eprintln!("\n--- 텍스트 삽입 테스트 ---");
        for apply_to_val in [0u8, 1, 2] {
            for sec_idx in 0..num_sections {
                let result = core.insert_text_in_header_footer_native(
                    sec_idx,
                    true,
                    apply_to_val,
                    0,
                    0,
                    "X",
                );
                match result {
                    Ok(r) => eprintln!(
                        "  insert(sec={}, apply_to={}) => OK: {}",
                        sec_idx, apply_to_val, r
                    ),
                    Err(e) => eprintln!(
                        "  insert(sec={}, apply_to={}) => ERR: {}",
                        sec_idx, apply_to_val, e
                    ),
                }
            }
        }
    }

    /// 꼬리말 마당 적용 후 본문 텍스트 삽입이 정상 렌더링되는지 확인 (회귀 테스트)
    ///
    /// 머리말/꼬리말 컨트롤 추가 시 char_count가 갱신되지 않으면
    /// compose_lines에서 텍스트가 UTF-16 범위 밖으로 밀려 렌더링 누락됨.
    #[test]
    fn test_body_text_after_hf_template() {
        let mut core = DocumentCore::new_empty();
        core.create_blank_document_native().unwrap();

        let controls_before = core.document.sections[0].paragraphs[0].controls.len();

        // 꼬리말 마당 적용 (가운데 쪽번호)
        core.apply_hf_template_native(0, false, 0, 2).unwrap();

        // 컨트롤 추가 확인 + char_count 갱신 확인
        let para = &core.document.sections[0].paragraphs[0];
        assert_eq!(para.controls.len(), controls_before + 1);
        // char_count는 컨트롤 1개(8 UTF-16 code units) 만큼 증가해야 함
        assert!(
            para.char_count >= (para.controls.len() as u32) * 8,
            "char_count({})가 컨트롤 UTF-16 크기({})보다 작음",
            para.char_count,
            para.controls.len() * 8
        );

        // 본문 문단 0에 텍스트 삽입
        core.insert_text_native(0, 0, 0, "가나다").unwrap();

        // composed 데이터에 삽입된 텍스트가 포함되어야 함
        let all_text: String = core.composed[0][0]
            .lines
            .iter()
            .flat_map(|l| l.runs.iter().map(|r| r.text.as_str()))
            .collect();
        assert!(
            all_text.contains("가나다"),
            "HF 컨트롤 추가 후 본문 텍스트가 composed에 누락됨: {:?}",
            all_text
        );

        // 렌더 트리에도 포함되어야 함
        let tree = core.build_page_tree(0).unwrap();
        assert!(
            format!("{:?}", tree).contains("가나다"),
            "렌더 트리에 본문 텍스트 없음"
        );
    }

    /// [#3214] 머리말 생성이 `controls` 만 늘려 `ctrl_data_records` 와 어긋나면, 같은 문단에
    /// 각주를 삽입할 때 `ctrl_data_records.insert` 가 범위를 넘어 패닉한다.
    /// (WASM 에서는 패닉이 객체 borrow 를 오염시켜 이후 모든 호출이 실패한다.)
    #[test]
    fn issue3214_header_creation_keeps_ctrl_data_records_aligned() {
        let mut core = DocumentCore::new_empty();
        core.create_blank_document_native().unwrap();
        core.insert_text_native(0, 0, 0, "ab").unwrap();

        core.create_header_footer_native(0, true, 0).unwrap();

        let para = &core.document.sections[0].paragraphs[0];
        assert_eq!(
            para.controls.len(),
            para.ctrl_data_records.len(),
            "머리말 생성 후 controls/ctrl_data_records 길이가 어긋났다"
        );

        // 머리말 컨트롤 "뒤"(텍스트 끝)에 각주를 삽입해야 insert_idx == controls.len() 이 되어
        // ctrl_data_records(짧음)에 대한 범위 초과가 드러난다 — 수정 전에는 여기서 패닉했다.
        core.insert_footnote_native(0, 0, 2).unwrap();
        let para = &core.document.sections[0].paragraphs[0];
        assert_eq!(para.controls.len(), para.ctrl_data_records.len());
    }

    /// [#3214] HWPX 파서는 CTRL_DATA(HWP5 전용 레코드) 개념이 없어 `ctrl_data_records` 를
    /// 채우지 않는다. 즉 `ctrl_data_records.len() < controls.len()` 은 HWPX 문서의 정상
    /// 상태이며, 컨트롤 삽입 경로는 이를 견뎌야 한다.
    #[test]
    fn issue3214_insert_survives_unaligned_ctrl_data_records() {
        let mut core = DocumentCore::new_empty();
        core.create_blank_document_native().unwrap();
        core.insert_text_native(0, 0, 0, "ab").unwrap();

        // HWPX 파서가 남기는 어긋난 상태를 재현한다(컨트롤은 있고 CTRL_DATA 는 없음).
        core.create_header_footer_native(0, true, 0).unwrap();
        {
            let para = &mut core.document.sections[0].paragraphs[0];
            para.ctrl_data_records.clear();
            assert!(!para.controls.is_empty());
        }

        core.insert_footnote_native(0, 0, 2).unwrap();

        let para = &core.document.sections[0].paragraphs[0];
        assert_eq!(
            para.controls.len(),
            para.ctrl_data_records.len(),
            "삽입 후 두 배열 길이가 정합해야 한다"
        );
    }

    /// [#4324] `reflow_hf_paragraph`가 `self.styles`(직전 rebuild_section 스냅샷)를
    /// 읽으면, `apply_para_format_in_hf_native`가 그 직전에 `find_or_create_para_shape`로
    /// 막 만든 새 para_shape_id는 그 스냅샷의 `para_styles` 범위 밖이라
    /// margin_left/margin_right가 0.0으로 폴백한다 — 여백을 무시한(옛) 폭으로
    /// 리플로우해버려 이 이슈가 고치려던 결함이 머리말/꼬리말 경로에서 그대로 남는다.
    ///
    /// 재현: `rebuild_section`으로 self.styles 스냅샷을 "margin 0, para_shape 1개"
    /// 상태로 고정한 뒤(직전 명령이 남긴 스냅샷과 같은 전제), marginLeft 적용 전/후의
    /// 줄 수를 비교한다.
    #[test]
    fn para_format_margin_change_in_header_reflows_with_correct_width_not_stale_styles() {
        use crate::model::document::{Document, Section, SectionDef};
        use crate::model::page::PageDef;
        use crate::model::paragraph::CharShapeRef;

        let mut doc = Document::default();
        let section = Section {
            section_def: SectionDef {
                page_def: PageDef {
                    width: 28504,
                    height: 84188,
                    margin_left: 4252,
                    margin_right: 4252,
                    margin_top: 5668,
                    margin_bottom: 4252,
                    margin_header: 4252,
                    margin_footer: 4252,
                    ..Default::default()
                },
                ..Default::default()
            },
            paragraphs: vec![Paragraph::default()],
            trailing_lists: None,
            raw_stream: None,
            raw_provenance: None,
        };
        // text_width = 28504 - 4252 - 4252 = 20000 HWPUNIT (≈266.7px) — formatting.rs의
        // 셀 재현 테스트와 같은 축척.
        doc.sections.push(section);
        let mut core = DocumentCore::new_empty();
        core.document = doc;
        core.composed = vec![Vec::new()];
        core.dirty_sections = vec![true];
        core.dirty_paragraphs = vec![None];

        core.create_header_footer_native(0, true, 0)
            .expect("머리말 생성이 성공해야 함");

        let text = "A".repeat(200);
        {
            let para = core.get_hf_paragraph_mut(0, true, 0, 0).unwrap();
            para.text = text.clone();
            para.char_offsets = (0..text.chars().count() as u32).collect();
            // 공통 IR 의 char_count 는 문단 종결자를 포함한다 (model/paragraph.rs).
            para.char_count = text.chars().count() as u32 + 1;
            para.char_shapes = vec![CharShapeRef {
                start_pos: 0,
                char_shape_id: 0,
            }];
            para.has_para_text = true;
        }

        // self.styles 스냅샷을 지금(margin 0, para_shape 1개) 상태로 고정한다.
        core.rebuild_section(0);

        // 기준선: 여백 0 상태에서 실제 폭으로 리플로우한 줄 수.
        core.reflow_hf_paragraph(0, true, 0, 0);
        let before_lines = core
            .get_hf_paragraph_ref(0, true, 0, 0)
            .unwrap()
            .line_segs
            .len();

        // marginLeft 적용 — 기존 para_shape(margin 0)와 달라 새 id가 만들어진다.
        // self.styles가 stale이면 새 id 조회가 None → margin 0 폴백 → 폭이 그대로다.
        core.apply_para_format_in_hf_native(0, true, 0, 0, r#"{"marginLeft":8000}"#)
            .expect("서식 적용이 성공해야 함");
        let after_lines = core
            .get_hf_paragraph_ref(0, true, 0, 0)
            .unwrap()
            .line_segs
            .len();

        assert!(
            after_lines > before_lines,
            "marginLeft 적용으로 사용 가능 폭이 줄었으면 줄 수가 늘어야 함 \
             (before={before_lines}줄, after={after_lines}줄 — self.styles가 stale이면 \
             새 para_shape_id 조회가 None이 되어 margin=0으로 폴백, after==before로 남는다)"
        );
    }
}