rhwp 0.9.1

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
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
//! HWP/HWPX 파일 파서 모듈
//!
//! HWP 5.0 바이너리 또는 HWPX(XML) 파일을 파싱하여 IR(Document Model)로 변환한다.
//!
//! ## HWP 바이너리 파싱 순서
//! 1. CFB 컨테이너 열기 (cfb_reader)
//! 2. FileHeader 파싱 (header)
//! 3. DocInfo 파싱 → 참조 테이블 구축 (doc_info)
//! 4. BodyText 파싱 → 섹션/문단 (body_text)
//! 5. 컨트롤 파싱 → 표/도형/그림 (control)
//!
//! ## HWPX 파싱 순서
//! 1. ZIP 컨테이너 열기 (hwpx/reader)
//! 2. content.hpf → 섹션 목록 (hwpx/content)
//! 3. header.xml → DocInfo (hwpx/header)
//! 4. section*.xml → Section (hwpx/section)

mod auto_numbers;
pub(crate) use auto_numbers::{assign_auto_numbers, assign_auto_numbers_from_fields};

pub mod bin_data;
pub mod body_text;
pub mod byte_reader;
pub mod cfb_reader;
pub mod control;
pub mod crypto;
pub mod doc_info;
pub mod header;
pub mod hml;
pub mod hwp3;
pub mod hwp_summary;
pub mod hwpx;
pub mod ingest;
pub mod ole_container;
#[cfg(feature = "pdf-import")]
pub mod pdf;
pub mod record;
pub mod tags;
pub(crate) mod tracked_viewtext;

use crate::model::bin_data::BinDataContent;
use crate::model::document::{
    Document, FileHeader as ModelFileHeader, HwpVersion as ModelHwpVersion, Preview, PreviewImage,
    PreviewImageFormat,
};

/// 파일 포맷 종류
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum FileFormat {
    /// HWP 5.0 바이너리 (CFB/OLE 컨테이너)
    Hwp,
    /// HWPX (XML 기반, ZIP 컨테이너)
    Hwpx,
    /// HWP 3.0 바이너리
    Hwp3,
    /// Standalone HWPML XML
    Hml,
    /// PDF (실험적 가져오기는 `pdf-import` feature 필요)
    Pdf,
    /// DRM/보안 컨테이너로 보호된 문서 (미지원 — 감지만, Issue #1982)
    /// Fasoo(`\x9b DRMONE`) / SoftCamp SCDSA(`SCDSA00x`) 등. 복호화는 범위 밖.
    DrmProtected,
    /// 빈 파일(0 바이트) (Issue #1982)
    Empty,
    /// 알 수 없는 포맷
    Unknown,
}

const UNSUPPORTED_FILE_FORMAT_CODE: &str = "UNSUPPORTED_FILE_FORMAT";
const SUPPORTED_FORMATS_HINT: &str =
    "현재 rhwp는 HWP 5.0, HWPX, 일부 HWP 3.0, HWPML 2.9 문서를 지원합니다.";
const DRM_PROTECTED_CODE: &str = "DRM_PROTECTED";
const DRM_PROTECTED_HINT: &str =
    "DRM/보안 컨테이너로 보호된 문서입니다. 한컴오피스 등 DRM 클라이언트에서 보호를 해제한 뒤 저장해 열어주세요.";
const EMPTY_FILE_CODE: &str = "EMPTY_FILE";
const EMPTY_FILE_HINT: &str = "빈 파일(0 바이트)입니다.";
pub(crate) const PDF_IMPORT_DISABLED_HINT: &str =
    "이 빌드는 PDF 가져오기가 제외되었습니다. pdf-import feature를 포함해 다시 빌드하세요.";

/// HWP5 완전 문서 열기가 선택하는 핵심 스트림 출력 예산.
///
/// 이 정책은 `parse_hwp*`와 자동 포맷 감지 진입점에서만 만들고, CFB/암호 계층에는
/// 남은 바이트 상한만 명시적으로 전달한다.
#[derive(Clone, Copy, Debug)]
struct Hwp5DocumentOpenDecompressionLimits {
    max_stream_input_bytes: usize,
    max_stream_output_bytes: usize,
    max_total_output_bytes: usize,
}

impl Hwp5DocumentOpenDecompressionLimits {
    const DEFAULT: Self = Self {
        // 암호문/압축 원본도 materialize 전에 제한한다. 압축 불가 데이터와 암호화
        // 블록 패딩을 위해 출력 상한보다 1 MiB 여유를 둔다.
        max_stream_input_bytes: 257 * 1024 * 1024,
        // 단일 DocInfo/BodyText 압축 해제 결과 상한. HWPX XML 엔트리와 HWP3 본문에
        // 적용된 256 MiB 문서 열기 계약과 맞춘다.
        max_stream_output_bytes: 256 * 1024 * 1024,
        // 여러 정상 섹션을 허용하되 단일 문서가 상한을 반복하지 못하게 하는 누적 상한.
        max_total_output_bytes: 512 * 1024 * 1024,
    };
}

/// 자동 포맷 감지를 포함한 완전 문서 열기의 자원 정책.
///
/// HWP3은 그 자체로 완전 문서 진입점인 `hwp3::parse_hwp3`에도 같은 기본 정책을
/// 적용하지만, 자동 감지 경로에서는 이 객체가 명시적으로 전달한다.
#[derive(Clone, Copy, Debug)]
struct DocumentOpenDecompressionPolicy {
    hwp5: Hwp5DocumentOpenDecompressionLimits,
    hwp3_max_body_output_bytes: usize,
}

impl DocumentOpenDecompressionPolicy {
    const DEFAULT: Self = Self {
        hwp5: Hwp5DocumentOpenDecompressionLimits::DEFAULT,
        hwp3_max_body_output_bytes: hwp3::DEFAULT_HWP3_DOCUMENT_OPEN_BODY_OUTPUT_BYTES,
    };
}

/// 비밀번호 보호 HWP5의 BinData를 parser가 materialize할 때 적용하는 별도 출력 상한.
///
/// BinData는 DocInfo/BodyText 문서 열기 누적 예산에는 포함하지 않지만, 해당 소비 경로가
/// crypto helper에 명시적으로 전달하는 parser 소유 정책이다.
const MAX_PASSWORD_PROTECTED_BIN_DATA_OUTPUT_BYTES: usize = 512 * 1024 * 1024;

#[cfg(test)]
thread_local! {
    /// E2E 회귀에서 공개 문서 열기 API를 작은 예산으로 실행하는 scoped test seam.
    /// 릴리스 빌드에는 존재하지 않는다.
    static TEST_DOCUMENT_OPEN_DECOMPRESSION_POLICY:
        std::cell::Cell<Option<DocumentOpenDecompressionPolicy>> = const { std::cell::Cell::new(None) };
}

fn document_open_decompression_policy() -> DocumentOpenDecompressionPolicy {
    #[cfg(test)]
    {
        TEST_DOCUMENT_OPEN_DECOMPRESSION_POLICY.with(|slot| {
            slot.get()
                .unwrap_or(DocumentOpenDecompressionPolicy::DEFAULT)
        })
    }

    #[cfg(not(test))]
    {
        DocumentOpenDecompressionPolicy::DEFAULT
    }
}

#[cfg(test)]
struct TestDocumentOpenDecompressionPolicyGuard(Option<DocumentOpenDecompressionPolicy>);

#[cfg(test)]
impl Drop for TestDocumentOpenDecompressionPolicyGuard {
    fn drop(&mut self) {
        TEST_DOCUMENT_OPEN_DECOMPRESSION_POLICY.with(|slot| slot.set(self.0));
    }
}

#[cfg(test)]
fn with_document_open_decompression_policy_for_test<T>(
    policy: DocumentOpenDecompressionPolicy,
    operation: impl FnOnce() -> T,
) -> T {
    let previous = TEST_DOCUMENT_OPEN_DECOMPRESSION_POLICY.with(|slot| slot.replace(Some(policy)));
    let _restore = TestDocumentOpenDecompressionPolicyGuard(previous);
    operation()
}

#[derive(Debug)]
struct Hwp5DocumentOpenDecompressionBudget {
    remaining: usize,
    max_stream_input_bytes: usize,
    max_stream_output_bytes: usize,
}

impl Hwp5DocumentOpenDecompressionBudget {
    fn new(limits: Hwp5DocumentOpenDecompressionLimits) -> Self {
        Self {
            remaining: limits.max_total_output_bytes,
            max_stream_input_bytes: limits.max_stream_input_bytes,
            max_stream_output_bytes: limits.max_stream_output_bytes,
        }
    }

    fn stream_limit(&self) -> usize {
        self.remaining.min(self.max_stream_output_bytes)
    }

    /// 암호문과 압축 원본을 `Vec`로 읽기 전에 적용하는 별도 상한이다.
    ///
    /// 압축 해제 출력 상한만으로는 원시 스트림이 과도하게 큰 입력을 막지 못하므로,
    /// strict/lenient CFB 경로 모두 이 값을 먼저 적용해야 한다.
    fn raw_stream_limit(&self) -> usize {
        self.max_stream_input_bytes
    }

    fn consume(&mut self, bytes: usize) -> Result<(), cfb_reader::CfbError> {
        if bytes > self.stream_limit() {
            return Err(cfb_reader::CfbError::LimitExceeded(self.stream_limit()));
        }
        self.remaining -= bytes;
        Ok(())
    }
}

// DRM/보안 컨테이너 시그니처 (Issue #1982 — 10k 서베이 검출).
// Fasoo: `\x9b DRMONE  This Document is encrypted and protected by Fasoo`.
const FASOO_DRM_SIG: &[u8] = b"\x9b DRMONE";
// SoftCamp SCDSA(Security Content Document Security Agent): `SCDSA002`/`SCDSA004`.
const SCDSA_SIG: &[u8] = b"SCDSA";

/// 파일 데이터의 매직 바이트로 포맷을 감지한다.
pub fn detect_format(data: &[u8]) -> FileFormat {
    if data.is_empty() {
        return FileFormat::Empty;
    }
    // DRM/보안 컨테이너(미지원 — 감지만, Issue #1982). 정상 매직보다 먼저 판별해
    // "알 수 없는 파일 형식" 대신 명확한 안내를 준다.
    if data.starts_with(FASOO_DRM_SIG) || data.starts_with(SCDSA_SIG) {
        return FileFormat::DrmProtected;
    }
    if data.starts_with(b"%PDF-") {
        return FileFormat::Pdf;
    }
    if data.len() >= 8 {
        // CFB/OLE 시그니처: D0 CF 11 E0 A1 B1 1A E1
        if data[0] == 0xD0 && data[1] == 0xCF && data[2] == 0x11 && data[3] == 0xE0 {
            return FileFormat::Hwp;
        }
        // ZIP 시그니처는 HWPX 후보일 뿐이다. XLSX/DOCX 등 OOXML도 같은 매직을
        // 사용하므로 중앙 디렉터리의 HWPX 필수 엔트리까지 확인해 최종 확정한다.
        if data[0] == 0x50
            && data[1] == 0x4B
            && data[2] == 0x03
            && data[3] == 0x04
            && hwpx::reader::has_required_package_entries(data)
        {
            return FileFormat::Hwpx;
        }
    }
    // HWP 3.0 바이너리 (Issue #265): "HWP Document File" 프리픽스.
    // V3.00 ~ 2.x/초기 한컴 워디안까지 관대하게 포괄.
    if data.len() >= 17 && &data[0..17] == b"HWP Document File" {
        return FileFormat::Hwp3;
    }
    if hml::detect_hml_signature(data) {
        return FileFormat::Hml;
    }
    FileFormat::Unknown
}

/// 파싱 에러 (통합)
#[derive(Debug)]
pub enum ParseError {
    CfbError(cfb_reader::CfbError),
    HeaderError(header::HeaderError),
    DocInfoError(doc_info::DocInfoError),
    BodyTextError(body_text::BodyTextError),
    CryptoError(crypto::CryptoError),
    HwpxError(hwpx::HwpxError),
    Hwp3Error(hwp3::Hwp3Error),
    HmlError(hml::HmlError),
    #[cfg(feature = "pdf-import")]
    PdfError(pdf::PdfImportError),
    EncryptedDocument,
    /// 감지는 되었으나 지원하지 않는 포맷
    UnsupportedFormat {
        code: &'static str,
        format: &'static str,
        hint: &'static str,
    },
}

impl std::fmt::Display for ParseError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ParseError::CfbError(e) => write!(f, "CFB 오류: {}", e),
            ParseError::HeaderError(e) => write!(f, "헤더 오류: {}", e),
            ParseError::DocInfoError(e) => write!(f, "DocInfo 오류: {}", e),
            ParseError::BodyTextError(e) => write!(f, "BodyText 오류: {}", e),
            ParseError::CryptoError(e) => write!(f, "암호 오류: {}", e),
            ParseError::HwpxError(e) => write!(f, "HWPX 오류: {}", e),
            ParseError::Hwp3Error(e) => write!(f, "HWP 3.0 오류: {}", e),
            ParseError::HmlError(e) => write!(f, "HML 오류: {}", e),
            #[cfg(feature = "pdf-import")]
            ParseError::PdfError(e) => write!(f, "PDF 오류: {}", e),
            ParseError::EncryptedDocument => write!(
                f,
                "비밀번호가 필요한 암호 문서입니다 (parse_document_with_password 또는 parse_hwp_with_password 로 비밀번호를 전달하세요)"
            ),
            ParseError::UnsupportedFormat { code, format, hint } => {
                write!(
                    f,
                    "지원하지 않는 포맷입니다: {format}. 오류코드: {code}. {hint}"
                )
            }
        }
    }
}

impl std::error::Error for ParseError {}

impl From<hwpx::HwpxError> for ParseError {
    fn from(e: hwpx::HwpxError) -> Self {
        match e {
            hwpx::HwpxError::Encrypted(_) => ParseError::EncryptedDocument,
            other => ParseError::HwpxError(other),
        }
    }
}

impl From<hwp3::Hwp3Error> for ParseError {
    fn from(e: hwp3::Hwp3Error) -> Self {
        match e {
            hwp3::Hwp3Error::PasswordRequired => ParseError::EncryptedDocument,
            other => ParseError::Hwp3Error(other),
        }
    }
}

impl From<hml::HmlError> for ParseError {
    fn from(error: hml::HmlError) -> Self {
        ParseError::HmlError(error)
    }
}

/// HWP 파일 바이트 데이터를 파싱하여 Document IR로 변환
///
/// 파싱 순서:
/// 1. CFB 컨테이너 열기
/// 2. FileHeader 파싱 (버전, 플래그)
/// 3. DocInfo 파싱 (참조 테이블)
/// 4. BodyText 섹션별 파싱 (배포용 문서: ViewText 복호화)
pub fn parse_hwp(data: &[u8]) -> Result<Document, ParseError> {
    parse_hwp_inner(data, None)
}

/// 비밀번호로 보호된 HWP 파일을 비밀번호와 함께 파싱한다.
///
/// `encrypted` 플래그와 EncryptVersion 4가 설정된 문서를 연다. 비밀번호가 틀리면
/// `ParseError::CryptoError(CryptoError::WrongPassword)` 가 반환된다. 비밀번호가
/// 필요 없는 일반/배포용 문서에 비밀번호를 전달해도 결과는 동일하다(무시됨).
pub fn parse_hwp_with_password(data: &[u8], password: &[u8]) -> Result<Document, ParseError> {
    parse_hwp_inner(data, Some(password))
}

fn validate_password_encryption(file_header: &header::FileHeader) -> Result<(), ParseError> {
    if file_header.flags.encrypted
        && file_header.encrypt_version != crypto::SUPPORTED_PASSWORD_ENCRYPT_VERSION
    {
        return Err(ParseError::CryptoError(
            crypto::CryptoError::UnsupportedScheme {
                encrypt_version: file_header.encrypt_version,
            },
        ));
    }
    Ok(())
}

fn parse_doc_info_stream(
    data: &[u8],
    encrypted: bool,
) -> Result<
    (
        crate::model::document::DocInfo,
        crate::model::document::DocProperties,
    ),
    ParseError,
> {
    if encrypted {
        // 압축 문서는 deflate 오류로 오답 비밀번호를 검출할 수 있지만 비압축 문서는
        // 레코드 구조를 직접 확인해야 한다. DocInfo의 필수 선두 레코드 두 종류를
        // 인증 표식으로 사용해 무작위 복호화 결과가 빈/부분 문서로 통과하지 않게 한다.
        let records = record::Record::read_all(data)
            .map_err(|_| ParseError::CryptoError(crypto::CryptoError::WrongPassword))?;
        let has_required_prefix = records
            .first()
            .is_some_and(|record| record.tag_id == tags::HWPTAG_DOCUMENT_PROPERTIES)
            && records
                .iter()
                .any(|record| record.tag_id == tags::HWPTAG_ID_MAPPINGS);
        if !has_required_prefix {
            return Err(ParseError::CryptoError(crypto::CryptoError::WrongPassword));
        }
    }

    doc_info::parse_doc_info(data).map_err(|error| {
        if encrypted {
            ParseError::CryptoError(crypto::CryptoError::WrongPassword)
        } else {
            ParseError::DocInfoError(error)
        }
    })
}

fn parse_hwp_inner(data: &[u8], password: Option<&[u8]>) -> Result<Document, ParseError> {
    parse_hwp_inner_with_limits(data, password, document_open_decompression_policy().hwp5)
}

fn parse_hwp_inner_with_limits(
    data: &[u8],
    password: Option<&[u8]>,
    limits: Hwp5DocumentOpenDecompressionLimits,
) -> Result<Document, ParseError> {
    // 1. CFB 컨테이너 열기 (strict → lenient 폴백)
    let mut document = match cfb_reader::CfbReader::open(data) {
        Ok(cfb) => parse_hwp_with_cfb(cfb, data, password, limits),
        Err(strict_err) => {
            eprintln!(
                "표준 CFB 파서 실패: {}, lenient 파서로 재시도...",
                strict_err
            );
            let lenient = cfb_reader::LenientCfbReader::open(data)
                .map_err(|_| ParseError::CfbError(strict_err))?;
            parse_hwp_with_lenient(lenient, data, password, limits)
        }
    }?;
    document.seal_section_tail_provenance();
    document.seal_loaded_memo_tails();
    Ok(document)
}

/// 표준 CfbReader로 파싱
fn parse_hwp_with_cfb(
    mut cfb: cfb_reader::CfbReader,
    raw_data: &[u8],
    password: Option<&[u8]>,
    limits: Hwp5DocumentOpenDecompressionLimits,
) -> Result<Document, ParseError> {
    // 2. FileHeader 파싱
    let header_data = cfb.read_file_header().map_err(ParseError::CfbError)?;
    let file_header = header::parse_file_header(&header_data).map_err(ParseError::HeaderError)?;
    validate_password_encryption(&file_header)?;

    let encrypted = file_header.flags.encrypted;
    // 비밀번호 암호 문서인데 비밀번호가 없으면 열 수 없다.
    // 비밀번호가 제공되지 않은 경우 기존과 동일하게 EncryptedDocument 에러로
    // 호출자가 비밀번호 입력을 유도할 수 있게 한다.
    if encrypted && password.is_none() {
        return Err(ParseError::EncryptedDocument);
    }

    let compressed = file_header.flags.compressed;
    let distribution = file_header.flags.distribution;
    let mut decompression_budget = Hwp5DocumentOpenDecompressionBudget::new(limits);

    // 3. DocInfo 파싱 (비밀번호 암호 문서: raw 읽기 → 복호화)
    //
    // EncryptVersion 4(한글 7.0 이후)만 지원한다. 구버전 1~3을 같은 알고리즘으로
    // 해석하면 WrongPassword로 오진하므로 FileHeader 단계에서 명시적으로 거부한다.
    let doc_info_output_limit = decompression_budget.stream_limit();
    let doc_info_raw_limit = decompression_budget.raw_stream_limit();
    let doc_info_data = if encrypted {
        let raw = cfb
            .read_stream_raw_limited("/DocInfo", doc_info_raw_limit)
            .map_err(ParseError::CfbError)?;
        crypto::decrypt_password_protected_limited(
            &raw,
            password.unwrap(),
            compressed,
            doc_info_output_limit,
        )
        .map_err(ParseError::CryptoError)?
    } else {
        let raw = cfb
            .read_stream_raw_limited("/DocInfo", doc_info_raw_limit)
            .map_err(ParseError::CfbError)?;
        cfb_reader::decode_stream_limited(raw, compressed, doc_info_output_limit)
            .map_err(ParseError::CfbError)?
    };
    decompression_budget
        .consume(doc_info_data.len())
        .map_err(ParseError::CfbError)?;
    let (mut doc_info, doc_properties) = parse_doc_info_stream(&doc_info_data, encrypted)?;
    doc_info::apply_v5024_strike_bits(&mut doc_info.char_shapes, &file_header.version);
    if let Ok(bytes) = cfb.read_stream_raw_limited(
        crate::model::native_font_program::HWP_STREAM,
        crate::model::native_font_program::MAX_BYTES,
    ) {
        crate::model::native_font_program::decode(&mut doc_info, &doc_info_data, &bytes);
    }
    doc_info.raw_stream = Some(doc_info_data);

    // 4. BodyText 섹션별 파싱
    //
    // rhwp 저장 표지가 인증한 구역만 LineSeg tag bit 31 을 rhwp 합성 표지로 읽는다(#8939).
    // 표지는 보조 스트림으로 남아 저장기가 원본 그대로 다시 쓰는 구역의 의미를 이어 받는다.
    let rhwp_line_seg_sections = cfb
        .read_stream_raw_limited(
            crate::model::line_seg_tags::HWP_STREAM,
            crate::model::line_seg_tags::MAX_BYTES,
        )
        .map(|bytes| crate::model::line_seg_tags::decode(&bytes))
        .unwrap_or_default();
    let section_count = cfb.section_count();
    let sections = parse_sections_strict(
        &mut cfb,
        &rhwp_line_seg_sections,
        section_count,
        compressed,
        distribution,
        encrypted,
        password,
        &mut decompression_budget,
        &doc_info,
    )?;

    // 5-7. 미리보기, BinData, 추가 스트림
    // Preview is optional document metadata.  A malformed or disproportionately
    // large thumbnail must not prevent the actual document from opening.
    let preview = extract_preview(&mut cfb, MAX_THUMBNAIL_BYTES);
    let bin_data_content = load_bin_data_content(
        &mut cfb,
        raw_data,
        &doc_info.bin_data_list,
        compressed,
        encrypted,
        password,
    );
    let extra_streams = collect_extra_streams(
        &mut cfb,
        &doc_info.bin_data_list,
        &bin_data_content,
        encrypted,
        password,
    );

    // Document 조립
    let model_header = ModelFileHeader {
        version: ModelHwpVersion {
            major: file_header.version.major,
            minor: file_header.version.minor,
            build: file_header.version.build,
            revision: file_header.version.revision,
        },
        flags: file_header.flags.raw,
        compressed,
        encrypted: file_header.flags.encrypted,
        distribution,
        raw_data: Some(header_data),
    };

    // [Task #1001] HWP3 변환본 식별 — HwpSummary HWP3 시대 년 검출.
    // sample16-hwp5 같은 복잡한 변환본 (Task #554 의 PS<0.05 휴리스틱 미적용)
    // 도 식별. 단 false positive (예: HWP5 에 HWP3 시대 텍스트만 인용된 일반
    // 문서 — exam_eng) 차단 위해 PS/CS 비율도 추가 검증 (variant 는 작성자
    // 다양한 스타일 사용 안하므로 작은 비율).
    let summary_hwp3_era = cfb.detect_hwp3_variant();

    // [Issue #1770] rhwp HWPX→HWP 변환본 식별 — 마커 스트림 감지 (결정론).
    // 변환본 IR 은 HWPX LINE_SEG 시멘틱 그대로이므로 pagination/렌더의
    // is_hwpx_source 분기를 HWPX 로 해석해야 roundtrip 쪽수가 자기정합한다.
    let is_hwpx_variant = extra_streams
        .iter()
        .any(|(p, _)| p == crate::model::document::HWPX_ORIGIN_STREAM_PATH);

    let mut doc = Document {
        memo_parents: Vec::new(),
        header: model_header,
        doc_properties,
        doc_info,
        sections,
        preview,
        bin_data_content,
        extra_streams,
        hwpx_aux_entries: Vec::new(),
        is_hwp3_variant: false,
        is_hwpx_variant,
        provenance: crate::model::provenance::SourceProvenance {
            format: crate::model::provenance::SourceFormat::Hwp5,
            hwp3_lineage: false,
            hwpx_lineage: is_hwpx_variant,
            hft_ascii_halfwidth_witnessed: false,
            stored_rows_before_hancom_2020: false,
        },
    };

    // 자동 번호 할당 (문서 전체에서 순차적으로)
    assign_auto_numbers(&mut doc);

    // [Task #554] HWP3 → HWP5 변환본 식별 + page_def margin_bottom 보정
    apply_hwp3_origin_fixup(&mut doc, summary_hwp3_era);

    // [Task #1001] HwpSummary HWP3 시대 년 AND PS/CS 비율 작음 → 변환본 확정.
    // 두 신호 결합으로 false positive 차단 (exam_eng 등 일반 HWP5 가 본문에
    // HWP3 시대 텍스트만 인용한 경우).
    // [#1880 v2] rhwp HWPX→HWP 변환본 제외 — 원본 HWPX 가 HWP3-계보 요약정보를
    // 승계해도 rhwp 변환본 IR 은 HWPX 시멘틱이므로 spacing 반감 보정이 오발동
    // 하면 안 된다 (위 apply_hwp3_origin_fixup 게이트와 동일 근거).
    if summary_hwp3_era && !doc.is_hwpx_variant {
        let total_paras: usize = doc.sections.iter().map(|s| s.paragraphs.len()).sum();
        if total_paras > 50 {
            let ps_r = doc.doc_info.para_shapes.len() as f64 / total_paras as f64;
            let cs_r = doc.doc_info.char_shapes.len() as f64 / total_paras as f64;
            if ps_r < 0.20 && cs_r < 0.20 {
                doc.is_hwp3_variant = true;
                doc.provenance.hwp3_lineage = true;
                // 계보는 출처 정보다. HWP5의 문단 간격과 저장 vpos는 HWP5 계약으로
                // 읽으며, 원본 HWP3의 좌표에 맞추어 저장 속성을 다시 줄이지 않는다.
                // 정상 한컴 저장본에서 raw spacing_before / 2가 첫 저장 vpos와 일치한다.
            }
        }
    }

    // [Task #873] BinData Link 타입 의 외부 file path 영역 Picture.external_path 전달.
    // 이후 model::document::populate_external_images_from_dir (Task #741) 가 같은
    // dir 영역 basename 매칭 영역 image 영역 자동 load.
    populate_link_image_paths(&mut doc);

    // 저장 LineSeg의 원점은 문단 간격을 포함한 실제 저장 결과다.
    // 계보에 맞춰 좌표를 다시 쓰지 않고 소비 단계에서 같은 저장 프레임을 사용한다.

    if let Some(idx) = doc
        .extra_streams
        .iter()
        .position(|(p, _)| p == crate::model::border_paint::HWP_STREAM)
    {
        let (_, bytes) = doc.extra_streams.remove(idx);
        crate::model::border_paint::decode(&mut doc, &bytes);
    }
    if let Some(idx) = doc
        .extra_streams
        .iter()
        .position(|(p, _)| p == crate::model::text_clip::HWP_STREAM)
    {
        let (_, bytes) = doc.extra_streams.remove(idx);
        crate::model::text_clip::decode(&mut doc, &bytes);
    }
    if let Some(idx) = doc
        .extra_streams
        .iter()
        .position(|(p, _)| p == crate::model::text_paint::HWP_STREAM)
    {
        let (_, bytes) = doc.extra_streams.remove(idx);
        crate::model::text_paint::decode(&mut doc, &bytes);
    }
    if let Some(idx) = doc
        .extra_streams
        .iter()
        .position(|(p, _)| p == crate::model::hyperlink_format::HWP_STREAM)
    {
        let (_, bytes) = doc.extra_streams.remove(idx);
        if bytes.len() <= 16 * 1024 * 1024 {
            crate::model::hyperlink_format::decode(&mut doc, &bytes);
        }
    }
    // 메모 댓글 관계. 읽지 못한 스트림은 원본으로 남긴다.
    if let Some(idx) = doc
        .extra_streams
        .iter()
        .position(|(p, _)| p == crate::model::memo_extended::HWP_STREAM)
    {
        let raw = &doc.extra_streams[idx].1;
        let data = if doc.header.compressed {
            cfb_reader::decompress_stream_limited(raw, crate::model::memo_extended::MAX_BYTES).ok()
        } else {
            Some(raw.clone())
        };
        if let Some(links) = data
            .as_deref()
            .and_then(crate::model::memo_extended::decode_hwp)
        {
            doc.extra_streams.remove(idx);
            doc.memo_parents = links;
        }
    }
    Ok(doc)
}

/// [Task #554] HWP3 → HWP5/HWPX 변환본 식별 휴리스틱 + 페이지 여백 보정
///
/// 한컴이 HWP3 → HWP5 로 변환할 때 한글97의 "마지막 줄 tolerance" (1600 HU)
/// 동작이 누락되어 페이지 수가 +1 ~ +4 증가한다. 변환본을 식별 후 모든
/// SectionDef.page_def.margin_bottom 을 1600 HU 줄여 한글97 페이지네이션과 정합.
///
/// ## 식별 휴리스틱 (Task #554 진단 결과)
///
/// 한컴은 HWP3 → HWP5 변환 시 ParaShape/CharShape 를 거의 재사용하지 않고 매우
/// 적은 수만 생성하여 paragraph 대비 비율이 극도로 낮다. 직접 작성본은 작성자가
/// 다양한 스타일을 사용하므로 비율이 paragraph 와 비슷하거나 더 높다.
///
/// - **`ParaShape/Paragraph < 0.05` AND `CharShape/Paragraph < 0.15`** → 변환본
/// - **`Paragraph > 50`** 가드: 매우 짧은 문서는 비율이 왜곡되므로 제외
///
/// 27 fixture 검증에서 100% 정확 분류 (Stage 1 보고서 §3.2 참조).
/// [Task #1001] 변환본의 line_segs 단위 보정.
/// vertical_pos 만 ParaShape spacing 누적 영향으로 변환본에서 2배 단위.
/// 나머지 필드 (line_height/text_height/baseline_distance/line_spacing/column_start/
/// segment_width) 는 단위 동일 (HWP3 와 같음) 이라 보정 불필요.
fn fixup_line_segs_for_variant(paragraphs: &mut [crate::model::paragraph::Paragraph]) {
    for para in paragraphs.iter_mut() {
        for ls in para.line_segs.iter_mut() {
            ls.vertical_pos /= 2;
        }
        // 표 셀 내부 paragraph 재귀
        for control in para.controls.iter_mut() {
            if let crate::model::control::Control::Table(table) = control {
                for cell in table.cells.iter_mut() {
                    fixup_line_segs_for_variant(&mut cell.paragraphs);
                }
            }
        }
    }
}

fn apply_hwp3_origin_fixup(doc: &mut Document, summary_hwp3_era: bool) {
    let external_realign = doc.layout_profile().hwp3_external_realign();
    // [#1880 v2] rhwp HWPX→HWP 변환본(is_hwpx_variant, #1886 마커)은 한컴
    // HWP3→HWP5 변환본이 아니다 — 결정론 마커가 비율 휴리스틱에 우선한다.
    // 미게이트 시 저-스타일 대형 문서(2959953)가 비율에 걸려 margin_bottom
    // -1600 이 오발동, HWPX 렌더와 페이지 기하가 21.3px 어긋나 PI_MOVED 유발
    // (HWPX 파스는 #1608 에서 동종 감지 제거됨).
    if doc.is_hwpx_variant {
        return;
    }
    // [#3707] rhwp 가 만든 HWP3→HWP5 변환본에 쪽나눔 허용치를 되돌린다.
    //
    // HWP3 파서는 `pagination_bottom_tolerance = 1600 HU`(21.3px)를 세운다 — 한글97 의
    // 마지막 줄 tolerance 를 흉내 내 **페이지네이터에게만** 여유를 주는 렌더러 내부
    // 값이고 파일 포맷 필드가 아니다. HWP5 로 저장·재파싱하면 0 이 되어 본문 가용이
    // 21.3px 짧아진다.
    //
    // 그만큼 미주 단 가용이 줄어 단 전환이 일찍 걸리고, 2단 미주의 왼쪽 단이 조기에
    // 닫혀 미주가 다음 쪽으로 밀린다(SO-SUEOP 44쪽: 미주 128·129 가 45쪽으로). 한컴은
    // 원본·왕복본 모두 44쪽에 실으므로 허용치가 살아 있는 쪽이 정답지와 맞는다.
    //
    // 파일에 실리는 여백(`margin_bottom`)은 건드리지 않는다 — 줄이면 한컴이 보는 쪽
    // 기하가 원본과 달라지고 `convert --verify` 의 IR 비교에도 잡힌다. 이 값은 그
    // 비교에서 제외되는 렌더러 내부 값이라 왕복 정합을 깨지 않는다.
    if doc
        .extra_streams
        .iter()
        .any(|(p, _)| p == crate::model::document::HWP3_ORIGIN_STREAM_PATH)
    {
        // 마커의 존재 이유가 출처 복원이다 — lineage 를 함께 세워야
        // `native_hwp5_layout` 이 변환본을 원본 HWP5 로 오판하지 않는다.
        // (종전에는 휴리스틱(문단>50·shape 비율)만 lineage 를 세워, 마커가
        // 있는 소형 서식 변환본이 native 로 새어 저장-lineseg 전용 분기가
        // 발화했다 — issue_1892 자기일관 실측.)
        doc.provenance.hwp3_lineage = true;
        for section in doc.sections.iter_mut() {
            let pd = &mut section.section_def.page_def;
            if !external_realign && pd.pagination_bottom_tolerance == 0 {
                pd.pagination_bottom_tolerance = 1600.min(pd.margin_bottom);
            }
        }
    }

    // 출처는 보존하되 외부 문서의 재정렬 요청에 이전 마지막 줄 허용치를 덧씌우지 않는다.
    if external_realign {
        return;
    }
    let total_paragraphs: usize = doc.sections.iter().map(|s| s.paragraphs.len()).sum();
    if total_paragraphs <= 50 {
        return;
    }
    // [#7035] 비율 휴리스틱에 **결정론 신호를 함께 요구한다.**
    //
    // 바로 아래 `is_hwp3_variant` 판정([Task #1001])은 같은 질문에 `summary_hwp3_era`
    // (HwpSummary 의 1990~2003년 표기) **AND** 비율을 쓰는데, 여기는 비율만 봤다. 더 약한
    // 쪽이 조판 예산(`pagination_bottom_tolerance` = 한글97 마지막 줄 허용치 21.3px)을
    // 쥐고 있었다.
    //
    // 실측: 속기자료 4문서(148733091 · 148737458 · 148759033 · 148762372)는 진짜 HWP5
    // (version 5.0.0.6 · 저장 5.7.9.3051 · HWP3 출처 마커 없음)인데 비율에 걸린다
    // (ps 0.034~0.040 · cs 0.038~0.045). 그 허용치가 typeset 예산을 본문보다 21.3px 크게
    // 만들어 쪽마다 마지막 한 줄이 본문 바닥을 +2.9~+11.4px 넘겨 그려졌다(#7035).
    // 한/글 2020 정본은 그 줄들을 다음 쪽 첫머리에 둔다.
    //
    // 결정론 신호는 두 무리를 완전히 가른다 — 저장소의 HWP3 to HWP5 변환본 16건은 전부
    // `summary_hwp3_era = true`, 위 속기자료 4건은 전부 `false` 다. 종전 주석이 적어 둔
    // "추정이라 오탐 비용이 특히 크다"(02600 사례)를 이 신호로 막는다.
    if !summary_hwp3_era {
        return;
    }
    let ps_ratio = doc.doc_info.para_shapes.len() as f64 / total_paragraphs as f64;
    let cs_ratio = doc.doc_info.char_shapes.len() as f64 / total_paragraphs as f64;
    if ps_ratio < 0.05 && cs_ratio < 0.15 {
        // [Task #554] 변환본 의심 시 한글97 의 마지막 줄 tolerance 를 흉내 낸다.
        // is_hwp3_variant 플래그 설정은 caller 가 별도 (HwpSummary HWP3-era + 더 관대한
        // ratio AND 조건) 로 처리 — hwpspec.hwp 같은 spec 문서 false-positive 차단 위해
        // ratio 단독 변환본 확정 회피.
        //
        // 종전에는 `margin_bottom` 을 직접 1600 깎았다. 그건 **파일에 실리는 값**이라
        // 저장본의 쪽 기하가 원본과 달라진다 — 위 #3707 블록이 같은 이유로 이미 금지한
        // 조작이다. 이 휴리스틱은 확정이 아니라 추정이라 오탐 비용이 특히 크다:
        // 02600 은 진짜 HWP5 인데 비율에 걸려 아래 여백이 4252 -> 2652 가 되고, 쪽당
        // 내용이 늘어 한글이 36쪽 문서를 35쪽으로 연다(오라클 실측).
        //
        // 페이지네이터에게만 여유를 주는 `pagination_bottom_tolerance` 로 옮기면 의도한
        // 조판 효과는 그대로 두면서 파일 값은 원본대로 남는다. 이 필드는 렌더러 내부
        // 값이라 `--verify` IR 비교에서도 제외된다.
        for section in doc.sections.iter_mut() {
            let pd = &mut section.section_def.page_def;
            if pd.pagination_bottom_tolerance == 0 {
                pd.pagination_bottom_tolerance = 1600.min(pd.margin_bottom);
            }
        }
    }
}

/// Decode a non-distribution ViewText paragraph stream, falling back on stubs.
/// Change-tracking streams contain review history, not just visible content;
/// DocInfo visibility must be applied before this stream becomes layout IR.
fn decode_rendered_viewtext(
    raw: Vec<u8>,
    compressed: bool,
    output_limit: usize,
) -> Option<Vec<u8>> {
    let decoded = cfb_reader::decode_stream_limited(raw, compressed, output_limit).ok()?;
    starts_with_paragraph_header(&decoded).then_some(decoded)
}

fn starts_with_paragraph_header(data: &[u8]) -> bool {
    data.get(..4).is_some_and(|bytes| {
        let header = u32::from_le_bytes(bytes.try_into().unwrap());
        (header & 0x3ff) as u16 == tags::HWPTAG_PARA_HEADER
    })
}

/// 암호 문서도 #5169의 ViewText 우선 정책을 따른다. 스텁은 BodyText로 내려가되,
/// 읽기 오류와 자원 제한 초과는 숨기지 않는다. DocInfo에서 비밀번호는 이미 검증됐다.
/// 반환값은 복호화된 문단 레코드 스트림이며, 비밀번호나 파생 키가 아니다.
fn decode_viewtext_paragraph_stream(
    raw: Result<Vec<u8>, cfb_reader::CfbError>,
    password: &[u8],
    compressed: bool,
    output_limit: usize,
) -> Result<Option<Vec<u8>>, ParseError> {
    let raw = match raw {
        Ok(raw) => raw,
        Err(cfb_reader::CfbError::StreamNotFound(_)) => return Ok(None),
        Err(error) => return Err(ParseError::CfbError(error)),
    };
    match crypto::decrypt_password_protected_limited(&raw, password, compressed, output_limit) {
        Ok(decoded) => Ok(starts_with_paragraph_header(&decoded).then_some(decoded)),
        Err(crypto::CryptoError::WrongPassword) => Ok(None),
        Err(error) => Err(ParseError::CryptoError(error)),
    }
}

fn parse_visible_section(
    data: &[u8],
    previous: &mut [crate::model::document::Section],
    doc_info: &crate::model::document::DocInfo,
) -> Result<crate::model::document::Section, body_text::BodyTextError> {
    let projected = tracked_viewtext::project(data, doc_info)?;
    body_text::parse_section_with_previous(projected.as_deref().unwrap_or(data), previous)
}

/// CfbReader로 섹션들 파싱
#[allow(clippy::too_many_arguments)]
fn parse_sections_strict(
    cfb: &mut cfb_reader::CfbReader,
    rhwp_line_seg_sections: &[[u8; 32]],
    section_count: u32,
    compressed: bool,
    distribution: bool,
    encrypted: bool,
    password: Option<&[u8]>,
    decompression_budget: &mut Hwp5DocumentOpenDecompressionBudget,
    doc_info: &crate::model::document::DocInfo,
) -> Result<Vec<crate::model::document::Section>, ParseError> {
    let mut sections = Vec::new();

    for i in 0..section_count {
        let section_output_limit = decompression_budget.stream_limit();
        let section_raw_limit = decompression_budget.raw_stream_limit();
        let section_data = if distribution {
            // 배포용 문서: ViewText 복호화
            let raw = cfb
                .read_viewtext_section_raw_limited(i, section_raw_limit)
                .map_err(ParseError::CfbError)?;
            crypto::decrypt_viewtext_section_limited(&raw, compressed, section_output_limit)
                .map_err(ParseError::CryptoError)?
        } else if encrypted {
            let rendered = decode_viewtext_paragraph_stream(
                cfb.read_viewtext_section_raw_limited(i, section_raw_limit),
                password.unwrap(),
                compressed,
                section_output_limit,
            )?;
            match rendered {
                Some(decoded) => decoded,
                None => {
                    let raw = cfb
                        .read_body_text_section_raw_limited(i, section_raw_limit)
                        .map_err(ParseError::CfbError)?;
                    crypto::decrypt_password_protected_limited(
                        &raw,
                        password.unwrap(),
                        compressed,
                        section_output_limit,
                    )
                    .map_err(ParseError::CryptoError)?
                }
            }
        } else {
            // ViewText may be the only complete section. Apply its visibility
            // separately after decoding; existence alone does not mean visible.
            let rendered = cfb
                .read_viewtext_section_raw_limited(i, section_raw_limit)
                .ok()
                .and_then(|raw| decode_rendered_viewtext(raw, compressed, section_output_limit));
            match rendered {
                Some(decoded) => decoded,
                None => {
                    let raw = cfb
                        .read_body_text_section_raw_limited(i, section_raw_limit)
                        .map_err(ParseError::CfbError)?;
                    cfb_reader::decode_stream_limited(raw, compressed, section_output_limit)
                        .map_err(ParseError::CfbError)?
                }
            }
        };
        decompression_budget
            .consume(section_data.len())
            .map_err(ParseError::CfbError)?;

        let _rhwp_line_seg_tags = rhwp_line_seg_sections
            .contains(&crate::model::line_seg_tags::section_digest(&section_data))
            .then(body_text::RhwpLineSegTagScope::enter);
        match parse_visible_section(&section_data, &mut sections, doc_info) {
            Ok(mut section) => {
                // 원본 BodyText 스트림 보존 (라운드트립용)
                section.raw_stream = Some(section_data);
                sections.push(section);
            }
            Err(
                e @ (body_text::BodyTextError::DrawingTextStructure(_)
                | body_text::BodyTextError::ChangeTrackingStructure(_)),
            ) => {
                return Err(ParseError::BodyTextError(e));
            }
            Err(e) => {
                // 개별 섹션 파싱 실패 시 빈 섹션으로 대체 (전체 실패 방지)
                eprintln!("경고: Section{} 파싱 실패: {}", i, e);
                sections.push(crate::model::document::Section::default());
            }
        }
    }

    // [#6868 잔여] 구역 경계를 넘는 누름틀의 종료 마커를 잇는다 — 구역 하나를 파싱하는
    // 동안에는 앞 구역에서 열린 필드를 볼 수 없다.
    body_text::link_orphan_field_ends_across_sections(&mut sections);

    Ok(sections)
}

/// LenientCfbReader로 파싱 (FAT 검증 무시)
fn parse_hwp_with_lenient(
    lenient: cfb_reader::LenientCfbReader,
    _raw_data: &[u8],
    password: Option<&[u8]>,
    limits: Hwp5DocumentOpenDecompressionLimits,
) -> Result<Document, ParseError> {
    // FileHeader 파싱
    let header_data = lenient.read_file_header().map_err(ParseError::CfbError)?;
    let file_header = header::parse_file_header(&header_data).map_err(ParseError::HeaderError)?;
    validate_password_encryption(&file_header)?;

    let encrypted = file_header.flags.encrypted;
    if encrypted && password.is_none() {
        return Err(ParseError::EncryptedDocument);
    }

    let compressed = file_header.flags.compressed;
    let distribution = file_header.flags.distribution;
    let mut decompression_budget = Hwp5DocumentOpenDecompressionBudget::new(limits);

    // DocInfo 파싱 (비밀번호 암호 문서: 제한된 raw 읽기 → 복호화)
    let doc_info_output_limit = decompression_budget.stream_limit();
    let doc_info_raw_limit = decompression_budget.raw_stream_limit();
    let doc_info_data = if encrypted {
        let raw = lenient
            .read_stream_raw_limited("DocInfo", doc_info_raw_limit)
            .map_err(ParseError::CfbError)?;
        crypto::decrypt_password_protected_limited(
            &raw,
            password.unwrap(),
            compressed,
            doc_info_output_limit,
        )
        .map_err(ParseError::CryptoError)?
    } else {
        let raw = lenient
            .read_stream_raw_limited("DocInfo", doc_info_raw_limit)
            .map_err(ParseError::CfbError)?;
        cfb_reader::decode_stream_limited(raw, compressed, doc_info_output_limit)
            .map_err(ParseError::CfbError)?
    };
    decompression_budget
        .consume(doc_info_data.len())
        .map_err(ParseError::CfbError)?;
    let (mut doc_info, doc_properties) = parse_doc_info_stream(&doc_info_data, encrypted)?;
    doc_info::apply_v5024_strike_bits(&mut doc_info.char_shapes, &file_header.version);
    if let Ok(bytes) = lenient.read_stream_raw_limited(
        crate::model::native_font_program::HWP_STREAM,
        crate::model::native_font_program::MAX_BYTES,
    ) {
        crate::model::native_font_program::decode(&mut doc_info, &doc_info_data, &bytes);
    }
    doc_info.raw_stream = Some(doc_info_data);

    // BodyText 섹션별 파싱
    let section_count = lenient.section_count();
    let mut sections = Vec::new();

    for i in 0..section_count {
        let section_output_limit = decompression_budget.stream_limit();
        let section_raw_limit = decompression_budget.raw_stream_limit();
        let section_data = if distribution {
            let raw = lenient
                .read_viewtext_section_raw_limited(i, section_raw_limit)
                .map_err(ParseError::CfbError)?;
            crypto::decrypt_viewtext_section_limited(&raw, compressed, section_output_limit)
                .map_err(ParseError::CryptoError)?
        } else if encrypted {
            let rendered = decode_viewtext_paragraph_stream(
                lenient.read_viewtext_section_raw_limited(i, section_raw_limit),
                password.unwrap(),
                compressed,
                section_output_limit,
            )?;
            match rendered {
                Some(decoded) => decoded,
                None => {
                    let raw = lenient
                        .read_body_text_section_raw_limited(i, section_raw_limit)
                        .map_err(ParseError::CfbError)?;
                    crypto::decrypt_password_protected_limited(
                        &raw,
                        password.unwrap(),
                        compressed,
                        section_output_limit,
                    )
                    .map_err(ParseError::CryptoError)?
                }
            }
        } else {
            // [#5169] 비배포 문서라도 정상 복호되는 ViewText 가 있으면 우선한다(위 strict
            // 경로와 동일 규칙). 복호 실패·스텁이면 BodyText 로 폴백.
            let rendered = lenient
                .read_viewtext_section_raw_limited(i, section_raw_limit)
                .ok()
                .and_then(|raw| decode_rendered_viewtext(raw, compressed, section_output_limit));
            match rendered {
                Some(decoded) => decoded,
                None => {
                    let raw = lenient
                        .read_body_text_section_raw_limited(i, section_raw_limit)
                        .map_err(ParseError::CfbError)?;
                    cfb_reader::decode_stream_limited(raw, compressed, section_output_limit)
                        .map_err(ParseError::CfbError)?
                }
            }
        };
        decompression_budget
            .consume(section_data.len())
            .map_err(ParseError::CfbError)?;

        match parse_visible_section(&section_data, &mut sections, &doc_info) {
            Ok(mut section) => {
                section.raw_stream = Some(section_data);
                sections.push(section);
            }
            Err(
                e @ (body_text::BodyTextError::DrawingTextStructure(_)
                | body_text::BodyTextError::ChangeTrackingStructure(_)),
            ) => {
                return Err(ParseError::BodyTextError(e));
            }
            Err(e) => {
                eprintln!("경고: Section{} 파싱 실패 (lenient): {}", i, e);
                sections.push(crate::model::document::Section::default());
            }
        }
    }

    // [#6868 잔여] 구역 경계를 넘는 누름틀의 종료 마커 — strict 경로와 같다.
    body_text::link_orphan_field_ends_across_sections(&mut sections);

    // BinData 로드 시도
    let bin_data_content = load_bin_data_content_lenient(
        &lenient,
        &doc_info.bin_data_list,
        encrypted,
        compressed,
        password,
    );

    // Document 조립 (preview, extra_streams는 lenient에서 생략)
    let model_header = ModelFileHeader {
        version: ModelHwpVersion {
            major: file_header.version.major,
            minor: file_header.version.minor,
            build: file_header.version.build,
            revision: file_header.version.revision,
        },
        flags: file_header.flags.raw,
        compressed,
        encrypted: file_header.flags.encrypted,
        distribution,
        raw_data: Some(header_data),
    };

    let mut doc = Document {
        memo_parents: Vec::new(),
        header: model_header,
        doc_properties,
        doc_info,
        sections,
        preview: None,
        bin_data_content,
        extra_streams: Vec::new(),
        is_hwpx_variant: false,
        hwpx_aux_entries: Vec::new(),
        is_hwp3_variant: false,
        provenance: crate::model::provenance::SourceProvenance {
            format: crate::model::provenance::SourceFormat::Hwp5,
            hwp3_lineage: false,
            hwpx_lineage: false,
            hft_ascii_halfwidth_witnessed: false,
            stored_rows_before_hancom_2020: false,
        },
    };

    assign_auto_numbers(&mut doc);

    // [Task #554] HWP3 → HWP5 변환본 식별 + page_def margin_bottom 보정
    // [Task #1001] 변환본 식별 시 doc.is_hwp3_variant = true 설정
    // [#7035] lenient 경로도 정상 경로와 **같은 결정론 신호**를 쓴다 — 한쪽만 신호를
    // 갖고 다른 쪽이 비율만 보면 같은 문서가 파싱 경로에 따라 다른 조판 예산을 받는다.
    let summary_hwp3_era = [
        "/\u{0005}HwpSummaryInformation",
        "\u{0005}HwpSummaryInformation",
    ]
    .iter()
    .find_map(|path| lenient.read_stream(path).ok())
    .is_some_and(|raw| cfb_reader::hwp_summary_indicates_hwp3_era(&raw));
    apply_hwp3_origin_fixup(&mut doc, summary_hwp3_era);

    // [Task #873] BinData Link 타입 의 외부 file path 영역 Picture.external_path 전달.
    // 이후 model::document::populate_external_images_from_dir (Task #741) 가 같은
    // dir 영역 basename 매칭 영역 image 영역 자동 load.
    populate_link_image_paths(&mut doc);

    // 저장 LineSeg의 원점은 문단 간격을 포함한 실제 저장 결과다.
    // 계보에 맞춰 좌표를 다시 쓰지 않고 소비 단계에서 같은 저장 프레임을 사용한다.

    Ok(doc)
}

fn bin_data_should_compress(
    compression: crate::model::bin_data::BinDataCompression,
    document_compressed: bool,
) -> bool {
    use crate::model::bin_data::BinDataCompression;
    match compression {
        BinDataCompression::Default => document_compressed,
        BinDataCompression::Compress => true,
        BinDataCompression::NoCompress => false,
    }
}

/// BinData 스트림의 실제 압축 여부를 판정한다.
///
/// 일반 HWP는 `HWPTAG_BIN_DATA`의 개별 압축 속성을 따른다. 반면 한컴이
/// EncryptVersion 4로 저장한 암호 문서는 `NoCompress` BinData도 문서 전역
/// `compressed` 플래그에 따라 압축한 뒤 암호화한다. 따라서 암호 문서에서 개별
/// 속성을 따르면 복호화까지만 된 raw-deflate 바이트를 이미지로 오인하게 된다.
fn bin_data_stream_is_compressed(
    compression: crate::model::bin_data::BinDataCompression,
    document_compressed: bool,
    encrypted: bool,
) -> bool {
    if encrypted {
        document_compressed
    } else {
        bin_data_should_compress(compression, document_compressed)
    }
}

fn decode_encrypted_stream_limited(
    raw: &[u8],
    password: &[u8],
    compressed: bool,
    max_bytes: usize,
) -> Option<Vec<u8>> {
    crypto::decrypt_password_protected_limited(raw, password, compressed, max_bytes).ok()
}

/// LenientCfbReader로 BinData 로드
fn load_bin_data_content_lenient(
    lenient: &cfb_reader::LenientCfbReader,
    bin_data_list: &[crate::model::bin_data::BinData],
    encrypted: bool,
    compressed: bool,
    password: Option<&[u8]>,
) -> Vec<BinDataContent> {
    use crate::model::bin_data::BinDataType;

    let mut contents = Vec::new();

    for bd in bin_data_list.iter() {
        let is_storage = match bd.data_type {
            BinDataType::Embedding => false,
            BinDataType::Storage => true,
            BinDataType::Link => {
                // 연결 레코드도 순번 자리를 지켜야 뒤 그림이 제 항목을 가리킨다.
                contents.push(crate::model::bin_data::hwp5_link_slot());
                continue;
            }
        };

        let ext = if is_storage {
            bd.extension.as_deref().unwrap_or("OLE")
        } else {
            bd.extension.as_deref().unwrap_or("dat")
        };
        let storage_name = format!("BIN{:04X}.{}", bd.storage_id, ext);
        let stream_compressed =
            bin_data_stream_is_compressed(bd.compression, compressed, encrypted);

        match lenient.read_stream(&format!("/BinData/{}", storage_name)) {
            Ok(data) => {
                let mut decompressed = if encrypted {
                    let pwd = password.unwrap();
                    match crypto::decrypt_password_protected_limited(
                        &data,
                        pwd,
                        stream_compressed,
                        MAX_PASSWORD_PROTECTED_BIN_DATA_OUTPUT_BYTES,
                    ) {
                        Ok(d) => d,
                        Err(e) => {
                            eprintln!(
                                "경고: BinData '{}' 복호화 실패 (lenient): {}",
                                storage_name, e
                            );
                            continue;
                        }
                    }
                } else {
                    match cfb_reader::decompress_stream(&data) {
                        Ok(d) => d,
                        Err(_) => data,
                    }
                };

                // Task #195 단계 6: OLE Storage는 CFB 매직 바로 앞의 4-byte size prefix 스킵
                if is_storage && decompressed.len() >= 12 {
                    let cfb_magic = [0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1];
                    if decompressed[..8] != cfb_magic && decompressed[4..12] == cfb_magic {
                        decompressed.drain(..4);
                    }
                }

                contents.push(BinDataContent {
                    id: bd.storage_id,
                    data: decompressed.into(),
                    extension: ext.to_string(),
                });
            }
            Err(e) => {
                eprintln!(
                    "경고: BinData '{}' 로드 실패 (lenient): {}",
                    storage_name, e
                );
            }
        }
    }

    contents
}

/// [Task #873] BinData Link 타입의 외부 file path 를 Picture.image_attr.external_path
/// 로 전달. 모든 포맷 (HWP5/HWPX) 공통 — HWP3 는 파서 내부에서 직접 설정 (Task #741).
///
/// HWP5 의 BinDataType::Link entry, HWPX 의 isEmbeded="0" item 이 abs_path/rel_path
/// 보유. 본 함수는 Picture.bin_data_id 로 BinData entry lookup → Link 인 경우
/// external_path 설정. 이후 populate_external_images_from_dir (model/document.rs) 가
/// HWP 파일 디렉토리에서 basename 매칭으로 실제 image 로드.
pub(crate) fn populate_link_image_paths(doc: &mut Document) {
    use crate::model::bin_data::BinDataType;
    use crate::model::control::Control;
    use crate::model::shape::ShapeObject;

    let bin_data = doc.doc_info.bin_data_list.clone();
    for section in &mut doc.sections {
        for para in &mut section.paragraphs {
            for ctrl in &mut para.controls {
                let pic = match ctrl {
                    Control::Picture(p) => p,
                    Control::Shape(s) => match s.as_mut() {
                        ShapeObject::Picture(p) => p,
                        _ => continue,
                    },
                    _ => continue,
                };
                if pic.image_attr.external_path.is_some() {
                    continue;
                }
                let bin_idx = (pic.image_attr.bin_data_id as usize).saturating_sub(1);
                if let Some(bd) = bin_data.get(bin_idx) {
                    if matches!(bd.data_type, BinDataType::Link) {
                        let path = bd
                            .abs_path
                            .clone()
                            .filter(|p| !p.is_empty())
                            .or_else(|| bd.rel_path.clone().filter(|p| !p.is_empty()));
                        if let Some(p) = path {
                            pic.image_attr.external_path = Some(p);
                        }
                    }
                }
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Trait 추상화: DocumentParser
// ---------------------------------------------------------------------------

/// 문서 파서 trait — 바이트 데이터를 Document IR로 변환
pub trait DocumentParser {
    fn parse(&self, data: &[u8]) -> Result<Document, ParseError>;
}

/// HWP 5.0 바이너리 파서
pub struct HwpParser;

impl DocumentParser for HwpParser {
    fn parse(&self, data: &[u8]) -> Result<Document, ParseError> {
        parse_hwp(data)
    }
}

/// HWPX (XML/ZIP) 파서
pub struct HwpxParser;

impl DocumentParser for HwpxParser {
    fn parse(&self, data: &[u8]) -> Result<Document, ParseError> {
        hwpx::parse_hwpx(data).map_err(ParseError::from)
    }
}

/// HWP 3.0 파서
pub struct Hwp3Parser;

impl DocumentParser for Hwp3Parser {
    fn parse(&self, data: &[u8]) -> Result<Document, ParseError> {
        hwp3::parse_hwp3(data).map_err(ParseError::from)
    }
}

/// Standalone HWPML XML parser.
pub struct HmlParser;

impl DocumentParser for HmlParser {
    fn parse(&self, data: &[u8]) -> Result<Document, ParseError> {
        hml::parse_hml(data)
            .map(|result| result.document)
            .map_err(ParseError::from)
    }
}

/// HML 입력에서만 제공되는 열기 메타데이터와 손실 진단.
pub struct HmlImportMetadata {
    pub hwpml_version: Option<String>,
    pub sub_version: Option<String>,
    pub style: Option<String>,
    pub encoding: hml::HmlEncoding,
    pub resource_count: usize,
    pub warnings: Vec<hml::HmlWarning>,
    pub preserved_fragments: Vec<hml::PreservedFragment>,
}

/// 공통 IR과 입력 포맷 전용 열기 메타데이터를 분리해 전달한다.
pub struct ParsedDocument {
    pub document: Document,
    pub hml_metadata: Option<HmlImportMetadata>,
    #[cfg(feature = "pdf-import")]
    pub pdf_metadata: Option<pdf::PdfImportMetadata>,
}

/// 선택한 PDF 쪽을 공통 IR과 원본 쪽 대응 메타데이터로 가져온다.
///
/// 자동 감지 경로와 같은 provenance 봉인을 사용한다. PDF로 다시 저장하는 API가 아니다.
#[cfg(feature = "pdf-import")]
pub fn parse_pdf_with_metadata(
    data: &[u8],
    options: &pdf::PdfImportOptions,
) -> Result<ParsedDocument, ParseError> {
    parse_pdf_with_metadata_and_policy(data, options, pdf::PdfImportPolicy::default())
}

/// Explicit policy with the same provenance sealing as format auto-detection.
#[cfg(feature = "pdf-import")]
pub fn parse_pdf_with_metadata_and_policy(
    data: &[u8],
    options: &pdf::PdfImportOptions,
    policy: pdf::PdfImportPolicy,
) -> Result<ParsedDocument, ParseError> {
    parse_pdf_unsealed_with_policy(data, options, policy).map(seal_parsed_document)
}

#[cfg(feature = "pdf-import")]
pub(crate) fn parse_pdf_with_metadata_and_request(
    data: &[u8],
    options: &pdf::PdfImportOptions,
    policy: pdf::PdfImportPolicy,
    request: std::sync::Arc<pdf_oxide::import_limits::ImportBudget>,
    progress: &mut dyn FnMut(pdf::PdfImportProgress) -> Result<(), pdf::PdfImportError>,
) -> Result<ParsedDocument, ParseError> {
    let result = pdf::parse_pdf_with_request_and_progress(data, options, policy, request, progress)
        .map_err(ParseError::PdfError)?;
    Ok(seal_parsed_document(ParsedDocument {
        document: result.document,
        hml_metadata: None,
        pdf_metadata: Some(result.metadata),
    }))
}

#[cfg(feature = "pdf-import")]
fn parse_pdf_unsealed(
    data: &[u8],
    options: &pdf::PdfImportOptions,
) -> Result<ParsedDocument, ParseError> {
    parse_pdf_unsealed_with_policy(data, options, pdf::PdfImportPolicy::default())
}

#[cfg(feature = "pdf-import")]
fn parse_pdf_unsealed_with_policy(
    data: &[u8],
    options: &pdf::PdfImportOptions,
    policy: pdf::PdfImportPolicy,
) -> Result<ParsedDocument, ParseError> {
    let result = pdf::parse_pdf_with_policy(data, options, policy).map_err(ParseError::PdfError)?;
    Ok(ParsedDocument {
        document: result.document,
        hml_metadata: None,
        pdf_metadata: Some(result.metadata),
    })
}

#[cfg(feature = "pdf-import")]
pub(crate) fn parse_pdf_editor_hwpx(
    data: &[u8],
    reservation: std::sync::Arc<dyn crate::storage::Reservation>,
) -> Result<ParsedDocument, ParseError> {
    hwpx::parse_hwpx_with_reservation(data, Some(reservation))
        .map_err(ParseError::from)
        .map(without_hml_metadata)
        .map(seal_parsed_document)
}

/// 포맷 자동 감지 후 공통 IR과 입력 메타데이터를 파싱한다.
pub fn parse_document_with_metadata(data: &[u8]) -> Result<ParsedDocument, ParseError> {
    parse_document_inner(data, None)
}

/// 포맷 자동 감지 후 비밀번호와 함께 파싱한다.
///
/// HWP5 EncryptVersion 4, 압축 HWP3, ODF AES-256-CBC HWPX 비밀번호 암호 문서를 연다.
/// 비밀번호가 틀리면 암호 불일치/손상 오류를 반환한다. 암호화되지 않은 HWPX는 기존
/// 파서 결과를 그대로 반환한다.
pub fn parse_document_with_metadata_password(
    data: &[u8],
    password: &[u8],
) -> Result<ParsedDocument, ParseError> {
    parse_document_inner(data, Some(password))
}

fn parse_document_inner(
    data: &[u8],
    password: Option<&[u8]>,
) -> Result<ParsedDocument, ParseError> {
    parse_document_inner_unsealed(data, password).map(seal_parsed_document)
}

/// `DocumentCore` 로 여는 경로 전용 — DocInfo 만 봉인하고 본문 봉인은 호출자에게 맡긴다.
///
/// `DocumentCore::from_parsed_document` 는 로드 픽스업과 첫 paginate 뒤 본문을 다시
/// 봉인하고, 그 사이에는 본문 봉인 값을 읽지 않는다(편집 신호는 봉인 유무와
/// `raw_stream` 유무만 보는데 로드 픽스업은 `raw_stream` 을 지우지 않는다). 파서 말미의
/// 본문 봉인은 덮어써질 뿐이므로 본문 전체 직렬화·해시를 한 번 줄인다.
pub(crate) fn parse_document_for_core(
    data: &[u8],
    password: Option<&[u8]>,
) -> Result<ParsedDocument, ParseError> {
    parse_document_inner_unsealed(data, password).map(seal_parsed_doc_info)
}

fn seal_parsed_doc_info(mut parsed: ParsedDocument) -> ParsedDocument {
    // [#4493] 파싱과 모든 load fixup 이 끝난 마지막 지점에서 DocInfo raw 출처를
    // 봉인한다 — 이보다 앞(포맷별 파서 내부)에서 봉인하면 HWP3-변환본 spacing
    // 반감 같은 로드 보정이 봉인을 깨서, 무변경 문서의 원본 바이트 통과가 죽는다.
    // raw 캐시가 없는 포맷(HWPX/HWP3/HML)에서는 no-op.
    parsed
        .document
        .doc_info
        .seal_raw_provenance(&parsed.document.doc_properties);
    parsed
}

fn seal_parsed_document(parsed: ParsedDocument) -> ParsedDocument {
    let mut parsed = seal_parsed_doc_info(parsed);
    // [#4488/#4495] 본문 Section raw_stream 과 하위 컨트롤 raw 레코드도 같은
    // 지점에서 봉인한다. DocumentCore 로 열리는 경로는 이 봉인을 건너뛰고
    // (`parse_document_for_core`) from_bytes 의 로드 픽스업 뒤에 한 번 봉인한다.
    parsed.document.seal_body_raw_provenance();
    parsed
}

fn parse_document_inner_unsealed(
    data: &[u8],
    password: Option<&[u8]>,
) -> Result<ParsedDocument, ParseError> {
    let open_policy = document_open_decompression_policy();
    match detect_format(data) {
        FileFormat::Hwp => {
            parse_hwp_inner_with_limits(data, password, open_policy.hwp5).map(without_hml_metadata)
        }
        FileFormat::Hwpx => match password {
            Some(password) => hwpx::parse_hwpx_with_password(data, password),
            None => hwpx::parse_hwpx(data),
        }
        .map_err(ParseError::from)
        .map(without_hml_metadata),
        FileFormat::Hwp3 => match password {
            Some(password) => hwp3::parse_hwp3_with_open_body_limit_and_password(
                data,
                password,
                open_policy.hwp3_max_body_output_bytes,
            ),
            None => {
                hwp3::parse_hwp3_with_open_body_limit(data, open_policy.hwp3_max_body_output_bytes)
            }
        }
        .map_err(ParseError::from)
        .map(without_hml_metadata),
        FileFormat::Hml => {
            let result = hml::parse_hml(data).map_err(ParseError::from)?;
            Ok(ParsedDocument {
                document: result.document,
                hml_metadata: Some(HmlImportMetadata {
                    hwpml_version: result.metadata.hwpml_version,
                    sub_version: result.metadata.sub_version,
                    style: result.metadata.style,
                    encoding: result.metadata.encoding,
                    resource_count: result.metadata.resource_count,
                    warnings: result.warnings,
                    preserved_fragments: result.preserved_fragments,
                }),
                #[cfg(feature = "pdf-import")]
                pdf_metadata: None,
            })
        }
        #[cfg(feature = "pdf-import")]
        FileFormat::Pdf => parse_pdf_unsealed(
            data,
            &pdf::PdfImportOptions::with_password(password).map_err(ParseError::PdfError)?,
        ),
        #[cfg(not(feature = "pdf-import"))]
        FileFormat::Pdf => Err(ParseError::UnsupportedFormat {
            code: "PDF_IMPORT_DISABLED",
            format: "PDF",
            hint: PDF_IMPORT_DISABLED_HINT,
        }),
        FileFormat::DrmProtected => Err(ParseError::UnsupportedFormat {
            code: DRM_PROTECTED_CODE,
            format: drm_format_name(data),
            hint: DRM_PROTECTED_HINT,
        }),
        FileFormat::Empty => Err(ParseError::UnsupportedFormat {
            code: EMPTY_FILE_CODE,
            format: "빈 파일",
            hint: EMPTY_FILE_HINT,
        }),
        FileFormat::Unknown => Err(ParseError::UnsupportedFormat {
            code: UNSUPPORTED_FILE_FORMAT_CODE,
            format: "알 수 없는 파일 형식",
            hint: SUPPORTED_FORMATS_HINT,
        }),
    }
}

fn without_hml_metadata(document: Document) -> ParsedDocument {
    ParsedDocument {
        document,
        hml_metadata: None,
        #[cfg(feature = "pdf-import")]
        pdf_metadata: None,
    }
}

/// 포맷 자동 감지 후 공통 IR만 반환하는 호환 진입점.
pub fn parse_document(data: &[u8]) -> Result<Document, ParseError> {
    parse_document_with_metadata(data).map(|parsed| parsed.document)
}

/// 포맷 자동 감지 후 비밀번호와 함께 공통 IR만 반환한다.
///
/// 비암호 문서와 다른 지원 포맷에서는 비밀번호를 무시한다. 암호화된 HWP5의
/// EncryptVersion이 4가 아니면 `UnsupportedScheme`을 반환하며, HWP3는 압축
/// 암호 본문, HWPX는 ODF AES-256-CBC/PBKDF2 패키지를 지원한다.
pub fn parse_document_with_password(data: &[u8], password: &[u8]) -> Result<Document, ParseError> {
    parse_document_with_metadata_password(data, password).map(|parsed| parsed.document)
}

/// DRM 벤더 시그니처로 사람이 읽을 이름을 고른다 (Issue #1982).
fn drm_format_name(data: &[u8]) -> &'static str {
    if data.starts_with(FASOO_DRM_SIG) {
        "DRM 보호 문서 (Fasoo)"
    } else if data.starts_with(SCDSA_SIG) {
        "DRM 보호 문서 (SoftCamp SCDSA)"
    } else {
        "DRM 보호 문서"
    }
}

/// 미리보기 데이터 추출 (PrvImage, PrvText)
fn extract_preview(cfb: &mut cfb_reader::CfbReader, max_thumbnail_bytes: usize) -> Option<Preview> {
    let image_data = cfb.read_preview_image_limited(max_thumbnail_bytes);
    let text = cfb.read_preview_text();

    // 둘 다 없으면 None 반환
    if image_data.is_none() && text.is_none() {
        return None;
    }

    let image = image_data.map(|data| {
        let format = detect_image_format(&data);
        PreviewImage { format, data }
    });

    Some(Preview { image, text })
}

/// HWP/HWPX 파일에서 썸네일 이미지만 경량 추출 (전체 파싱 없이)
///
/// - HWP (CFB): `/PrvImage` 스트림에서 추출
/// - HWPX (ZIP): `Preview/PrvImage.png` 엔트리에서 추출
pub fn extract_thumbnail_only(data: &[u8]) -> Option<ThumbnailResult> {
    let image_data = if detect_format(data) == FileFormat::Hwpx {
        // HWPX: ZIP 컨테이너에서 Preview/PrvImage.png 읽기
        extract_thumbnail_from_hwpx(data, MAX_THUMBNAIL_BYTES)?
    } else {
        // HWP: CFB 컨테이너에서 /PrvImage 스트림 읽기
        let mut cfb = cfb_reader::CfbReader::open(data).ok()?;
        cfb.read_preview_image_limited(MAX_THUMBNAIL_BYTES)?
    };
    let format = detect_image_format(&image_data);

    // 이미지 크기 추출
    let (width, height) = match format {
        PreviewImageFormat::Png if image_data.len() >= 24 => {
            // PNG IHDR: offset 16 = width (u32 BE), offset 20 = height (u32 BE)
            let w = u32::from_be_bytes([
                image_data[16],
                image_data[17],
                image_data[18],
                image_data[19],
            ]);
            let h = u32::from_be_bytes([
                image_data[20],
                image_data[21],
                image_data[22],
                image_data[23],
            ]);
            (w, h)
        }
        PreviewImageFormat::Bmp if image_data.len() >= 26 => {
            // BMP 헤더: offset 18 = width (i32 LE), offset 22 = height (i32 LE)
            let w = i32::from_le_bytes([
                image_data[18],
                image_data[19],
                image_data[20],
                image_data[21],
            ]);
            let h = i32::from_le_bytes([
                image_data[22],
                image_data[23],
                image_data[24],
                image_data[25],
            ]);
            (w.unsigned_abs(), h.unsigned_abs())
        }
        PreviewImageFormat::Gif if image_data.len() >= 10 => {
            let w = u16::from_le_bytes([image_data[6], image_data[7]]) as u32;
            let h = u16::from_le_bytes([image_data[8], image_data[9]]) as u32;
            (w, h)
        }
        _ => (0, 0),
    };

    let output_format = match format {
        PreviewImageFormat::Png => "png",
        PreviewImageFormat::Bmp => "bmp",
        PreviewImageFormat::Gif => "gif",
        PreviewImageFormat::Unknown => "unknown",
    };

    Some(ThumbnailResult {
        format: output_format.to_string(),
        data: image_data,
        width,
        height,
    })
}

/// 미리보기 이미지 하나의 최대 압축 해제 크기.
///
/// HWP/HWPX 문서 열기와 브라우저 썸네일 소비자가 선택하는 10 MiB 상한이다.
pub const MAX_THUMBNAIL_BYTES: usize = 10 * 1024 * 1024;

fn read_thumbnail_limited<R: std::io::Read>(
    reader: &mut R,
    expected_bytes: usize,
    max_bytes: usize,
) -> Option<Vec<u8>> {
    if expected_bytes == 0 || expected_bytes > max_bytes {
        return None;
    }

    let mut buf = Vec::new();
    let mut limited = std::io::Read::take(&mut *reader, (expected_bytes as u64).saturating_add(1));
    std::io::Read::read_to_end(&mut limited, &mut buf).ok()?;
    (buf.len() == expected_bytes).then_some(buf)
}

/// HWPX(ZIP)에서 Preview/PrvImage.png 추출
fn extract_thumbnail_from_hwpx(data: &[u8], max_bytes: usize) -> Option<Vec<u8>> {
    let cursor = std::io::Cursor::new(data);
    let mut archive = zip::ZipArchive::new(cursor).ok()?;

    // Preview/PrvImage.png 또는 Preview/PrvImage.* 탐색
    let entry_name = (0..archive.len()).find_map(|i| {
        let file = archive.by_index(i).ok()?;
        let name = file.name().ok()?.into_owned();
        if name.starts_with("Preview/PrvImage") {
            Some(name)
        } else {
            None
        }
    })?;

    let mut file = archive.by_name(&entry_name).ok()?;
    let declared_size = usize::try_from(file.size()).ok()?;
    read_thumbnail_limited(&mut file, declared_size, max_bytes)
}

/// 썸네일 추출 결과
#[derive(Debug, Clone)]
pub struct ThumbnailResult {
    /// 출력 포맷 ("png", "gif", "unknown")
    pub format: String,
    /// 이미지 바이너리 데이터 (BMP는 PNG로 변환됨)
    pub data: Vec<u8>,
    /// 이미지 너비 (px)
    pub width: u32,
    /// 이미지 높이 (px)
    pub height: u32,
}

/// 이미지 포맷 감지 (BMP/GIF/PNG)
fn detect_image_format(data: &[u8]) -> PreviewImageFormat {
    if data.len() >= 8 && &data[..8] == b"\x89PNG\r\n\x1a\n" {
        PreviewImageFormat::Png
    } else if data.len() >= 2 && data[0] == 0x42 && data[1] == 0x4D {
        PreviewImageFormat::Bmp
    } else if data.len() >= 3 && &data[..3] == b"GIF" {
        PreviewImageFormat::Gif
    } else {
        PreviewImageFormat::Unknown
    }
}

/// 파서가 모델링하지 않는 CFB 스트림을 수집한다.
///
/// FileHeader, DocInfo, BodyText/Section*, BinData/*, PrvImage, PrvText는
/// 이미 별도로 파싱되므로 제외한다.
fn collect_extra_streams(
    cfb: &mut cfb_reader::CfbReader,
    bin_data_list: &[crate::model::bin_data::BinData],
    bin_data_content: &[BinDataContent],
    encrypted: bool,
    password: Option<&[u8]>,
) -> Vec<(String, Vec<u8>)> {
    let all_streams = cfb.list_streams();
    let mut extra = Vec::new();

    // [Task #1554] 직렬화기(`cfb_writer`)가 `bin_data_content` 로부터 재생성할
    // /BinData 스트림 경로 집합. 직렬화기와 동일한 명명 규칙(`find_bin_data_info_with_compress`)
    // 을 미러링하여 계산한다. 이 집합에 들어가지 않는 /BinData 스트림은 대응 BinData
    // 레코드가 없는 "고아 스트림"(예: img-start-001 의 20개 BIN, interview.hwp 의 BIN0001)
    // 이며, 그대로 두면 저장 시 통째 드롭된다. extra_streams 로 원본 바이트를 보존한다.
    // CFB 디렉터리 이름은 대소문자를 가리지 않는다(읽기도 같은 규칙으로 찾는다). DocInfo
    // 확장자 `JPG` 와 저장 스트림 `BIN0001.jpg` 는 같은 항목이므로 대문자로 맞춰 비교한다.
    let emitted_bin_paths: std::collections::HashSet<String> = bin_data_content
        .iter()
        .map(|c| {
            let (storage_id, ext) = serialized_bin_name(bin_data_list, c);
            format!("/BinData/BIN{:04X}.{}", storage_id, ext).to_uppercase()
        })
        .collect();

    for path in &all_streams {
        // 이미 파싱된 스트림은 제외
        if path == "/FileHeader"
            || path == "/DocInfo"
            || path == crate::model::native_font_program::HWP_STREAM
            || path.starts_with("/BodyText/")
            || path.starts_with("/ViewText/")
            || path == "/PrvImage"
            || path == "/PrvText"
        {
            continue;
        }

        // /BinData 는 직렬화기가 재생성하는 스트림만 제외하고, 고아 스트림은 보존
        if path.starts_with("/BinData/") && emitted_bin_paths.contains(&path.to_uppercase()) {
            continue;
        }

        // 비밀번호 암호화 대상 중 모델링하지 않는 스트림은 평문 raw 상태로 보존한다.
        // 직렬화기는 암호화 플래그를 제거하므로 암호문을 그대로 보존하면 Scripts와
        // 고아 BinData가 읽을 수 없는 상태로 저장된다.
        if let Ok(mut data) = cfb.read_stream_raw(path) {
            if encrypted && (path.starts_with("/Scripts/") || path.starts_with("/BinData/")) {
                if let Some(password) = password {
                    data = crypto::decrypt_password_stream(&data, password);
                }
            }
            extra.push((path.clone(), data));
        }
    }

    extra
}

/// 직렬화기가 `BinDataContent` 에 대해 생성할 스트림 이름의 (storage_id, ext) 계산.
///
/// `cfb_writer::find_bin_data_info_with_compress` 의 명명 규칙(매칭 레코드 우선,
/// 없으면 content 자체값)을 미러링한다. extra_streams 의 고아 /BinData 판별 전용.
fn serialized_bin_name<'a>(
    bin_data_list: &'a [crate::model::bin_data::BinData],
    content: &'a BinDataContent,
) -> (u16, &'a str) {
    use crate::model::bin_data::BinDataType;
    for bd in bin_data_list {
        if matches!(bd.data_type, BinDataType::Embedding | BinDataType::Storage)
            && bd.storage_id == content.id
        {
            return (bd.storage_id, bd.extension.as_deref().unwrap_or("dat"));
        }
    }
    (content.id, &content.extension)
}

/// BinData 스토리지에서 이미지 데이터 로드
///
/// bin_data_list의 각 항목에 대해 CFB 스토리지에서 바이너리 데이터를 읽어온다.
/// Embedding 타입인 경우에만 로드하며, 압축된 경우 해제한다.
/// [Task #2263] HWP5 CFB 원본을 보유하고 요청 시점에 BinData 스트림을 압축 해제한다.
///
/// 파싱 시점에 모든 내장 이미지를 풀어 IR 에 상주시키면 원본 파일 크기의
/// 수십 배 메모리를 쓰게 된다. CFB 안의 BinData 스트림은 zlib 압축 상태이므로,
/// 원본 컨테이너만 들고 있다가 실제로 렌더·직렬화되는 항목만 그때 푼다.
struct Hwp5BinResolver {
    cfb: std::sync::Mutex<cfb_reader::CfbReader>,
    /// 선두 4-byte size prefix 정규화가 필요한 OLE Storage 스트림명
    ole_streams: std::collections::HashSet<String>,
    /// 스트림별 압축 여부. HWPTAG_BIN_DATA 속성이 문서 전역 플래그보다 우선한다.
    compressed_streams: std::collections::HashMap<String, bool>,
    /// 비밀번호 암호 문서 여부 (FileHeader encrypted 플래그)
    encrypted: bool,
    /// 비밀번호 바이트. 지연 로딩이 파싱 이후 렌더 시점에 스트림을 읽으므로
    /// 리졸버가 바이트를 소유해야 한다.
    password: Option<Vec<u8>>,
}

impl std::fmt::Debug for Hwp5BinResolver {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Hwp5BinResolver")
            .field("ole_streams", &self.ole_streams.len())
            .field("compressed_streams", &self.compressed_streams.len())
            .field("encrypted", &self.encrypted)
            .finish()
    }
}

impl Hwp5BinResolver {
    /// raw BinData 바이트를 복호화(암호 문서)+압축 해제한다.
    /// 비암호 문서에서 압축 해제 실패 시 원본을 그대로 반환한다(기존 동작).
    fn try_decode(&self, key: &str, raw: &[u8]) -> Option<Vec<u8>> {
        if self.encrypted {
            let pwd = self.password.as_deref().unwrap_or(&[]);
            let compressed = self.compressed_streams.get(key).copied().unwrap_or(false);
            crypto::decrypt_password_protected_limited(
                raw,
                pwd,
                compressed,
                MAX_PASSWORD_PROTECTED_BIN_DATA_OUTPUT_BYTES,
            )
            .ok()
        } else {
            match cfb_reader::decompress_stream(raw) {
                Ok(d) => Some(d),
                Err(_) => Some(raw.to_vec()),
            }
        }
    }
}

impl crate::model::bin_data::BinDataResolver for Hwp5BinResolver {
    fn resolve(&self, key: &str) -> Vec<u8> {
        let mut cfb = match self.cfb.lock() {
            Ok(c) => c,
            Err(poisoned) => poisoned.into_inner(),
        };
        let raw = match cfb.read_bin_data(key) {
            Ok(d) => d,
            Err(e) => {
                eprintln!("경고: BinData '{}' 로드 실패: {}", key, e);
                return Vec::new();
            }
        };

        let mut decompressed = match self.try_decode(key, &raw) {
            Some(d) => d,
            None => {
                eprintln!(
                    "경고: BinData '{}' 복호화 실패 (비밀번호 불일치 또는 손상)",
                    key
                );
                return Vec::new();
            }
        };

        // Task #195 단계 6: OLE Storage는 해제 후 선두 4바이트 size prefix를 스킵하여
        // 내부 CFB(`d0cf11e0...`) 시작 바이트부터 노출한다.
        if self.ole_streams.contains(key) && decompressed.len() >= 12 {
            let cfb_magic = [0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1];
            if decompressed[..8] != cfb_magic && decompressed[4..12] == cfb_magic {
                decompressed.drain(..4);
            }
        }

        decompressed
    }

    fn resolve_limited(&self, key: &str, max_bytes: usize) -> Option<Vec<u8>> {
        let mut cfb = match self.cfb.lock() {
            Ok(cfb) => cfb,
            Err(poisoned) => poisoned.into_inner(),
        };
        // 암호 문서는 블록 단위 복호화가 전체 스트림을 요구하므로 제한 없이 읽는다.
        let raw = if self.encrypted {
            match cfb.read_bin_data(key) {
                Ok(data) => data,
                Err(error) => {
                    eprintln!("경고: BinData '{}' bounded 로드 실패: {}", key, error);
                    return None;
                }
            }
        } else {
            match cfb.read_bin_data_limited(key, max_bytes) {
                Ok(data) => data,
                Err(error) => {
                    eprintln!("경고: BinData '{}' bounded 로드 실패: {}", key, error);
                    return None;
                }
            }
        };

        let mut bytes = if self.encrypted {
            let password = self.password.as_deref().unwrap_or(&[]);
            let compressed = self.compressed_streams.get(key).copied().unwrap_or(false);
            decode_encrypted_stream_limited(&raw, password, compressed, max_bytes)?
        } else {
            match cfb_reader::decompress_stream_limited(&raw, max_bytes) {
                Ok(data) => data,
                Err(cfb_reader::CfbError::LimitExceeded(_)) => return None,
                Err(_) => raw,
            }
        };
        if self.ole_streams.contains(key) && bytes.len() >= 12 {
            let cfb_magic = [0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1];
            if bytes[..8] != cfb_magic && bytes[4..12] == cfb_magic {
                bytes.drain(..4);
            }
        }
        (bytes.len() <= max_bytes).then_some(bytes)
    }

    /// [#2550] 저장된 형태 그대로의 바이트 — 압축 해제 없이 반환한다.
    ///
    /// 복호화는 크기 1:1 변환이라 deflate bomb 위험이 없으므로 수행한다. 반환
    /// 바이트는 원본 스트림과 같은 압축 상태이며, OLE size prefix 도 (압축 안에)
    /// 그대로 들어 있다 — 저장 경로가 이 바이트를 그대로 기록하면 왕복 무손실이다.
    fn resolve_raw(&self, key: &str) -> Option<crate::model::bin_data::StoredBinData> {
        let raw = {
            let mut cfb = match self.cfb.lock() {
                Ok(cfb) => cfb,
                Err(poisoned) => poisoned.into_inner(),
            };
            match cfb.read_bin_data(key) {
                Ok(data) => data,
                Err(error) => {
                    eprintln!("경고: BinData '{}' 원본 로드 실패: {}", key, error);
                    return None;
                }
            }
        };
        let bytes = if self.encrypted {
            let password = self.password.as_deref().unwrap_or(&[]);
            // `decrypt_hwp5_stream` 은 입력 길이로 truncate 하므로 크기가 보존된다.
            crypto::decrypt_password_stream(&raw, password)
        } else {
            raw
        };
        Some(crate::model::bin_data::StoredBinData {
            compressed: self.compressed_streams.get(key).copied().unwrap_or(false),
            bytes,
        })
    }

    /// [#2550] `resolve().len()` 의 bounded 미러 — 출력을 materialize 하지 않는다.
    ///
    /// 상한(비암호 [`MAX_BIN_DATA_BYTES`](crate::model::bin_data::MAX_BIN_DATA_BYTES),
    /// 암호 `MAX_PASSWORD_PROTECTED_BIN_DATA_OUTPUT_BYTES`) 초과 항목은 bounded 로드 경로가
    /// placeholder 로 접으므로 길이도 0 으로 보고한다.
    fn resolved_len(&self, key: &str) -> usize {
        let raw = {
            let mut cfb = match self.cfb.lock() {
                Ok(cfb) => cfb,
                Err(poisoned) => poisoned.into_inner(),
            };
            match cfb.read_bin_data(key) {
                Ok(data) => data,
                Err(_) => return 0,
            }
        };

        let stream_compressed = self.compressed_streams.get(key).copied().unwrap_or(false);
        let (plain, len) = if self.encrypted {
            // 복호화(1:1) 후 압축 여부에 따라 길이만 센다. resolve() 는 오류·상한
            // 초과 시 빈 값을 반환하므로 길이도 0 이다.
            let password = self.password.as_deref().unwrap_or(&[]);
            let plain = crypto::decrypt_password_stream(&raw, password);
            let len = if stream_compressed {
                match cfb_reader::decompressed_len_capped(
                    &plain,
                    MAX_PASSWORD_PROTECTED_BIN_DATA_OUTPUT_BYTES,
                ) {
                    Ok(len) => len,
                    Err(_) => return 0,
                }
            } else if plain.len() > MAX_PASSWORD_PROTECTED_BIN_DATA_OUTPUT_BYTES {
                return 0;
            } else {
                plain.len()
            };
            (plain, len)
        } else {
            let len = match cfb_reader::decompressed_len_capped(
                &raw,
                crate::model::bin_data::MAX_BIN_DATA_BYTES,
            ) {
                Ok(len) => len,
                Err(cfb_reader::CfbError::LimitExceeded(_)) => return 0,
                // 해제 실패 시 원본 바이트를 그대로 노출하는 resolve() 를 미러링.
                Err(_) => raw.len(),
            };
            (raw, len)
        };

        // resolve() 의 OLE size prefix strip 을 선두 12바이트만 해제해 미러링한다.
        if len >= 12 && self.ole_streams.contains(key) {
            let head = if self.encrypted && !stream_compressed {
                plain.get(..12).map(<[u8]>::to_vec).unwrap_or_default()
            } else {
                cfb_reader::decompress_stream_prefix(&plain, 12)
                    .unwrap_or_else(|_| plain.get(..12).map(<[u8]>::to_vec).unwrap_or_default())
            };
            let cfb_magic = [0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1];
            if head.len() >= 12 && head[..8] != cfb_magic && head[4..12] == cfb_magic {
                return len - 4;
            }
        }
        len
    }

    /// [#2550] 상한 초과 항목은 placeholder(빈 값) 의미이므로 길이 0 판정을 공유한다.
    fn resolved_is_empty(&self, key: &str) -> bool {
        self.resolved_len(key) == 0
    }
}

fn load_bin_data_content(
    cfb: &mut cfb_reader::CfbReader,
    data: &[u8],
    bin_data_list: &[crate::model::bin_data::BinData],
    compressed: bool,
    encrypted: bool,
    password: Option<&[u8]>,
) -> Vec<BinDataContent> {
    use crate::model::bin_data::BinDataType;

    // 지연 로딩 리졸버가 참조할 OLE Storage 스트림 집합을 먼저 구성한다.
    let mut ole_streams = std::collections::HashSet::new();
    let mut compressed_streams = std::collections::HashMap::new();
    for bd in bin_data_list.iter() {
        if matches!(bd.data_type, BinDataType::Embedding | BinDataType::Storage) {
            let ext = if bd.data_type == BinDataType::Storage {
                bd.extension.as_deref().unwrap_or("OLE")
            } else {
                bd.extension.as_deref().unwrap_or("dat")
            };
            let storage_name = format!("BIN{:04X}.{}", bd.storage_id, ext);
            if bd.data_type == BinDataType::Storage {
                ole_streams.insert(storage_name.clone());
            }
            compressed_streams.insert(
                storage_name,
                bin_data_stream_is_compressed(bd.compression, compressed, encrypted),
            );
        }
    }

    let resolver: Option<std::sync::Arc<dyn crate::model::bin_data::BinDataResolver>> =
        match cfb_reader::CfbReader::open(data) {
            Ok(reader) => Some(std::sync::Arc::new(Hwp5BinResolver {
                cfb: std::sync::Mutex::new(reader),
                ole_streams,
                compressed_streams,
                encrypted,
                password: password.map(|p| p.to_vec()),
            })),
            Err(e) => {
                // 리졸버를 못 열면 지연 로딩 불가 — 기존처럼 즉시 로드로 폴백한다.
                eprintln!(
                    "경고: BinData 지연 로딩 리졸버 생성 실패: {} — 즉시 로드로 폴백",
                    e
                );
                None
            }
        };

    let mut contents = Vec::new();

    for bd in bin_data_list.iter() {
        // Embedding(이미지)과 Storage(OLE) 로드. Link는 외부 파일 참조이므로 제외
        let is_storage = match bd.data_type {
            BinDataType::Embedding => false,
            BinDataType::Storage => true,
            BinDataType::Link => {
                // 연결 레코드도 순번 자리를 지켜야 뒤 그림이 제 항목을 가리킨다.
                contents.push(crate::model::bin_data::hwp5_link_slot());
                continue;
            }
        };

        // 스토리지 이름 생성: BIN0001.jpg (이미지) / BIN0001.OLE (OLE)
        // Storage 타입은 확장자 정보가 없을 수 있으므로 "OLE"로 기본 폴백
        let ext = if is_storage {
            bd.extension.as_deref().unwrap_or("OLE")
        } else {
            bd.extension.as_deref().unwrap_or("dat")
        };
        let storage_name = format!("BIN{:04X}.{}", bd.storage_id, ext);
        let stream_compressed =
            bin_data_stream_is_compressed(bd.compression, compressed, encrypted);

        // [Task #2263] 스트림 존재만 확인하고(압축 해제 없이) 지연 등록한다.
        //
        // 기존 동작은 읽기 실패 시 항목을 배열에 넣지 않고 건너뛴다. 이 의미를
        // 보존해야 위치 기반 조회(`find_bin_data` 의 `get(id-1)`)와 왕복 길이
        // 비교가 깨지지 않으므로, `has_stream` 으로 존재 여부만 미리 확인한다.
        if let Some(resolver) = resolver.as_ref() {
            if !cfb.has_stream(&format!("/BinData/{}", storage_name)) {
                eprintln!("경고: BinData '{}' 스트림 없음", storage_name);
                continue;
            }
            contents.push(BinDataContent {
                id: bd.storage_id,
                data: crate::model::bin_data::BinDataBytes::Lazy {
                    resolver: resolver.clone(),
                    key: storage_name.clone(),
                },
                extension: ext.to_string(),
            });
            continue;
        }

        match cfb.read_bin_data(&storage_name) {
            Ok(data) => {
                // 암호 문서: 복호화+압축해제. 그 외: 압축 해제 시도 (실패 시 원본).
                let mut decompressed = if encrypted {
                    let pwd = password.unwrap();
                    match crypto::decrypt_password_protected_limited(
                        &data,
                        pwd,
                        stream_compressed,
                        MAX_PASSWORD_PROTECTED_BIN_DATA_OUTPUT_BYTES,
                    ) {
                        Ok(d) => d,
                        Err(e) => {
                            eprintln!(
                                "경고: BinData '{}' 복호화 실패 (비밀번호 불일치?): {}",
                                storage_name, e
                            );
                            continue;
                        }
                    }
                } else {
                    match cfb_reader::decompress_stream(&data) {
                        Ok(d) => d,
                        Err(_) => data, // 압축 해제 실패 시 원본 사용 (비압축 데이터)
                    }
                };

                // Task #195 단계 6: OLE Storage는 해제 후 선두 4바이트 size prefix를 스킵하여
                // 내부 CFB(`d0cf11e0...`) 시작 바이트부터 노출한다.
                if is_storage && decompressed.len() >= 12 {
                    // CFB 매직이 바로 시작하면 prefix 없음
                    let cfb_magic = [0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1];
                    if decompressed[..8] != cfb_magic && decompressed[4..12] == cfb_magic {
                        decompressed.drain(..4);
                    }
                }

                contents.push(BinDataContent {
                    id: bd.storage_id,
                    data: decompressed.into(),
                    extension: ext.to_string(),
                });
            }
            Err(e) => {
                eprintln!("경고: BinData '{}' 로드 실패: {}", storage_name, e);
            }
        }
    }

    contents
}

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

    /// 손상된 변환 HWP5의 실제 파싱이 패닉 없이 Ok/Err로 끝나야 한다.
    /// 과거 누적 vpos 정규화의 오버플로 재현 바이트를 그대로 보존한다.
    /// 저장 원점 보존 이후에도 원본 파서 진입점으로 같은 손상을 검사한다.
    #[test]
    fn corrupt_variant_vpos_does_not_overflow_panic() {
        let path = concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/samples/hwp3-sample11-hwp5.hwp"
        );
        let data = std::fs::read(path).expect("샘플 읽기");
        let mut corrupt = data.clone();
        let pos = corrupt.len() * 90 / 100; // 감사기가 패닉을 재현한 결정적 손상
        corrupt[pos] ^= 0xFF;
        let _ = parse_document(&corrupt); // 결과값 무관 — 패닉만 안 하면 통과
    }

    /// HWP3 변환본 추정 휴리스틱은 **파일에 실리는 여백을 건드리면 안 된다**.
    ///
    /// 종전에는 `margin_bottom` 을 직접 1600 깎았다. 이 판정은 확정이 아니라 추정이라
    /// 오탐이 있는데, 오탐이 파일 값을 바꾸면 저장본의 쪽 기하가 원본과 달라진다
    /// (02600 실측: 진짜 HWP5 인데 비율에 걸려 4252 -> 2652, 한글이 36쪽을 35쪽으로 연다).
    ///
    /// 같은 함수의 #3707 블록이 이미 같은 이유로 이 조작을 금지하고
    /// `pagination_bottom_tolerance`(렌더러 내부 값, `--verify` IR 비교 제외)를 쓴다.
    #[test]
    fn hwp3_origin_heuristic_moves_tolerance_not_the_saved_margin() {
        use crate::model::document::Section;
        use crate::model::paragraph::Paragraph;
        use crate::model::style::{CharShape, ParaShape};

        let mut doc = Document::default();
        let mut section = Section::default();
        section.section_def.page_def.margin_bottom = 4252;
        // 휴리스틱 발화 조건: 문단 > 50, ParaShape/문단 < 0.05, CharShape/문단 < 0.15
        section.paragraphs = (0..60).map(|_| Paragraph::default()).collect();
        doc.sections.push(section);
        doc.doc_info.para_shapes = vec![ParaShape::default()];
        doc.doc_info.char_shapes = vec![CharShape::default()];

        // [#7035] 종전 의도 유지 — 이 시험들이 세운 전제는 "HWP3 변환본" 이므로
        // 결정론 신호가 있는 문서로 넘긴다. 신호가 없을 때의 새 계약은 tests/cases 에 둔다.
        apply_hwp3_origin_fixup(&mut doc, true);

        let pd = &doc.sections[0].section_def.page_def;
        assert_eq!(
            pd.margin_bottom, 4252,
            "파일에 실리는 여백은 그대로여야 한다 — 줄이면 한컴이 보는 쪽 기하가 원본과 달라진다"
        );
        assert_eq!(
            pd.pagination_bottom_tolerance, 1600,
            "조판 여유는 렌더러 내부 값으로만 준다"
        );
    }

    /// 여백이 1600 보다 작으면 그만큼만 허용한다 — 음수 여유를 만들지 않는다.
    #[test]
    fn hwp3_origin_tolerance_is_clamped_to_the_available_margin() {
        use crate::model::document::Section;
        use crate::model::paragraph::Paragraph;
        use crate::model::style::{CharShape, ParaShape};

        let mut doc = Document::default();
        let mut section = Section::default();
        section.section_def.page_def.margin_bottom = 900;
        section.paragraphs = (0..60).map(|_| Paragraph::default()).collect();
        doc.sections.push(section);
        doc.doc_info.para_shapes = vec![ParaShape::default()];
        doc.doc_info.char_shapes = vec![CharShape::default()];

        // [#7035] 종전 의도 유지 — 이 시험들이 세운 전제는 "HWP3 변환본" 이므로
        // 결정론 신호가 있는 문서로 넘긴다. 신호가 없을 때의 새 계약은 tests/cases 에 둔다.
        apply_hwp3_origin_fixup(&mut doc, true);

        let pd = &doc.sections[0].section_def.page_def;
        assert_eq!(pd.margin_bottom, 900);
        assert_eq!(pd.pagination_bottom_tolerance, 900);
    }

    /// 휴리스틱이 발화하지 않는 문서는 아무것도 바뀌지 않는다.
    #[test]
    fn ordinary_hwp5_document_keeps_margin_and_tolerance() {
        use crate::model::document::Section;
        use crate::model::paragraph::Paragraph;
        use crate::model::style::{CharShape, ParaShape};

        let mut doc = Document::default();
        let mut section = Section::default();
        section.section_def.page_def.margin_bottom = 4252;
        section.paragraphs = (0..60).map(|_| Paragraph::default()).collect();
        doc.sections.push(section);
        // 스타일이 문단 수만큼 있으면 변환본으로 보지 않는다.
        doc.doc_info.para_shapes = (0..60).map(|_| ParaShape::default()).collect();
        doc.doc_info.char_shapes = (0..60).map(|_| CharShape::default()).collect();

        // [#7035] 종전 의도 유지 — 이 시험들이 세운 전제는 "HWP3 변환본" 이므로
        // 결정론 신호가 있는 문서로 넘긴다. 신호가 없을 때의 새 계약은 tests/cases 에 둔다.
        apply_hwp3_origin_fixup(&mut doc, true);

        let pd = &doc.sections[0].section_def.page_def;
        assert_eq!(pd.margin_bottom, 4252);
        assert_eq!(pd.pagination_bottom_tolerance, 0);
    }

    fn png_preview() -> Vec<u8> {
        let mut png = vec![0; 24];
        png[..8].copy_from_slice(b"\x89PNG\r\n\x1a\n");
        png[16..20].copy_from_slice(&1u32.to_be_bytes());
        png[20..24].copy_from_slice(&1u32.to_be_bytes());
        png
    }

    fn hwp_with_preview(image: Vec<u8>) -> Vec<u8> {
        let mut document = Document::default();
        document.preview = Some(Preview {
            image: Some(PreviewImage {
                format: PreviewImageFormat::Png,
                data: image,
            }),
            text: None,
        });
        crate::serializer::serialize_document(&document).expect("serialize HWP preview fixture")
    }

    fn hwpx_with_preview(image: Vec<u8>) -> Vec<u8> {
        let mut document = Document::default();
        document
            .hwpx_aux_entries
            .push(("Preview/PrvImage.png".to_string(), image));
        crate::serializer::hwpx::serialize_hwpx(&document).expect("serialize HWPX preview fixture")
    }

    #[test]
    fn thumbnail_limited_read_rejects_streamed_overflow() {
        let mut input = std::io::Cursor::new(vec![0u8; 9]);
        assert!(read_thumbnail_limited(&mut input, 8, 8).is_none());
    }

    #[test]
    fn thumbnail_limited_read_rejects_truncated_stream() {
        let mut input = std::io::Cursor::new(vec![0u8; 7]);
        assert!(read_thumbnail_limited(&mut input, 8, 8).is_none());
    }

    #[test]
    fn document_open_preserves_small_hwp_thumbnail() {
        let image = png_preview();
        let document = parse_document(&hwp_with_preview(image.clone()))
            .expect("document opens with a valid thumbnail");

        assert_eq!(
            document
                .preview
                .as_ref()
                .and_then(|preview| preview.image.as_ref())
                .map(|preview| preview.data.as_slice()),
            Some(image.as_slice())
        );
    }

    #[test]
    fn document_open_omits_oversized_hwp_thumbnail() {
        let document = parse_document(&hwp_with_preview(vec![0; MAX_THUMBNAIL_BYTES + 1]))
            .expect("document still opens when its optional thumbnail is oversized");

        assert!(document
            .preview
            .as_ref()
            .and_then(|preview| preview.image.as_ref())
            .is_none());
    }

    #[test]
    fn document_open_preserves_small_hwpx_thumbnail() {
        let image = png_preview();
        let document = parse_document(&hwpx_with_preview(image.clone()))
            .expect("document opens with a valid HWPX thumbnail");

        assert_eq!(
            document.hwpx_aux_entry("Preview/PrvImage.png"),
            Some(image.as_slice())
        );
        assert_eq!(
            document
                .extra_streams
                .iter()
                .find(|(path, _)| path == "/PrvImage")
                .map(|(_, data)| data.as_slice()),
            Some(image.as_slice())
        );
    }

    #[test]
    fn document_open_omits_oversized_hwpx_thumbnail() {
        let document = parse_document(&hwpx_with_preview(vec![0; MAX_THUMBNAIL_BYTES + 1]))
            .expect("document still opens when its optional HWPX thumbnail is oversized");

        assert!(document.hwpx_aux_entry("Preview/PrvImage.png").is_none());
        assert!(document
            .extra_streams
            .iter()
            .find(|(path, _)| path == "/PrvImage")
            .is_some_and(|(_, data)| data.len() < MAX_THUMBNAIL_BYTES));
    }

    #[test]
    fn cfb_thumbnail_rejects_declared_output_above_limit() {
        use std::io::Write;

        let mut compound = cfb::CompoundFile::create(std::io::Cursor::new(Vec::new())).unwrap();
        {
            let mut image = compound.create_stream("/PrvImage").unwrap();
            image
                .write_all(&vec![0u8; MAX_THUMBNAIL_BYTES + 1])
                .unwrap();
        }

        assert!(extract_thumbnail_only(&compound.into_inner().into_inner()).is_none());
    }

    #[test]
    fn hwpx_thumbnail_rejects_declared_output_above_limit() {
        use std::io::Write;

        let mut archive = std::io::Cursor::new(Vec::new());
        {
            let mut writer = zip::ZipWriter::new(&mut archive);
            writer
                .start_file(
                    "Preview/PrvImage.png",
                    zip::write::SimpleFileOptions::default()
                        .compression_method(zip::CompressionMethod::Deflated),
                )
                .unwrap();
            writer
                .write_all(&vec![0u8; MAX_THUMBNAIL_BYTES + 1])
                .unwrap();
            writer.finish().unwrap();
        }

        assert!(extract_thumbnail_only(&archive.into_inner()).is_none());
    }

    #[test]
    fn hwpx_thumbnail_rejects_declared_actual_size_mismatch() {
        use std::io::Write;

        let mut archive = std::io::Cursor::new(Vec::new());
        {
            let mut writer = zip::ZipWriter::new(&mut archive);
            writer
                .start_file(
                    "Preview/PrvImage.png",
                    zip::write::SimpleFileOptions::default()
                        .compression_method(zip::CompressionMethod::Stored),
                )
                .unwrap();
            writer.write_all(&[1, 2, 3]).unwrap();
            writer.finish().unwrap();
        }

        let mut bytes = archive.into_inner();
        for (signature, size_offset) in [
            ([0x50, 0x4B, 0x03, 0x04], 22),
            ([0x50, 0x4B, 0x01, 0x02], 24),
        ] {
            let header = bytes
                .windows(signature.len())
                .position(|window| window == signature)
                .unwrap();
            bytes[header + size_offset..header + size_offset + 4]
                .copy_from_slice(&4u32.to_le_bytes());
        }

        assert!(extract_thumbnail_only(&bytes).is_none());
    }

    #[test]
    fn open_decompression_budget_rejects_cumulative_overflow() {
        let mut budget =
            Hwp5DocumentOpenDecompressionBudget::new(Hwp5DocumentOpenDecompressionLimits {
                max_stream_input_bytes: 1024,
                max_stream_output_bytes: 1024,
                max_total_output_bytes: 1024,
            });
        budget.consume(700).unwrap();
        assert_eq!(budget.stream_limit(), 324);
        assert!(matches!(
            budget.consume(325),
            Err(cfb_reader::CfbError::LimitExceeded(324))
        ));
        budget.consume(324).unwrap();
        assert_eq!(budget.stream_limit(), 0);
    }

    fn document_with_number_controls(controls: Vec<crate::model::control::Control>) -> Document {
        let mut paragraph = crate::model::paragraph::Paragraph::default();
        paragraph.controls = controls;

        let mut section = crate::model::document::Section::default();
        section.paragraphs.push(paragraph);

        let mut document = Document::default();
        document.doc_properties.page_start_num = 1;
        document.sections.push(section);
        document
    }

    fn auto_number_values(
        document: &Document,
    ) -> Vec<(crate::model::control::AutoNumberType, u16, u16)> {
        use crate::model::control::Control;

        document.sections[0].paragraphs[0]
            .controls
            .iter()
            .filter_map(|control| match control {
                Control::AutoNumber(auto_number) => Some((
                    auto_number.number_type,
                    auto_number.number,
                    auto_number.assigned_number,
                )),
                _ => None,
            })
            .collect()
    }

    #[test]
    fn total_page_auto_number_does_not_advance_page_counter() {
        use crate::model::control::{AutoNumber, AutoNumberType, Control};

        let mut document = document_with_number_controls(vec![
            Control::AutoNumber(AutoNumber {
                number_type: AutoNumberType::Page,
                ..Default::default()
            }),
            Control::AutoNumber(AutoNumber {
                number_type: AutoNumberType::TotalPage,
                number: 8,
                assigned_number: 8,
                ..Default::default()
            }),
            Control::AutoNumber(AutoNumber {
                number_type: AutoNumberType::Page,
                ..Default::default()
            }),
        ]);

        assign_auto_numbers(&mut document);

        assert_eq!(
            auto_number_values(&document),
            vec![
                (AutoNumberType::Page, 1, 1),
                (AutoNumberType::TotalPage, 8, 8),
                (AutoNumberType::Page, 2, 2),
            ],
            "TotalPage 표시값은 보존되고 뒤 Page 번호는 연속이어야 한다"
        );
    }

    #[test]
    fn total_page_new_number_does_not_reset_page_counter() {
        use crate::model::control::{AutoNumber, AutoNumberType, Control, NewNumber};

        let mut document = document_with_number_controls(vec![
            Control::AutoNumber(AutoNumber {
                number_type: AutoNumberType::Page,
                ..Default::default()
            }),
            Control::NewNumber(NewNumber {
                number_type: AutoNumberType::TotalPage,
                number: 99,
            }),
            Control::AutoNumber(AutoNumber {
                number_type: AutoNumberType::Page,
                ..Default::default()
            }),
            Control::NewNumber(NewNumber {
                number_type: AutoNumberType::Page,
                number: 10,
            }),
            Control::AutoNumber(AutoNumber {
                number_type: AutoNumberType::Page,
                ..Default::default()
            }),
        ]);

        assign_auto_numbers(&mut document);

        assert_eq!(
            auto_number_values(&document),
            vec![
                (AutoNumberType::Page, 1, 1),
                (AutoNumberType::Page, 2, 2),
                (AutoNumberType::Page, 10, 10),
            ],
            "NewNumber(TotalPage)는 Page 카운터에 영향이 없고 NewNumber(Page)는 유지돼야 한다"
        );
    }

    /// [#1880 v2] HWP3-origin 비율 휴리스틱 대상 문서(문단>50, 저-스타일 비율)
    /// 를 합성해, HWPX-변환본 마커(is_hwpx_variant) 유무에 따라 margin_bottom
    /// 보정(-1600)이 갈리는지 확인한다. 마커 있으면 보정 오발동 금지.
    fn hwp3_ratio_suspect_doc() -> Document {
        let mut doc = Document::default();
        doc.doc_info
            .para_shapes
            .push(crate::model::style::ParaShape::default()); // ps_ratio = 1/60
        doc.doc_info
            .char_shapes
            .push(crate::model::style::CharShape::default()); // cs_ratio = 1/60
        let mut section = crate::model::document::Section::default();
        section.section_def.page_def.margin_bottom = 4252;
        for _ in 0..60 {
            section
                .paragraphs
                .push(crate::model::paragraph::Paragraph::default());
        }
        doc.sections.push(section);
        doc
    }

    #[test]
    fn issue1880v2_hwp3_fixup_applies_to_native() {
        let mut doc = hwp3_ratio_suspect_doc();
        assert!(!doc.is_hwpx_variant);
        // [#7035] 종전 의도 유지 — 이 시험들이 세운 전제는 "HWP3 변환본" 이므로
        // 결정론 신호가 있는 문서로 넘긴다. 신호가 없을 때의 새 계약은 tests/cases 에 둔다.
        apply_hwp3_origin_fixup(&mut doc, true);
        let pd = &doc.sections[0].section_def.page_def;
        // 보정은 그대로 적용되지만 **파일 값이 아니라 렌더러 내부 값**에 실린다.
        // 종전에는 `margin_bottom` 을 4252 - 1600 으로 깎았다 — 추정이 빗나가면 저장본의
        // 쪽 기하가 원본과 달라진다(02600 실측: 36쪽 문서가 35쪽으로 열림).
        assert_eq!(
            pd.margin_bottom, 4252,
            "파일에 실리는 여백은 건드리지 않는다"
        );
        assert_eq!(
            pd.pagination_bottom_tolerance, 1600,
            "native HWP5 의심본에는 종전대로 보정이 적용된다 — 자리만 옮겼다"
        );
    }

    #[test]
    fn issue1880v2_hwp3_fixup_skipped_for_hwpx_variant() {
        let mut doc = hwp3_ratio_suspect_doc();
        doc.is_hwpx_variant = true;
        // [#7035] 종전 의도 유지 — 이 시험들이 세운 전제는 "HWP3 변환본" 이므로
        // 결정론 신호가 있는 문서로 넘긴다. 신호가 없을 때의 새 계약은 tests/cases 에 둔다.
        apply_hwp3_origin_fixup(&mut doc, true);
        let pd = &doc.sections[0].section_def.page_def;
        assert_eq!(pd.margin_bottom, 4252);
        // 보정이 tolerance 로 옮겨간 뒤로는 여백만 봐서는 오발동을 잡을 수 없다 —
        // 보정이 실리는 자리를 직접 본다.
        assert_eq!(
            pd.pagination_bottom_tolerance, 0,
            "rhwp HWPX→HWP 변환본(마커)은 HWP3-origin 보정 오발동 금지 (#1880 v2, 2959953)"
        );
    }

    #[test]
    fn test_parse_hwp_too_small() {
        let result = parse_hwp(&[0u8; 10]);
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_hwp_invalid_cfb() {
        let result = parse_hwp(&[0u8; 512]);
        assert!(result.is_err());
    }

    #[test]
    fn test_detect_image_format_bmp() {
        let bmp_data = [0x42, 0x4D, 0x00, 0x00]; // BM header
        assert_eq!(detect_image_format(&bmp_data), PreviewImageFormat::Bmp);
    }

    #[test]
    fn test_detect_image_format_gif() {
        let gif_data = b"GIF89a";
        assert_eq!(detect_image_format(gif_data), PreviewImageFormat::Gif);
    }

    #[test]
    fn test_detect_image_format_unknown() {
        let unknown_data = [0x00, 0x00, 0x00, 0x00];
        assert_eq!(
            detect_image_format(&unknown_data),
            PreviewImageFormat::Unknown
        );
    }

    #[test]
    fn test_detect_format_hwp() {
        let cfb_header = [0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1];
        assert_eq!(detect_format(&cfb_header), FileFormat::Hwp);
    }

    #[test]
    fn test_detect_format_hwpx() {
        let data = make_zip(&[
            ("Contents/content.hpf", b"<package/>"),
            ("Contents/header.xml", b"<head/>"),
        ]);
        assert_eq!(detect_format(&data), FileFormat::Hwpx);
    }

    #[test]
    fn test_detect_format_unknown() {
        let data = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
        assert_eq!(detect_format(&data), FileFormat::Unknown);
    }

    fn make_zip(entries: &[(&str, &[u8])]) -> Vec<u8> {
        use std::io::{Cursor, Write};
        use zip::write::SimpleFileOptions;

        let mut output = Cursor::new(Vec::new());
        {
            let mut writer = zip::ZipWriter::new(&mut output);
            let options = SimpleFileOptions::default();
            for (name, contents) in entries {
                writer.start_file(*name, options).expect("ZIP entry start");
                writer.write_all(contents).expect("ZIP entry write");
            }
            writer.finish().expect("ZIP finish");
        }
        output.into_inner()
    }

    #[test]
    fn test_detect_format_too_short() {
        assert_eq!(detect_format(&[0x50, 0x4B]), FileFormat::Unknown);
    }

    #[test]
    fn issue1982_detect_empty_file() {
        assert_eq!(detect_format(&[]), FileFormat::Empty);
        let err = parse_document(&[]).unwrap_err();
        assert!(
            matches!(&err, ParseError::UnsupportedFormat { code, .. } if *code == EMPTY_FILE_CODE),
            "empty file → EMPTY_FILE: {err}"
        );
    }

    #[test]
    fn issue1982_detect_drm_containers() {
        // Fasoo DRM
        let fasoo = b"\x9b DRMONE  This Document is encrypted and protected by Fasoo DRM";
        assert_eq!(detect_format(fasoo), FileFormat::DrmProtected);
        // SoftCamp SCDSA
        let scdsa = b"SCDSA002\x00\x00\xd0\x04";
        assert_eq!(detect_format(scdsa), FileFormat::DrmProtected);
        let err = parse_document(fasoo).unwrap_err();
        assert!(
            matches!(&err, ParseError::UnsupportedFormat { code, .. } if *code == DRM_PROTECTED_CODE),
            "DRM → DRM_PROTECTED: {err}"
        );
        assert_eq!(drm_format_name(fasoo), "DRM 보호 문서 (Fasoo)");
        assert_eq!(drm_format_name(scdsa), "DRM 보호 문서 (SoftCamp SCDSA)");
    }

    #[test]
    fn test_detect_format_hwp3() {
        // Issue #265: HWP 3.0 바이너리 시그니처
        let hwp3_header = b"HWP Document File V3.00 \x1a\x01\x02\x03\x04\x05\x00\x00";
        assert_eq!(detect_format(hwp3_header), FileFormat::Hwp3);
    }

    #[test]
    fn test_detect_format_hwp3_exact_17_bytes() {
        // 경계: 정확히 17바이트 "HWP Document File" 로 감지
        let exact = b"HWP Document File";
        assert_eq!(detect_format(exact), FileFormat::Hwp3);
    }

    #[test]
    fn test_detect_format_hwp3_too_short() {
        // 17바이트 미만이면 감지 불가 (Unknown)
        let short = b"HWP Document Fil"; // 16바이트
        assert_eq!(detect_format(short), FileFormat::Unknown);
    }

    #[test]
    fn test_detect_format_legacy_hwpml_21() {
        let hwpml = br#"<?xml version="1.0" encoding="UTF-8"?>
<HWPML Version="2.1"></HWPML>"#;
        assert_eq!(detect_format(hwpml), FileFormat::Hml);
    }

    #[test]
    fn test_detect_format_rejects_lowercase_generic_xml_root() {
        let hwpml = b"\xEF\xBB\xBF  \n<?xml version='1.0'?><hwpml version='2.1'></hwpml>";
        assert_eq!(detect_format(hwpml), FileFormat::Unknown);
    }

    #[test]
    fn test_parse_document_dispatches_hwp() {
        // CFB 시그니처 → HwpParser 경로로 디스패치
        let result = parse_document(&[0xD0, 0xCF, 0x11, 0xE0, 0x00, 0x00, 0x00, 0x00]);
        assert!(result.is_err()); // 유효하지 않은 CFB이므로 에러
    }

    #[test]
    fn test_parse_document_dispatches_hwpx() {
        // ZIP 시그니처 → HwpxParser 경로로 디스패치
        let result = parse_document(&[0x50, 0x4B, 0x03, 0x04, 0x00, 0x00, 0x00, 0x00]);
        assert!(result.is_err()); // 유효하지 않은 ZIP이므로 에러
    }

    #[test]
    fn test_parse_document_reports_unsupported_hwpml_version() {
        // [#5848] 예시를 `2.1` → `9.9` 로 바꿨다. 계약("모르는 버전은
        // `UnsupportedVersion` 으로 보고한다")은 그대로다 — 예시로 쓰던 `2.1` 이
        // 이제 **지원 대상**이 됐을 뿐이다(법제처 국가법령정보센터 배포본이 그 버전이고,
        // 파서는 버전 값으로 분기하지 않아 태그 기반 경로가 그대로 적용된다).
        // 게이트를 없앤 것이 아니므로 모르는 버전은 여전히 여기서 걸린다.
        let hwpml = br#"<?xml version="1.0" encoding="UTF-8"?>
<HWPML Version="9.9"></HWPML>"#;
        let err = parse_document(hwpml).unwrap_err();
        match err {
            ParseError::HmlError(hml::HmlError::UnsupportedVersion(version)) => {
                assert_eq!(version, "9.9");
            }
            other => panic!("expected HML unsupported version, got {other:?}"),
        }
    }

    #[test]
    fn test_parse_document_with_metadata_preserves_hml_import_diagnostics() {
        let parsed =
            parse_document_with_metadata(include_bytes!("../../samples/hml/formatting_table.hml"))
                .expect("real HML fixture should parse");
        let metadata = parsed
            .hml_metadata
            .expect("HML import metadata should be retained");

        assert_eq!(metadata.hwpml_version.as_deref(), Some("2.91"));
        assert_eq!(metadata.encoding, hml::HmlEncoding::Utf8);
        assert_eq!(metadata.resource_count, 0);
        assert!(metadata
            .warnings
            .iter()
            .any(|warning| warning.xml_path == "/HWPML/TAIL/SCRIPTCODE"));
    }

    #[test]
    fn test_parse_document_unknown_returns_unsupported_file_format() {
        let err = parse_document(b"not a document").unwrap_err();
        let msg = format!("{err}");
        match err {
            ParseError::UnsupportedFormat { code, format, .. } => {
                assert_eq!(code, "UNSUPPORTED_FILE_FORMAT");
                assert_eq!(format, "알 수 없는 파일 형식");
            }
            other => panic!("expected UnsupportedFormat, got {other:?}"),
        }
        assert!(msg.contains("UNSUPPORTED_FILE_FORMAT"));
        assert!(!msg.contains("CFB 오류"), "CFB detail leaked: {msg}");
    }

    #[test]
    fn test_parse_document_hwp3_too_short_errors() {
        // Issue #265 (updated): HWP 3.0 헤더 (now supported, but data is incomplete)
        let hwp3_header = b"HWP Document File V3.00 \x1a\x01\x02\x03\x04\x05";
        let err = parse_document(hwp3_header).unwrap_err();
        match err {
            ParseError::Hwp3Error(_) => {}
            other => panic!("expected Hwp3Error, got {other:?}"),
        }
    }

    #[test]
    fn test_parse_document_issue_265_sample() {
        // Issue #265: 실제 제보 파일 samples/issue_265.hwp 가 HWP 3.0 으로
        // 감지되고 정상적으로 파싱되는지 확인.
        let data = std::fs::read("samples/issue_265.hwp")
            .expect("samples/issue_265.hwp should exist in repo");
        assert_eq!(detect_format(&data), FileFormat::Hwp3);
        let doc = parse_document(&data).expect("Should successfully parse HWP3 sample");
        assert!(
            !doc.sections.is_empty(),
            "Document should have at least one section"
        );
    }

    #[test]
    fn test_mock_parser() {
        struct MockParser;
        impl DocumentParser for MockParser {
            fn parse(&self, _data: &[u8]) -> Result<Document, ParseError> {
                Err(ParseError::EncryptedDocument)
            }
        }
        let result = MockParser.parse(&[]);
        assert!(result.is_err());
    }

    fn set_password_header(data: &[u8], encrypt_version: u32) -> Vec<u8> {
        use std::io::{Read, Seek, SeekFrom, Write};

        let mut compound =
            cfb::CompoundFile::open(std::io::Cursor::new(data.to_vec())).expect("cfb open");
        let mut header = Vec::new();
        {
            let mut stream = compound
                .open_stream("/FileHeader")
                .expect("FileHeader 스트림");
            stream.read_to_end(&mut header).unwrap();
        }
        let flags = u32::from_le_bytes(header[36..40].try_into().unwrap()) | 0x02;
        header[36..40].copy_from_slice(&flags.to_le_bytes());
        header[44..48].copy_from_slice(&encrypt_version.to_le_bytes());
        {
            let mut stream = compound
                .create_stream("/FileHeader")
                .expect("FileHeader 갱신");
            stream.seek(SeekFrom::Start(0)).unwrap();
            stream.write_all(&header).unwrap();
        }
        compound.into_inner().into_inner()
    }

    fn set_distribution_header(data: &[u8]) -> Vec<u8> {
        use std::io::{Read, Seek, SeekFrom, Write};

        let mut compound =
            cfb::CompoundFile::open(std::io::Cursor::new(data.to_vec())).expect("cfb open");
        let mut header = Vec::new();
        {
            let mut stream = compound
                .open_stream("/FileHeader")
                .expect("FileHeader 스트림");
            stream.read_to_end(&mut header).unwrap();
        }
        let flags = u32::from_le_bytes(header[36..40].try_into().unwrap()) | 0x04;
        header[36..40].copy_from_slice(&flags.to_le_bytes());
        {
            let mut stream = compound
                .create_stream("/FileHeader")
                .expect("FileHeader 갱신");
            stream.seek(SeekFrom::Start(0)).unwrap();
            stream.write_all(&header).unwrap();
        }
        compound.into_inner().into_inner()
    }

    fn add_raw_streams(data: &[u8], streams: &[(&str, &[u8])]) -> Vec<u8> {
        use std::io::Write;

        let mut compound =
            cfb::CompoundFile::open(std::io::Cursor::new(data.to_vec())).expect("cfb open");
        for (path, payload) in streams {
            if let Some(parent) = std::path::Path::new(path).parent() {
                compound.create_storage_all(parent).unwrap();
            }
            let mut stream = compound.create_stream(path).expect("테스트 스트림 생성");
            stream.write_all(payload).unwrap();
        }
        compound.into_inner().into_inner()
    }

    fn raw_deflate(data: &[u8]) -> Vec<u8> {
        use flate2::write::DeflateEncoder;
        use flate2::Compression;
        use std::io::Write;

        let mut encoder = DeflateEncoder::new(Vec::new(), Compression::default());
        encoder.write_all(data).unwrap();
        encoder.finish().unwrap()
    }

    fn hwp5_document_open_policy_for_test(
        max_stream_output_bytes: usize,
        max_total_output_bytes: usize,
    ) -> DocumentOpenDecompressionPolicy {
        hwp5_document_open_policy_with_input_for_test(
            max_stream_output_bytes,
            max_stream_output_bytes,
            max_total_output_bytes,
        )
    }

    fn hwp5_document_open_policy_with_input_for_test(
        max_stream_input_bytes: usize,
        max_stream_output_bytes: usize,
        max_total_output_bytes: usize,
    ) -> DocumentOpenDecompressionPolicy {
        DocumentOpenDecompressionPolicy {
            hwp5: Hwp5DocumentOpenDecompressionLimits {
                max_stream_input_bytes,
                max_stream_output_bytes,
                max_total_output_bytes,
            },
            ..DocumentOpenDecompressionPolicy::DEFAULT
        }
    }

    fn hwp3_document_open_policy_for_test(
        max_body_output_bytes: usize,
    ) -> DocumentOpenDecompressionPolicy {
        DocumentOpenDecompressionPolicy {
            hwp3_max_body_output_bytes: max_body_output_bytes,
            ..DocumentOpenDecompressionPolicy::DEFAULT
        }
    }

    fn hwp5_doc_info_and_first_section(data: &[u8]) -> (Vec<u8>, Vec<u8>) {
        let mut cfb = cfb_reader::CfbReader::open(data).expect("HWP5 CFB fixture");
        let header = header::parse_file_header(&cfb.read_file_header().unwrap())
            .expect("HWP5 FileHeader fixture");
        assert!(
            header.flags.compressed,
            "fixture must exercise decompression"
        );
        let doc_info = cfb.read_doc_info(true).expect("compressed DocInfo");
        let section = cfb
            .read_body_text_section(0, true, false)
            .expect("compressed BodyText/Section0");
        (doc_info, section)
    }

    fn hwp5_raw_doc_info(data: &[u8]) -> Vec<u8> {
        let mut cfb = cfb_reader::CfbReader::open(data).expect("HWP5 CFB fixture");
        cfb.read_stream_raw("/DocInfo")
            .expect("raw DocInfo fixture")
    }

    fn replace_raw_stream(data: &[u8], path: &str, payload: &[u8]) -> Vec<u8> {
        use std::io::Write;

        let mut compound =
            cfb::CompoundFile::open(std::io::Cursor::new(data.to_vec())).expect("cfb open");
        let mut stream = compound.create_stream(path).expect("테스트 스트림 교체");
        stream.write_all(payload).unwrap();
        // Stream buffers writes independently of CompoundFile::into_inner().
        stream.flush().expect("flush replacement stream");
        let bytes = compound.into_inner().into_inner();
        let mut reopened = cfb_reader::CfbReader::open(&bytes).expect("reopen CFB fixture");
        assert_eq!(
            reopened
                .read_stream_raw(path)
                .expect("read replacement stream"),
            payload,
            "replacement stream must retain the complete payload"
        );
        bytes
    }

    /// 기본 CFB reader가 열기 단계에서 거부하지만 LenientCfbReader는 계속 읽을 수 있는
    /// FAT 메타데이터 불일치를 만든다. 실제 디렉터리/스트림 chain은 건드리지 않으므로
    /// 아래 공개 parse 경로가 strict → lenient fallback을 실제로 지난다.
    fn force_lenient_cfb_fallback(data: &[u8]) -> Vec<u8> {
        const CFB_HEADER_BYTES: usize = 512;

        let mut corrupted = data.to_vec();
        assert!(
            corrupted.len() >= CFB_HEADER_BYTES,
            "CFB fixture must include its header"
        );
        let sector_shift =
            u16::from_le_bytes(corrupted[30..32].try_into().expect("sector shift bytes"));
        assert!(
            (9..=12).contains(&sector_shift),
            "fixture must use a supported CFB sector size"
        );
        let sector_size = 1usize << sector_shift;
        let fat_sectors_count =
            u32::from_le_bytes(corrupted[44..48].try_into().expect("FAT count bytes")) as usize;
        assert!(
            (1..=109).contains(&fat_sectors_count),
            "fixture must keep its FAT sector ids in the CFB header"
        );
        let fat_sector_ids: Vec<u32> = (0..fat_sectors_count)
            .map(|index| {
                let offset = 76 + index * 4;
                u32::from_le_bytes(
                    corrupted[offset..offset + 4]
                        .try_into()
                        .expect("FAT sector id bytes"),
                )
            })
            .collect();
        let entries_per_fat_sector = sector_size / 4;
        let physical_sector_count = (corrupted.len() - CFB_HEADER_BYTES) / sector_size;
        let fat_entry_offset = |sector_id: usize| {
            let owner_index = sector_id / entries_per_fat_sector;
            let owner_sector_id = *fat_sector_ids
                .get(owner_index)
                .expect("fixture FAT must cover each physical sector")
                as usize;
            CFB_HEADER_BYTES
                + owner_sector_id * sector_size
                + (sector_id % entries_per_fat_sector) * 4
        };
        let target = (0..physical_sector_count)
            .filter_map(|sector_id| {
                let offset = fat_entry_offset(sector_id);
                let value = u32::from_le_bytes(
                    corrupted[offset..offset + 4]
                        .try_into()
                        .expect("FAT entry bytes"),
                );
                (value < physical_sector_count as u32).then_some(value)
            })
            .next()
            .expect("fixture must contain a live FAT pointee");
        let padding_offset = fat_entry_offset(physical_sector_count);
        assert!(
            padding_offset + 4 <= corrupted.len(),
            "fixture FAT padding entry must be in range"
        );
        // The padding slot is beyond the file's physical sectors and hence cannot
        // be reached by the intact document. Reusing a live target makes the
        // permissive cfb allocator reject duplicate pointees; LenientCfbReader
        // ignores this unused tail entry and retains the real chains.
        corrupted[padding_offset..padding_offset + 4].copy_from_slice(&target.to_le_bytes());

        assert!(
            cfb_reader::CfbReader::open(&corrupted).is_err(),
            "mutation must make the standard CFB reader fail"
        );
        assert!(
            cfb_reader::LenientCfbReader::open(&corrupted).is_ok(),
            "mutation must retain a usable lenient CFB path"
        );
        corrupted
    }

    /// 공개 `parse_hwp` 진입점이 low-level CFB 기본값이 아니라 문서 열기 정책을
    /// 선택하고, DocInfo의 압축 해제 출력을 그 정책으로 차단하는지 검증한다.
    #[test]
    fn hwp5_open_decompression_rejects_doc_info_past_e2e_limit() {
        const LIMIT: usize = 1024;

        let source = std::fs::read("samples/2010-01-06.hwp").expect("sample 존재");
        let _ = hwp5_doc_info_and_first_section(&source);
        let oversized_doc_info = raw_deflate(&vec![0; LIMIT + 1]);
        let mutated = replace_raw_stream(&source, "/DocInfo", &oversized_doc_info);

        let result = with_document_open_decompression_policy_for_test(
            hwp5_document_open_policy_for_test(LIMIT, LIMIT * 2),
            || parse_hwp(&mutated),
        );

        assert!(matches!(
            result,
            Err(ParseError::CfbError(cfb_reader::CfbError::LimitExceeded(
                LIMIT
            )))
        ));
    }

    /// 공개 HWP5 문서 열기는 압축 해제 전에 DocInfo 원시 스트림 자체를 제한해야 한다.
    /// trailing bytes는 raw deflate decoder가 본문을 정상 해제할 수 있어도, 이전 구현에서는
    /// 불필요하게 모두 materialize했으므로 원시 입력 제한의 회귀 fixture로 사용한다.
    #[test]
    fn hwp5_open_rejects_doc_info_raw_input_before_decode() {
        let source = std::fs::read("samples/2010-01-06.hwp").expect("sample 존재");
        let mut oversized_raw_doc_info = hwp5_raw_doc_info(&source);
        let raw_limit = oversized_raw_doc_info.len();
        oversized_raw_doc_info.push(0);
        let mutated = replace_raw_stream(&source, "/DocInfo", &oversized_raw_doc_info);

        let result = with_document_open_decompression_policy_for_test(
            hwp5_document_open_policy_with_input_for_test(raw_limit, 1024 * 1024, 2 * 1024 * 1024),
            || parse_document(&mutated),
        );

        assert!(matches!(
            result,
            Err(ParseError::CfbError(cfb_reader::CfbError::LimitExceeded(limit)))
                if limit == raw_limit
        ));
    }

    /// strict CFB가 거부되어 lenient fallback을 타는 경우도 같은 raw 입력 상한을
    /// 디코딩 전에 적용해야 한다.
    #[test]
    fn hwp5_open_lenient_rejects_doc_info_raw_input_before_decode() {
        let source = std::fs::read("samples/2010-01-06.hwp").expect("sample 존재");
        let mut oversized_raw_doc_info = hwp5_raw_doc_info(&source);
        let raw_limit = oversized_raw_doc_info.len();
        oversized_raw_doc_info.push(0);
        let strict_rejected = replace_raw_stream(&source, "/DocInfo", &oversized_raw_doc_info);
        let mutated = force_lenient_cfb_fallback(&strict_rejected);

        let result = with_document_open_decompression_policy_for_test(
            hwp5_document_open_policy_with_input_for_test(raw_limit, 1024 * 1024, 2 * 1024 * 1024),
            || parse_document(&mutated),
        );

        assert!(matches!(
            result,
            Err(ParseError::CfbError(cfb_reader::CfbError::LimitExceeded(limit)))
                if limit == raw_limit
        ));
    }

    /// 배포 플래그가 있지만 ViewText가 없는 손상 HWP5는 BodyText로 fallback해
    /// 무제한 해제하지 않고, 공개 문서 열기 경계에서 missing ViewText 오류로 끝나야 한다.
    #[test]
    fn hwp5_open_decompression_rejects_missing_viewtext_without_bodytext_fallback() {
        let source = std::fs::read("samples/2010-01-06.hwp").expect("sample 존재");
        let (doc_info, _) = hwp5_doc_info_and_first_section(&source);
        let limit = doc_info.len().max(1024);
        let oversized_body_text = raw_deflate(&vec![0; limit + 1]);
        let mutated = set_distribution_header(&replace_raw_stream(
            &source,
            "/BodyText/Section0",
            &oversized_body_text,
        ));

        let result = with_document_open_decompression_policy_for_test(
            hwp5_document_open_policy_for_test(limit, limit * 2),
            || parse_document(&mutated),
        );

        assert!(matches!(
            result,
            Err(ParseError::CfbError(cfb_reader::CfbError::StreamNotFound(path)))
                if path == "/ViewText/Section0"
        ));
    }

    /// strict CFB 검증을 통과하지 못해 lenient fallback으로 연 문서도 공개 자동 감지
    /// 경로에서 같은 DocInfo 출력 상한을 적용해야 한다.
    #[test]
    fn hwp5_open_decompression_lenient_path_rejects_doc_info_past_e2e_limit() {
        const LIMIT: usize = 1024;

        let source = std::fs::read("samples/2010-01-06.hwp").expect("sample 존재");
        let oversized_doc_info = raw_deflate(&vec![0; LIMIT + 1]);
        let strict_rejected = replace_raw_stream(&source, "/DocInfo", &oversized_doc_info);
        let mutated = force_lenient_cfb_fallback(&strict_rejected);
        let lenient = cfb_reader::LenientCfbReader::open(&mutated).expect("lenient fixture");
        assert_eq!(
            lenient.read_stream("DocInfo").expect("lenient DocInfo"),
            oversized_doc_info,
            "FAT mutation must preserve the oversized DocInfo payload"
        );

        let result = with_document_open_decompression_policy_for_test(
            hwp5_document_open_policy_for_test(LIMIT, LIMIT * 2),
            || parse_document(&mutated),
        );

        assert!(
            matches!(
                result,
                Err(ParseError::CfbError(cfb_reader::CfbError::LimitExceeded(
                    LIMIT
                )))
            ),
            "expected DocInfo output limit, got {result:?}"
        );
    }

    /// Lenient fallback에서도 배포 플래그가 켜졌다면 정확한 ViewText hierarchy만
    /// 읽어야 한다. 손상된 BodyText를 fallback으로 해제하면 안 된다.
    #[test]
    fn hwp5_open_decompression_lenient_distribution_rejects_missing_viewtext() {
        let source = std::fs::read("samples/2010-01-06.hwp").expect("sample 존재");
        let (doc_info, _) = hwp5_doc_info_and_first_section(&source);
        let limit = doc_info.len().max(1024);
        let oversized_body_text = raw_deflate(&vec![0; limit + 1]);
        let strict_rejected = set_distribution_header(&replace_raw_stream(
            &source,
            "/BodyText/Section0",
            &oversized_body_text,
        ));
        let mutated = force_lenient_cfb_fallback(&strict_rejected);

        let result = with_document_open_decompression_policy_for_test(
            hwp5_document_open_policy_for_test(limit, limit * 2),
            || parse_document(&mutated),
        );

        match &result {
            Err(ParseError::CfbError(cfb_reader::CfbError::StreamNotFound(path)))
                if path == "ViewText/Section0" => {}
            other => panic!("expected missing exact lenient ViewText path, got {other:?}"),
        }
    }

    /// 자동 감지 공개 진입점에서 DocInfo와 첫 BodyText가 각각의 단일 스트림 상한은
    /// 넘지 않아도 같은 문서 열기 누적 예산을 공유하는지 검증한다.
    #[test]
    fn hwp5_open_decompression_rejects_cumulative_output_through_parse_document() {
        let source = std::fs::read("samples/2010-01-06.hwp").expect("sample 존재");
        let (doc_info, section) = hwp5_doc_info_and_first_section(&source);
        assert!(!doc_info.is_empty(), "DocInfo fixture must have output");
        assert!(
            section.len() > 1,
            "BodyText fixture must have enough output for a one-byte deficit"
        );

        let max_total_output_bytes = doc_info
            .len()
            .checked_add(section.len())
            .expect("fixture output length fits usize")
            - 1;
        let expected_remaining_limit = section.len() - 1;
        let result = with_document_open_decompression_policy_for_test(
            hwp5_document_open_policy_for_test(
                doc_info.len().max(section.len()),
                max_total_output_bytes,
            ),
            || parse_document(&source),
        );

        assert!(matches!(
            result,
            Err(ParseError::CfbError(cfb_reader::CfbError::LimitExceeded(limit)))
                if limit == expected_remaining_limit
        ));
    }

    /// 비밀번호 보호 HWP5도 공개 `parse_document_with_password` 경로에서 같은
    /// 문서 열기 정책의 명시적 상한을 crypto helper에 전달하는지 검증한다.
    #[test]
    fn hwp5_open_decompression_encrypted_doc_info_uses_e2e_limit() {
        const PASSWORD: &[u8] = b"e2e-open-budget";

        let source = std::fs::read("samples/2010-01-06.hwp").expect("sample 존재");
        let (doc_info, _) = hwp5_doc_info_and_first_section(&source);
        assert!(doc_info.len() > 1, "DocInfo fixture must have output");
        let encrypted = encrypt_hwp_streams_for_test(&source, PASSWORD);
        assert!(
            parse_document_with_password(&encrypted, PASSWORD).is_ok(),
            "encrypted fixture must be valid before constraining its public open path"
        );

        let limit = doc_info.len() - 1;
        let result = with_document_open_decompression_policy_for_test(
            hwp5_document_open_policy_for_test(limit, doc_info.len()),
            || parse_document_with_password(&encrypted, PASSWORD),
        );

        assert!(matches!(
            result,
            Err(ParseError::CryptoError(
                crypto::CryptoError::DecompressedStreamLimitExceeded { max_bytes }
            )) if max_bytes == limit
        ));
    }

    /// 비밀번호 문서도 복호화 helper에 전달하기 전에 암호문 raw 입력 크기를 차단해야 한다.
    #[test]
    fn hwp5_open_encrypted_doc_info_rejects_raw_input_before_decrypt() {
        let source = std::fs::read("samples/2010-01-06.hwp").expect("sample 존재");
        let password = hwp5_raw_doc_info(&source)
            .into_iter()
            .take(16)
            .collect::<Vec<_>>();
        assert!(
            !password.is_empty(),
            "DocInfo fixture must provide test bytes"
        );

        let encrypted = encrypt_hwp_streams_for_test(&source, &password);
        let ciphertext_len = hwp5_raw_doc_info(&encrypted).len();
        assert!(
            ciphertext_len > 1,
            "encrypted DocInfo fixture must be nonempty"
        );
        let raw_limit = ciphertext_len - 1;

        let result = with_document_open_decompression_policy_for_test(
            hwp5_document_open_policy_with_input_for_test(raw_limit, 1024 * 1024, 2 * 1024 * 1024),
            || parse_document_with_password(&encrypted, &password),
        );

        assert!(
            matches!(
                &result,
                Err(ParseError::CfbError(cfb_reader::CfbError::LimitExceeded(limit)))
                    if *limit == raw_limit
            ),
            "expected raw input limit {raw_limit}"
        );
    }

    /// HWP3도 public `parse_document` 자동 감지 경로에서 작은 문서 열기 상한을
    /// HWP3 본문 압축 해제 helper로 전달하는지 실제 압축 fixture로 검증한다.
    #[test]
    fn hwp3_open_decompression_rejects_compressed_body_through_parse_document() {
        let source = std::fs::read("samples/issue_265.hwp").expect("HWP3 sample 존재");
        assert_eq!(detect_format(&source), FileFormat::Hwp3);
        assert_eq!(
            source.get(154),
            Some(&1),
            "fixture must mark its HWP3 body as compressed"
        );
        assert!(
            parse_document(&source).is_ok(),
            "HWP3 fixture must be valid before constraining its public open path"
        );

        let result = with_document_open_decompression_policy_for_test(
            hwp3_document_open_policy_for_test(1),
            || parse_document(&source),
        );

        assert!(matches!(
            result,
            Err(ParseError::Hwp3Error(hwp3::Hwp3Error::ParseError { message }))
                if message.contains("1 바이트 상한")
        ));
    }

    fn encrypt_hwp_streams_for_test(data: &[u8], password: &[u8]) -> Vec<u8> {
        use std::io::{Read, Write};

        let mut compound =
            cfb::CompoundFile::open(std::io::Cursor::new(data.to_vec())).expect("cfb open");
        let encrypted_paths: Vec<String> = compound
            .walk()
            .filter(|entry| entry.is_stream())
            .map(|entry| entry.path().to_string_lossy().replace('\\', "/"))
            .filter(|path| {
                path == "/DocInfo"
                    || path.starts_with("/BodyText/")
                    || path.starts_with("/ViewText/")
                    || path.starts_with("/BinData/")
                    || path.starts_with("/Scripts/")
            })
            .collect();

        for path in encrypted_paths {
            let mut raw = Vec::new();
            {
                let mut stream = compound.open_stream(&path).expect("암호화 대상 스트림");
                stream.read_to_end(&mut raw).unwrap();
            }
            let encrypted = crypto::encrypt_password_stream_for_test(&raw, password);
            let mut stream = compound.create_stream(&path).expect("암호문 스트림 갱신");
            stream.write_all(&encrypted).unwrap();
        }

        let bytes = compound.into_inner().into_inner();
        set_password_header(&bytes, crypto::SUPPORTED_PASSWORD_ENCRYPT_VERSION)
    }

    fn extra_stream_payload<'a>(doc: &'a Document, path: &str) -> &'a [u8] {
        doc.extra_streams
            .iter()
            .find(|(candidate, _)| candidate == path)
            .map(|(_, data)| data.as_slice())
            .unwrap_or_else(|| panic!("추가 스트림 없음: {path}"))
    }

    fn total_paragraphs(doc: &Document) -> usize {
        doc.sections
            .iter()
            .map(|section| section.paragraphs.len())
            .sum()
    }

    /// 비밀번호 암호 라우팅 검증: 일반 샘플의 FileHeader 에서 encrypted 비트와
    /// EncryptVersion만 켠 변형을 만들어 (스트림 자체는 암호화하지 않음)
    /// 파서의 분기를 확인한다.
    ///
    /// - 비밀번호 없음 → ParseError::EncryptedDocument
    /// - 비밀번호 제공(틀림) → 실제 복호화 시도 후 WrongPassword (압축 해제 실패)
    /// - 원본은 여전히 정상 파싱 (회귀 없음)
    #[test]
    fn test_encrypted_flag_routes_password_paths() {
        let original = std::fs::read("samples/2010-01-06.hwp").expect("sample 존재");
        // 원본 정상 파싱 (회귀 가드)
        assert!(parse_document(&original).is_ok(), "원본은 파싱되어야 함");

        let modified = set_password_header(&original, crypto::SUPPORTED_PASSWORD_ENCRYPT_VERSION);

        // 1) 비밀번호 없음 → EncryptedDocument
        match parse_document(&modified) {
            Err(ParseError::EncryptedDocument) => {}
            Err(e) => panic!("비밀번호 없는 암호 문서는 EncryptedDocument 이어야 함: {e}"),
            Ok(_) => panic!("encrypted 플래그가 켜졌으면 파싱이 성공하면 안 됨"),
        }

        // 2) 비밀번호 제공 (스트림이 실제로 암호화되지 않았으므로 복호화 결과는 쓰레기
        //    → 압축 해제 실패 → CryptoError::WrongPassword)
        match parse_document_with_metadata_password(&modified, b"any-password") {
            Err(ParseError::CryptoError(crypto::CryptoError::WrongPassword)) => {}
            Err(e) => panic!("틀린 비밀번호는 WrongPassword 여야 함 (다른 에러): {e}"),
            Ok(_) => panic!("틀린 비밀번호인데 파싱이 성공하면 안 됨"),
        }
    }

    #[test]
    fn test_encrypted_document_rejects_unsupported_encrypt_version() {
        let original = std::fs::read("samples/2010-01-06.hwp").expect("sample 존재");
        let modified = set_password_header(&original, 3);

        assert!(matches!(
            parse_document_with_password(&modified, b"password"),
            Err(ParseError::CryptoError(
                crypto::CryptoError::UnsupportedScheme { encrypt_version: 3 }
            ))
        ));
    }

    #[test]
    fn test_encrypted_stream_limited_decode_enforces_decompression_bound() {
        const PASSWORD: &[u8] = b"bounded-password";
        let plaintext = vec![b'A'; 4096];
        let compressed = raw_deflate(&plaintext);
        let encrypted = crypto::encrypt_password_stream_for_test(&compressed, PASSWORD);

        assert!(
            decode_encrypted_stream_limited(&encrypted, PASSWORD, true, 1024).is_none(),
            "압축 해제 결과가 상한을 넘으면 materialize하지 않아야 함"
        );
        assert_eq!(
            decode_encrypted_stream_limited(&encrypted, PASSWORD, true, plaintext.len()).unwrap(),
            plaintext
        );
    }

    #[test]
    fn test_password_encrypted_uncompressed_hwp_detects_wrong_password() {
        const PASSWORD: &[u8] = b"uncompressed-password";

        let mut source_doc = Document::default();
        source_doc.header.version = crate::model::document::HwpVersion {
            major: 5,
            minor: 0,
            build: 1,
            revision: 7,
        };
        source_doc.doc_properties.section_count = 1;
        source_doc.sections.push(crate::model::document::Section {
            paragraphs: vec![crate::model::paragraph::Paragraph {
                text: "비압축".to_string(),
                char_count: 4,
                ..Default::default()
            }],
            ..Default::default()
        });

        let uncompressed =
            crate::serializer::serialize_document(&source_doc).expect("비압축 기준 HWP");
        let baseline = parse_document(&uncompressed).expect("비압축 기준 재파싱");
        let encrypted = encrypt_hwp_streams_for_test(&uncompressed, PASSWORD);

        assert!(matches!(
            parse_document_with_password(&encrypted, b"wrong-password"),
            Err(ParseError::CryptoError(crypto::CryptoError::WrongPassword))
        ));
        let decrypted =
            parse_document_with_password(&encrypted, PASSWORD).expect("비압축 암호 HWP 파싱");
        assert_eq!(decrypted.sections.len(), baseline.sections.len());
        assert_eq!(total_paragraphs(&decrypted), total_paragraphs(&baseline));
    }

    #[test]
    fn test_password_encrypted_hwp_full_stream_roundtrip() {
        use crate::model::bin_data::{
            BinData, BinDataCompression, BinDataContent, BinDataStatus, BinDataType,
        };

        const PASSWORD: &[u8] = "한글-password".as_bytes();
        const SCRIPT_TEXT: &[u8] = b"function OnDocumentOpen() { return 7; }";
        const ORPHAN_TEXT: &[u8] = b"orphan BinData preserved after password decryption";
        const BIN_PAYLOAD: &[u8; 32] = b"0123456789abcdef0123456789abcdef";

        // 권위 샘플을 한 번 정상 파싱한 뒤, 문서 전역 compressed=true와 반대인
        // NoCompress BinData를 추가해 스트림별 압축 속성도 함께 검증한다.
        let source = std::fs::read("samples/2010-01-06.hwp").expect("sample 존재");
        let mut source_doc = parse_document(&source).expect("원본 파싱");
        let storage_id = source_doc
            .doc_info
            .bin_data_list
            .iter()
            .map(|item| item.storage_id)
            .max()
            .unwrap_or(0)
            .saturating_add(1);
        source_doc.doc_info.bin_data_list.push(BinData {
            raw_data: None,
            attr: 0x0021, // Embedding + NoCompress
            data_type: BinDataType::Embedding,
            compression: BinDataCompression::NoCompress,
            status: BinDataStatus::NotAccessed,
            abs_path: None,
            rel_path: None,
            storage_id,
            extension: Some("pwdtest".to_string()),
        });
        source_doc.bin_data_content.push(BinDataContent {
            id: storage_id,
            data: BIN_PAYLOAD.to_vec().into(),
            extension: "pwdtest".to_string(),
        });
        source_doc.doc_info.raw_stream_dirty = true;

        let serialized = crate::serializer::serialize_document(&source_doc).expect("기준 HWP 생성");
        let script_raw = raw_deflate(SCRIPT_TEXT);
        let orphan_raw = raw_deflate(ORPHAN_TEXT);
        let with_extras = add_raw_streams(
            &serialized,
            &[
                ("/Scripts/PasswordTest", &script_raw),
                ("/BinData/ORPHAN.pwd", &orphan_raw),
            ],
        );
        let baseline = parse_document(&with_extras).expect("기준 HWP 재파싱");

        // 실제 한컴 EncryptVersion 4 저장 동작은 BIN_DATA attr이 NoCompress여도
        // 문서 전역 compressed=true이면 BinData를 raw-deflate한 뒤 암호화한다.
        // 일반 HWP 기준본은 NoCompress를 유지하고, 암호화 입력만 이 on-disk
        // 형태로 바꿔 실제 파일의 압축 계약을 재현한다.
        let password_bin_path = format!("/BinData/BIN{:04X}.pwdtest", storage_id);
        let password_bin_raw = raw_deflate(BIN_PAYLOAD);
        let password_layout = add_raw_streams(
            &with_extras,
            &[(password_bin_path.as_str(), password_bin_raw.as_slice())],
        );
        let encrypted = encrypt_hwp_streams_for_test(&password_layout, PASSWORD);

        assert!(matches!(
            parse_document(&encrypted),
            Err(ParseError::EncryptedDocument)
        ));
        assert!(matches!(
            parse_document_with_password(&encrypted, b"wrong-password"),
            Err(ParseError::CryptoError(crypto::CryptoError::WrongPassword))
        ));

        let decrypted =
            parse_document_with_password(&encrypted, PASSWORD).expect("암호 HWP 전체 파싱");
        assert_eq!(decrypted.sections.len(), baseline.sections.len());
        assert_eq!(total_paragraphs(&decrypted), total_paragraphs(&baseline));
        assert_eq!(
            decrypted
                .bin_data_content
                .iter()
                .find(|content| content.id == storage_id)
                .expect("NoCompress BinData")
                .data
                .load(),
            BIN_PAYLOAD
        );
        assert_eq!(
            cfb_reader::decompress_stream(extra_stream_payload(
                &decrypted,
                "/Scripts/PasswordTest"
            ))
            .expect("Scripts 평문 raw-deflate"),
            SCRIPT_TEXT
        );
        assert_eq!(
            cfb_reader::decompress_stream(extra_stream_payload(&decrypted, "/BinData/ORPHAN.pwd"))
                .expect("고아 BinData 평문 raw-deflate"),
            ORPHAN_TEXT
        );

        // 암호화 쓰기는 지원하지 않으므로 저장 결과는 일반 HWP로 강하한다.
        // 이때 플래그뿐 아니라 EncryptVersion과 보존 스트림 암호문도 정리돼야 한다.
        let saved = crate::serializer::serialize_document(&decrypted).expect("복호 문서 저장");
        let mut saved_cfb = cfb_reader::CfbReader::open(&saved).expect("저장 CFB");
        let saved_header =
            header::parse_file_header(&saved_cfb.read_file_header().unwrap()).unwrap();
        assert!(!saved_header.flags.encrypted);
        assert_eq!(saved_header.encrypt_version, 0);

        let reparsed = parse_document(&saved).expect("저장 결과 비밀번호 없이 재파싱");
        assert_eq!(
            reparsed
                .bin_data_content
                .iter()
                .find(|content| content.id == storage_id)
                .expect("저장 NoCompress BinData")
                .data
                .load(),
            BIN_PAYLOAD
        );
        assert_eq!(
            cfb_reader::decompress_stream(extra_stream_payload(&reparsed, "/Scripts/PasswordTest"))
                .expect("저장 Scripts"),
            SCRIPT_TEXT
        );
        assert_eq!(
            cfb_reader::decompress_stream(extra_stream_payload(&reparsed, "/BinData/ORPHAN.pwd"))
                .expect("저장 고아 BinData"),
            ORPHAN_TEXT
        );
    }
}