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
//! Image and picture command adapters.

use std::fs;
use std::path::Path;
use std::process;

use rhwp::provenance;
use rhwp::schema_registry::ENVELOPE_SCHEMA_VERSION;

use super::runtime::{
    edit_output_format, edit_serialize, edit_verify_report, finish_edit_write, EditOutputFormat,
};
use crate::{load_document, EXIT_OK, EXIT_RUNTIME, EXIT_USAGE};

/// [#3719 §6-5] `edit insert-image` 가 받는 그림 형식.
///
/// BinData 로 넣을 수 있고 **원본 픽셀 크기를 헤더만 읽어 잴 수 있는** 형식만 담는다.
/// 크기를 못 재면 배율·배치 좌표가 의미를 잃으므로 삽입을 시작하지 않는다.
const INSERT_IMAGE_FORMATS: [&str; 6] = ["png", "jpg", "jpeg", "bmp", "tif", "tiff"];

/// 96dpi 픽셀 1개 = 75 HWPUNIT(7200/96). 코어가 crop 을 `px * 75` 로 잡는 것과 같은 환산비다.
const HWPUNIT_PER_PX: u32 = 75;

/// 그림의 원본 픽셀 크기 — 전체 디코드 없이 헤더만 읽는다.
///
/// 확장자는 거짓말할 수 있으므로 매직 바이트로 형식을 다시 판정한다. 알아보지 못하면
/// `None` — 호출부가 인자 오류(exit 2)로 끊는다.
fn insert_image_dimensions(bytes: &[u8]) -> Option<(u32, u32)> {
    use image::ImageFormat;

    let format = image::guess_format(bytes).ok()?;
    if !matches!(
        format,
        ImageFormat::Png | ImageFormat::Jpeg | ImageFormat::Bmp | ImageFormat::Tiff
    ) {
        return None;
    }
    let (width, height) = image::ImageReader::with_format(std::io::Cursor::new(bytes), format)
        .into_dimensions()
        .ok()?;
    if width == 0 || height == 0 {
        return None;
    }
    Some((width, height))
}

/// `--page` 가 가리키는 쪽의 **앵커 문단**(구역 인덱스, 문단 인덱스).
///
/// 용지 기준(Paper-relative) floating 그림은 앵커 문단이 놓인 쪽에 그려진다. 그래서
/// "몇 쪽" 을 "어느 문단" 으로 옮겨야 하는데, 그 환산은 이미 조판 결과가 알고 있다 —
/// 기존 진단 질의 `dump_page_items_json` 을 그대로 읽어 그 쪽의 첫 본문 항목을 고른다
/// (새 조판 로직 0). 미주(`isEndnote`)는 구역 뒤에 합성된 문단이라 앵커로 쓰지 않는다.
fn insert_image_page_anchor(
    doc: &rhwp::wasm_api::HwpDocument,
    page: u32,
) -> Option<(usize, usize)> {
    let empty: Vec<serde_json::Value> = Vec::new();
    let pages = doc.dump_page_items_json(Some(page));
    let page_json = pages.as_array()?.first()?;
    let section = page_json["section"].as_u64()? as usize;

    for column in page_json["columns"].as_array().unwrap_or(&empty) {
        for item in column["items"].as_array().unwrap_or(&empty) {
            if item["isEndnote"] == true {
                continue;
            }
            if let Some(para) = item["paraIndex"].as_u64() {
                return Some((section, para as usize));
            }
        }
    }
    // 항목이 하나도 없는 쪽(어울림 문단·감춘 빈 줄만 귀속된 쪽)은 extras 로 온다.
    for extra in page_json["extras"].as_array().unwrap_or(&empty) {
        if let Some(para) = extra["paraIndex"].as_u64() {
            return Some((section, para as usize));
        }
    }
    None
}

struct InsertImageArgs<'a> {
    file_path: &'a str,
    image_path: &'a str,
    page: u32,
    x_hu: u32,
    y_hu: u32,
    width: Option<u32>,
    height: Option<u32>,
    output: Option<String>,
    dry_run: bool,
    json: bool,
    verify: bool,
}

fn parse_insert_image_args(args: &[String]) -> Result<InsertImageArgs<'_>, i32> {
    const USAGE: &str = "사용법: rhwp edit insert-image <파일> --image <그림> [--page N] [--x N --y N] [--width N --height N] [-o <출력>] [--dry-run] [--verify] [--json]";

    let mut file_path = None;
    let mut image_path = None;
    let mut page = 0;
    let mut x_hu = 0;
    let mut y_hu = 0;
    let mut width = None;
    let mut height = None;
    let mut output = None;
    let mut dry_run = false;
    let mut json = false;
    let mut verify = false;

    let mut i = 0;
    while i < args.len() {
        match args[i].as_str() {
            "--image" => {
                i += 1;
                match args.get(i) {
                    Some(value) => image_path = Some(value.as_str()),
                    None => {
                        eprintln!("오류: --image 뒤에 그림 파일 경로가 필요합니다.");
                        return Err(EXIT_USAGE);
                    }
                }
            }
            "--page" | "--x" | "--y" | "--width" | "--height" => {
                let name = args[i].as_str();
                // 단위를 오류 문구에도 박아 둔다 — px 로 넣으면 도장이 사라진다.
                let unit = if name == "--page" {
                    " (0부터)"
                } else {
                    " (HWPUNIT, 1/7200 inch)"
                };
                i += 1;
                let Some(raw) = args.get(i) else {
                    eprintln!("오류: {name} 뒤에 0 이상의 정수가 필요합니다{unit}.");
                    return Err(EXIT_USAGE);
                };
                let Ok(value) = raw.parse::<u32>() else {
                    eprintln!("오류: {name} 뒤에 0 이상의 정수가 필요합니다{unit}: {raw}");
                    return Err(EXIT_USAGE);
                };
                match name {
                    "--page" => page = value,
                    "--x" => x_hu = value,
                    "--y" => y_hu = value,
                    "--width" => width = Some(value),
                    _ => height = Some(value),
                }
            }
            "-o" | "--output" => {
                i += 1;
                match args.get(i) {
                    Some(value) => output = Some(value.clone()),
                    None => {
                        eprintln!("오류: -o 뒤에 출력 파일 경로가 필요합니다.");
                        return Err(EXIT_USAGE);
                    }
                }
            }
            "--dry-run" => dry_run = true,
            "--json" => json = true,
            "--verify" => verify = true,
            other if other.starts_with('-') => {
                eprintln!("알 수 없는 옵션: {other}");
                return Err(EXIT_USAGE);
            }
            other => {
                if file_path.replace(other).is_some() {
                    eprintln!("오류: 입력 파일은 하나만 지정할 수 있습니다: {other}");
                    return Err(EXIT_USAGE);
                }
            }
        }
        i += 1;
    }

    let (Some(file_path), Some(image_path)) = (file_path, image_path) else {
        eprintln!("{USAGE}");
        return Err(EXIT_USAGE);
    };
    for (name, value) in [("--width", width), ("--height", height)] {
        if value == Some(0) {
            eprintln!("오류: {name} 는 1 이상이어야 합니다 (HWPUNIT, 1/7200 inch).");
            return Err(EXIT_USAGE);
        }
    }

    Ok(InsertImageArgs {
        file_path,
        image_path,
        page,
        x_hu,
        y_hu,
        width,
        height,
        output,
        dry_run,
        json,
        verify,
    })
}

/// `edit insert-image` — 도장·서명 같은 그림을 쪽 좌표에 붙인다 (#3719 §6-5).
///
/// 실물 서식 제출의 마지막 조각이다. 채워 넣은 서식에 직인·서명 이미지를 얹지 못하면
/// 사람이 한 번 더 한컴을 열어야 하고, 그 순간 자동화 사슬이 끊긴다.
///
/// 새 삽입 로직을 만들지 않는다 — 검증된 코어 `insert_picture_native` 의 **본문 floating
/// 분기**(용지 기준 offset, `treat_as_char=false`, 한컴 native 기본값)를 그대로 쓴다.
/// 인자 파싱·저장·봉투·`--verify`·`changedPages` 는 `edit set-cell` 과 같은 형태다.
///
/// **길이 단위는 전부 HWPUNIT(1/7200 inch)** 이다 — px 로 오해하면 도장이 점만 하게
/// 찍히거나 아예 안 보인다. A4 세로는 59528 × 84188 HWPUNIT.
pub(super) fn edit_insert_image(args: &[String]) -> i32 {
    let InsertImageArgs {
        file_path,
        image_path,
        page: page_arg,
        x_hu,
        y_hu,
        width: width_arg,
        height: height_arg,
        output: out_path,
        dry_run,
        json: json_mode,
        verify: verify_mode,
    } = match parse_insert_image_args(args) {
        Ok(parsed) => parsed,
        Err(code) => return code,
    };

    // ── 그림 선검증 — 문서를 읽기 전에 끊는다 ──
    // 지원하지 않는 형식은 **인자 문제**다(런타임 실패가 아니다) → exit 2.
    let image_ext = Path::new(image_path)
        .extension()
        .map(|e| e.to_string_lossy().to_ascii_lowercase())
        .unwrap_or_default();
    if !INSERT_IMAGE_FORMATS.contains(&image_ext.as_str()) {
        eprintln!(
            "오류: 지원하지 않는 그림 형식입니다 - {} (지원: {})",
            if image_ext.is_empty() {
                "확장자 없음".to_string()
            } else {
                image_ext.clone()
            },
            INSERT_IMAGE_FORMATS.join(", ")
        );
        return EXIT_USAGE;
    }
    let image_bytes = match fs::read(image_path) {
        Ok(d) => d,
        Err(e) => {
            eprintln!("오류: 그림 파일을 읽을 수 없습니다 - {}: {}", image_path, e);
            return EXIT_RUNTIME;
        }
    };
    // 확장자만 믿지 않는다 — 내용이 그림이 아니면 원본 픽셀 크기를 못 재고,
    // 크기를 모르면 배치 좌표가 의미를 잃는다.
    let Some((natural_w_px, natural_h_px)) = insert_image_dimensions(&image_bytes) else {
        eprintln!(
            "오류: 그림 형식을 알아볼 수 없습니다 - {} (지원: {})",
            image_path,
            INSERT_IMAGE_FORMATS.join(", ")
        );
        return EXIT_USAGE;
    };

    // 크기 결정: 둘 다 없으면 원본 픽셀(96dpi 환산), 하나만 주면 원본 비율 유지.
    // 어느 쪽이든 최종 값은 봉투에 그대로 실어 "조용한 보정" 이 없게 한다.
    let (width_hu, height_hu) = match (width_arg, height_arg) {
        (Some(w), Some(h)) => (w, h),
        (Some(w), None) => (
            w,
            ((w as u64 * natural_h_px as u64) / natural_w_px as u64).max(1) as u32,
        ),
        (None, Some(h)) => (
            ((h as u64 * natural_w_px as u64) / natural_h_px as u64).max(1) as u32,
            h,
        ),
        (None, None) => (
            natural_w_px.saturating_mul(HWPUNIT_PER_PX),
            natural_h_px.saturating_mul(HWPUNIT_PER_PX),
        ),
    };
    // 코어는 offset·크기를 i32/u32 로 다룬다. 범위를 넘는 값이 조용히 감기면 도장이
    // 엉뚱한 곳에 찍히므로 인자 오류로 끊는다.
    for (name, value) in [
        ("--x", x_hu),
        ("--y", y_hu),
        ("--width", width_hu),
        ("--height", height_hu),
    ] {
        if value > i32::MAX as u32 {
            eprintln!(
                "오류: {name} 값이 너무 큽니다 (HWPUNIT 최대 {}): {value}",
                i32::MAX
            );
            return EXIT_USAGE;
        }
    }

    let bytes = match fs::read(file_path) {
        Ok(d) => d,
        Err(e) => {
            eprintln!("오류: 파일을 읽을 수 없습니다 - {}: {}", file_path, e);
            return EXIT_RUNTIME;
        }
    };
    let mut doc = match rhwp::wasm_api::HwpDocument::from_bytes(&bytes) {
        Ok(d) => d,
        Err(e) => {
            eprintln!("오류: HWP 파싱 실패 - {}", e);
            return EXIT_RUNTIME;
        }
    };

    let page_count = doc.page_count();
    if page_arg >= page_count {
        eprintln!(
            "오류: 페이지 번호가 범위를 벗어났습니다 (0~{}): {page_arg}",
            page_count.saturating_sub(1)
        );
        return EXIT_USAGE;
    }
    let Some((sec, para)) = insert_image_page_anchor(&doc, page_arg) else {
        eprintln!("오류: {page_arg}쪽(0 기준)에서 그림을 붙일 본문 문단을 찾지 못했습니다.");
        return EXIT_RUNTIME;
    };

    // [#3480 과 같은 취지] 쪽 밖으로 나가면 **조용히 자르지 않는다**. 에이전트는 렌더
    // 결과를 보지 않으므로 신호가 없으면 잘려 나간 도장을 완성본으로 판단한다.
    let page_def = &doc.document().sections[sec].section_def.page_def;
    let (paper_w, paper_h) = if page_def.landscape {
        (page_def.height as i64, page_def.width as i64)
    } else {
        (page_def.width as i64, page_def.height as i64)
    };
    let right = x_hu as i64 + width_hu as i64;
    let bottom = y_hu as i64 + height_hu as i64;
    let overflow = if right > paper_w || bottom > paper_h {
        Some(serde_json::json!({
            "page": page_arg,
            "paperWidthHu": paper_w,
            "paperHeightHu": paper_h,
            "rightHu": right,
            "bottomHu": bottom,
            "overflowXHu": (right - paper_w).max(0),
            "overflowYHu": (bottom - paper_h).max(0),
        }))
    } else {
        None
    };

    let mut bin_data_id = serde_json::Value::Null;
    let mut ctrl_value = serde_json::Value::Null;
    if !dry_run {
        // 그림 설명(대체 텍스트)은 파일명 — 한컴이 개체 속성에 보여 주는 값이다.
        let description = Path::new(image_path)
            .file_name()
            .map(|n| n.to_string_lossy().to_string())
            .unwrap_or_default();
        let inserted = match doc.insert_picture_native(
            sec,
            para,
            0,
            &[],
            &image_bytes,
            width_hu,
            height_hu,
            natural_w_px,
            natural_h_px,
            &image_ext,
            &description,
            Some(x_hu as i32),
            Some(y_hu as i32),
        ) {
            Ok(v) => v,
            Err(e) => {
                eprintln!("오류: 그림 삽입 실패 - {}", e);
                // 실패 시 원본 불변 — 출력 파일을 쓰지 않고 즉시 끝낸다.
                return EXIT_RUNTIME;
            }
        };
        // binDataId 는 새 조회 API 없이 방금 삽입한 컨트롤에서 직접 읽는다 —
        // 같은 그림을 다시 참조하거나(도장 재사용) 산출물을 감사할 때 쓰는 주소다.
        let ctrl_idx = serde_json::from_str::<serde_json::Value>(&inserted)
            .ok()
            .and_then(|v| v["controlIdx"].as_u64())
            .map(|v| v as usize);
        if let Some(rhwp::model::control::Control::Picture(picture)) =
            ctrl_idx.and_then(|ctrl_idx| {
                doc.document()
                    .sections
                    .get(sec)
                    .and_then(|s| s.paragraphs.get(para))
                    .and_then(|p| p.controls.get(ctrl_idx))
            })
        {
            bin_data_id = serde_json::json!(picture.image_attr.bin_data_id);
            ctrl_value = serde_json::json!(ctrl_idx);
        }
    }

    // [#3383] 입력 형식을 보존한다 — 기본 확장자도 산출 형식을 따른다.
    let out_format = edit_output_format(&bytes, out_path.as_deref());
    let output_path = out_path.unwrap_or_else(|| {
        let stem = Path::new(file_path)
            .file_stem()
            .map(|s| s.to_string_lossy().to_string())
            .unwrap_or_else(|| "output".to_string());
        format!("{}_image.{}", stem, out_format.ext())
    });

    let mut verify_report = serde_json::Value::Null;
    let mut verify_failed = false;
    if !dry_run {
        let out_bytes = match edit_serialize(&mut doc, out_format) {
            Ok(b) => b,
            Err(e) => {
                eprintln!(
                    "오류: {} 직렬화 실패 - {}",
                    out_format.label().to_uppercase(),
                    e
                );
                return EXIT_RUNTIME;
            }
        };
        if let Err(e) = fs::write(&output_path, &out_bytes) {
            eprintln!("오류: 출력 쓰기 실패 - {}: {}", output_path, e);
            return EXIT_RUNTIME;
        }
        // [#3702] 저장 직후 자기검증 — 편집 후 IR ↔ 저장본 재파싱 IR.
        if verify_mode {
            let cross = out_format == EditOutputFormat::Hwp
                && rhwp::parser::detect_format(&bytes) == rhwp::parser::FileFormat::Hwpx;
            let (report, failed) = edit_verify_report(&doc, &out_bytes, cross);
            verify_report = report;
            verify_failed = failed;
        }
    }

    // [#3712] 눈검증 대상 페이지 — 앵커 문단이 걸친 쪽 전부.
    let changed_pages = if dry_run {
        serde_json::Value::Null
    } else {
        match doc.pages_covering_paragraphs(&[(sec, para)]) {
            Some(pages) => serde_json::json!(pages),
            None => serde_json::Value::Null,
        }
    };

    if json_mode {
        let mut envelope = serde_json::json!({
            "schemaVersion": ENVELOPE_SCHEMA_VERSION,
            "source": file_path,
            "image": image_path,
            "page": page_arg,
            "x": x_hu,
            "y": y_hu,
            "width": width_hu,
            "height": height_hu,
            "binDataId": bin_data_id,
            "section": sec,
            "paragraph": para,
            "ctrl": ctrl_value,
            "dryRun": dry_run,
            "changedPages": changed_pages,
            "overflow": overflow.clone().map(|o| vec![o]).unwrap_or_default(),
        });
        if !dry_run {
            envelope["output"] = serde_json::Value::String(output_path.clone());
            envelope["outputFormat"] = serde_json::Value::String(out_format.label().to_string());
            envelope["verify"] = verify_report.clone();
        }
        // [#3885] 이 봉투의 값은 전부 호출자 인자·엔진 판정이라 문서 유래 경로가
        // 없지만, 표지 자체는 항상 싣는다 — 키 부재는 "안전"이 아니라 "판정 안 함"
        // 으로 읽어야 하기 때문이다(S1).
        println!("{}", provenance::marked(envelope, "edit"));
        if verify_failed {
            process::exit(3);
        }
        return EXIT_OK;
    }

    if dry_run {
        println!(
            "배치 예정: {} {}쪽 ({}, {}) 크기 {}×{} HWPUNIT ← {} (원본 {}×{}px)",
            file_path,
            page_arg,
            x_hu,
            y_hu,
            width_hu,
            height_hu,
            image_path,
            natural_w_px,
            natural_h_px
        );
    } else {
        println!(
            "그림 삽입 완료: {} → {} — {}쪽 ({}, {}) 크기 {}×{} HWPUNIT ← {} (원본 {}×{}px)",
            file_path,
            output_path,
            page_arg,
            x_hu,
            y_hu,
            width_hu,
            height_hu,
            image_path,
            natural_w_px,
            natural_h_px
        );
    }
    if overflow.is_some() {
        eprintln!(
            "경고: 그림이 쪽 밖으로 나갑니다 (용지 {}×{} HWPUNIT, 오른쪽 {} 아래 {}) — 상세는 --json 의 overflow",
            paper_w, paper_h, right, bottom
        );
    }
    if verify_failed {
        eprintln!("검증 실패(--verify): 저장본 재파싱 IR 차이 — 상세는 --json 또는 ir-diff");
        process::exit(3);
    }
    EXIT_OK
}

/// `edit insert-picture` — 문단 좌표에 본문 그림을 끼운다. 코어 `insert_picture_native`.
/// `insert-image`(도장·서명, 쪽 좌표) 와 다르다.
pub(super) fn edit_insert_picture(args: &[String]) -> i32 {
    const USAGE: &str = "사용법: rhwp edit insert-picture <파일> --image <그림> [--section N --para N | --table N --row N --col N [--cell-para N]] [--offset N] [--width N] [--height N] [--x N] [--y N] [-o <출력>] [--dry-run] [--verify] [--json]";
    let mut file_path: Option<&str> = None;
    let mut image_path: Option<&str> = None;
    let mut section: usize = 0;
    let mut para: usize = 0;
    let mut body_target_given = false;
    let mut cell_args = CellTargetArgs::default();
    let mut offset: usize = 0;
    let mut x_hu: u32 = 0;
    let mut y_hu: u32 = 0;
    let mut width_arg: Option<u32> = None;
    let mut height_arg: Option<u32> = None;
    let mut out_path: Option<String> = None;
    let mut dry_run = false;
    let mut json_mode = false;
    let mut verify_mode = false;
    let mut i = 0;
    while i < args.len() {
        match args[i].as_str() {
            "--image" => {
                i += 1;
                match args.get(i) {
                    Some(v) => image_path = Some(v),
                    None => {
                        eprintln!("오류: --image 뒤에 그림 파일 경로가 필요합니다.");
                        return EXIT_USAGE;
                    }
                }
            }
            "--section" | "--para" | "--offset" | "--x" | "--y" | "--width" | "--height" => {
                let name = args[i].clone();
                i += 1;
                let Some(v) = args.get(i) else {
                    eprintln!("오류: {name} 뒤에 0 이상의 정수가 필요합니다.");
                    return EXIT_USAGE;
                };
                if matches!(name.as_str(), "--section" | "--para") {
                    body_target_given = true;
                }
                match name.as_str() {
                    "--section" => match v.parse::<usize>() {
                        Ok(n) => section = n,
                        Err(_) => {
                            eprintln!("오류: --section 뒤에 0 이상의 정수가 필요합니다: {v}");
                            return EXIT_USAGE;
                        }
                    },
                    "--para" => match v.parse::<usize>() {
                        Ok(n) => para = n,
                        Err(_) => {
                            eprintln!("오류: --para 뒤에 0 이상의 정수가 필요합니다: {v}");
                            return EXIT_USAGE;
                        }
                    },
                    "--offset" => match v.parse::<usize>() {
                        Ok(n) => offset = n,
                        Err(_) => {
                            eprintln!("오류: --offset 뒤에 0 이상의 정수가 필요합니다: {v}");
                            return EXIT_USAGE;
                        }
                    },
                    "--x" => match v.parse::<u32>() {
                        Ok(n) => x_hu = n,
                        Err(_) => {
                            eprintln!("오류: --x 뒤에 0 이상의 정수가 필요합니다 (HWPUNIT): {v}");
                            return EXIT_USAGE;
                        }
                    },
                    "--y" => match v.parse::<u32>() {
                        Ok(n) => y_hu = n,
                        Err(_) => {
                            eprintln!("오류: --y 뒤에 0 이상의 정수가 필요합니다 (HWPUNIT): {v}");
                            return EXIT_USAGE;
                        }
                    },
                    "--width" => match v.parse::<u32>() {
                        Ok(n) => width_arg = Some(n),
                        Err(_) => {
                            eprintln!(
                                "오류: --width 뒤에 0 이상의 정수가 필요합니다 (HWPUNIT): {v}"
                            );
                            return EXIT_USAGE;
                        }
                    },
                    _ => match v.parse::<u32>() {
                        Ok(n) => height_arg = Some(n),
                        Err(_) => {
                            eprintln!(
                                "오류: --height 뒤에 0 이상의 정수가 필요합니다 (HWPUNIT): {v}"
                            );
                            return EXIT_USAGE;
                        }
                    },
                }
            }
            "--table" | "--row" | "--col" | "--cell-para" => {
                let name = args[i].clone();
                i += 1;
                if let Err(code) = cell_args.parse(&name, args.get(i)) {
                    return code;
                }
            }
            "-o" | "--output" => {
                i += 1;
                match args.get(i) {
                    Some(v) => out_path = Some(v.clone()),
                    None => {
                        eprintln!("오류: -o 뒤에 출력 파일 경로가 필요합니다.");
                        return EXIT_USAGE;
                    }
                }
            }
            "--dry-run" => dry_run = true,
            "--json" => json_mode = true,
            "--verify" => verify_mode = true,
            other if other.starts_with('-') => {
                eprintln!("알 수 없는 옵션: {other}");
                return EXIT_USAGE;
            }
            other => {
                if file_path.replace(other).is_some() {
                    eprintln!("오류: 입력 파일은 하나만 지정할 수 있습니다: {other}");
                    return EXIT_USAGE;
                }
            }
        }
        i += 1;
    }
    let (Some(file_path), Some(image_path)) = (file_path, image_path) else {
        eprintln!("{USAGE}");
        return EXIT_USAGE;
    };
    for (name, value) in [("--width", width_arg), ("--height", height_arg)] {
        if value == Some(0) {
            eprintln!("오류: {name} 는 1 이상이어야 합니다 (HWPUNIT, 1/7200 inch).");
            return EXIT_USAGE;
        }
    }
    let image_ext = Path::new(image_path)
        .extension()
        .map(|e| e.to_string_lossy().to_ascii_lowercase())
        .unwrap_or_default();
    if !INSERT_IMAGE_FORMATS.contains(&image_ext.as_str()) {
        eprintln!(
            "오류: 지원하지 않는 그림 형식입니다 - {} (지원: {})",
            if image_ext.is_empty() {
                "확장자 없음".to_string()
            } else {
                image_ext.clone()
            },
            INSERT_IMAGE_FORMATS.join(", ")
        );
        return EXIT_USAGE;
    }
    let image_bytes = match fs::read(image_path) {
        Ok(d) => d,
        Err(e) => {
            eprintln!("오류: 그림 파일을 읽을 수 없습니다 - {}: {}", image_path, e);
            return EXIT_RUNTIME;
        }
    };
    let Some((natural_w_px, natural_h_px)) = insert_image_dimensions(&image_bytes) else {
        eprintln!(
            "오류: 그림 형식을 알아볼 수 없습니다 - {} (지원: {})",
            image_path,
            INSERT_IMAGE_FORMATS.join(", ")
        );
        return EXIT_USAGE;
    };
    let (width_hu, height_hu) = match (width_arg, height_arg) {
        (Some(w), Some(h)) => (w, h),
        (Some(w), None) => (
            w,
            ((w as u64 * natural_h_px as u64) / natural_w_px as u64).max(1) as u32,
        ),
        (None, Some(h)) => (
            ((h as u64 * natural_w_px as u64) / natural_h_px as u64).max(1) as u32,
            h,
        ),
        (None, None) => (
            natural_w_px.saturating_mul(HWPUNIT_PER_PX),
            natural_h_px.saturating_mul(HWPUNIT_PER_PX),
        ),
    };
    for (name, value) in [
        ("--x", x_hu),
        ("--y", y_hu),
        ("--width", width_hu),
        ("--height", height_hu),
    ] {
        if value > i32::MAX as u32 {
            eprintln!(
                "오류: {name} 값이 너무 큽니다 (HWPUNIT 최대 {}): {value}",
                i32::MAX
            );
            return EXIT_USAGE;
        }
    }
    let bytes = match fs::read(file_path) {
        Ok(d) => d,
        Err(e) => {
            eprintln!("오류: 파일을 읽을 수 없습니다 - {}: {}", file_path, e);
            return EXIT_RUNTIME;
        }
    };
    let mut doc = match load_document(&bytes) {
        Ok(d) => d,
        Err(e) => return e.report(),
    };
    let cell_path = match cell_args.resolve(&doc, body_target_given) {
        Ok(Some((sec, host_para, path))) => {
            section = sec;
            para = host_para;
            path
        }
        Ok(None) => Vec::new(),
        Err(code) => return code,
    };
    let section_count = doc.document().sections.len();
    if section >= section_count {
        eprintln!(
            "오류: --section 이 범위를 벗어났습니다 (0~{}): {section}",
            section_count.saturating_sub(1)
        );
        return EXIT_USAGE;
    }
    let para_count = doc.document().sections[section].paragraphs.len();
    if para >= para_count {
        eprintln!(
            "오류: --para 이 범위를 벗어났습니다 (구역 {section} 문단 0~{}): {para}",
            para_count.saturating_sub(1)
        );
        return EXIT_USAGE;
    }
    let mut bin_data_id = serde_json::Value::Null;
    let mut ctrl_value = serde_json::Value::Null;
    let mut cell_ctrl_value = serde_json::Value::Null;
    if !dry_run {
        let description = Path::new(image_path)
            .file_name()
            .map(|n| n.to_string_lossy().to_string())
            .unwrap_or_default();
        let inserted = if cell_path.is_empty() {
            doc.insert_picture_native(
                section,
                para,
                offset,
                &[],
                &image_bytes,
                width_hu,
                height_hu,
                natural_w_px,
                natural_h_px,
                &image_ext,
                &description,
                Some(x_hu as i32),
                Some(y_hu as i32),
            )
        } else {
            doc.insert_picture_in_cell_native(
                section,
                para,
                offset,
                &cell_path,
                &image_bytes,
                width_hu,
                height_hu,
                natural_w_px,
                natural_h_px,
                &image_ext,
                &description,
                Some(x_hu as i32),
                Some(y_hu as i32),
            )
        };
        let inserted = match inserted {
            Ok(v) => v,
            Err(e) => {
                eprintln!("오류: 그림 삽입 실패 - {e}");
                return EXIT_RUNTIME;
            }
        };
        let ctrl_idx = serde_json::from_str::<serde_json::Value>(&inserted)
            .ok()
            .and_then(|v| v["controlIdx"].as_u64())
            .map(|v| v as usize);
        if let Some(rhwp::model::control::Control::Picture(picture)) =
            ctrl_idx.and_then(|ctrl_idx| {
                paragraph_at(doc.document(), section, para, &cell_path)
                    .and_then(|p| p.controls.get(ctrl_idx))
            })
        {
            bin_data_id = serde_json::json!(picture.image_attr.bin_data_id);
            // 칸 안 그림의 번호는 칸 문단 안 번호라 본문 문단 기준인 ctrl 에 싣지 않는다.
            if cell_path.is_empty() {
                ctrl_value = serde_json::json!(ctrl_idx);
            } else {
                cell_ctrl_value = serde_json::json!(ctrl_idx);
            }
        }
    }
    finish_edit_write(
        &mut doc,
        &bytes,
        file_path,
        out_path,
        "picture",
        dry_run,
        json_mode,
        verify_mode,
        serde_json::json!({
            "image": image_path,
            "section": section,
            "paragraph": para,
            "offset": offset,
            "x": x_hu,
            "y": y_hu,
            "width": width_hu,
            "height": height_hu,
            "binDataId": bin_data_id,
            "ctrl": ctrl_value,
            "table": cell_args.table,
            "row": cell_args.row,
            "col": cell_args.col,
            "cellPara": cell_args.table.map(|_| cell_args.cell_para),
            "cellCtrl": cell_ctrl_value,
        }),
        &[(section, para)],
        &format!(
            "그림 삽입 예정: {file_path} 구역 {section} 문단 {para} 오프셋 {offset} ← {image_path}"
        ),
        &format!("그림 삽입 완료: {file_path}"),
    )
}

/// `edit delete-picture` — 본문 그림 컨트롤 삭제. 코어 `delete_picture_control_native`.
pub(super) fn edit_delete_picture(args: &[String]) -> i32 {
    const USAGE: &str = "사용법: rhwp edit delete-picture <파일> --section N --para N --ctrl N [-o <출력>] [--dry-run] [--verify] [--json]";
    let mut file_path: Option<&str> = None;
    let mut section: Option<usize> = None;
    let mut para: Option<usize> = None;
    let mut ctrl: Option<usize> = None;
    let mut out_path: Option<String> = None;
    let mut dry_run = false;
    let mut json_mode = false;
    let mut verify_mode = false;
    let mut i = 0;
    while i < args.len() {
        match args[i].as_str() {
            "--section" | "--para" | "--ctrl" => {
                let name = args[i].clone();
                i += 1;
                let Some(v) = args.get(i) else {
                    eprintln!("오류: {name} 뒤에 0 이상의 정수가 필요합니다.");
                    return EXIT_USAGE;
                };
                match v.parse::<usize>() {
                    Ok(n) => match name.as_str() {
                        "--section" => section = Some(n),
                        "--para" => para = Some(n),
                        _ => ctrl = Some(n),
                    },
                    Err(_) => {
                        eprintln!("오류: {name} 뒤에 0 이상의 정수가 필요합니다: {v}");
                        return EXIT_USAGE;
                    }
                }
            }
            "-o" | "--output" => {
                i += 1;
                match args.get(i) {
                    Some(v) => out_path = Some(v.clone()),
                    None => {
                        eprintln!("오류: -o 뒤에 출력 파일 경로가 필요합니다.");
                        return EXIT_USAGE;
                    }
                }
            }
            "--dry-run" => dry_run = true,
            "--json" => json_mode = true,
            "--verify" => verify_mode = true,
            other if other.starts_with('-') => {
                eprintln!("알 수 없는 옵션: {other}");
                return EXIT_USAGE;
            }
            other => {
                if file_path.replace(other).is_some() {
                    eprintln!("오류: 입력 파일은 하나만 지정할 수 있습니다: {other}");
                    return EXIT_USAGE;
                }
            }
        }
        i += 1;
    }
    let (Some(file_path), Some(section), Some(para), Some(ctrl)) = (file_path, section, para, ctrl)
    else {
        eprintln!("{USAGE}");
        return EXIT_USAGE;
    };
    let bytes = match fs::read(file_path) {
        Ok(d) => d,
        Err(e) => {
            eprintln!("오류: 파일을 읽을 수 없습니다 - {}: {}", file_path, e);
            return EXIT_RUNTIME;
        }
    };
    let mut doc = match load_document(&bytes) {
        Ok(d) => d,
        Err(e) => return e.report(),
    };
    if !dry_run {
        if let Err(e) = doc.delete_picture_control_native(section, para, ctrl) {
            eprintln!("오류: 그림 삭제 실패 - {e}");
            return EXIT_RUNTIME;
        }
    }
    finish_edit_write(
        &mut doc,
        &bytes,
        file_path,
        out_path,
        "delpic",
        dry_run,
        json_mode,
        verify_mode,
        serde_json::json!({ "section": section, "paragraph": para, "ctrl": ctrl }),
        &[(section, para)],
        &format!("그림 삭제 예정: {file_path} 구역 {section} 문단 {para} 컨트롤 {ctrl}"),
        &format!("그림 삭제 완료: {file_path}"),
    )
}

/// `edit set-picture` — 본문 그림 속성. 코어 `set_picture_properties_native`.
pub(super) fn edit_set_picture(args: &[String]) -> i32 {
    const USAGE: &str = "사용법: rhwp edit set-picture <파일> --section N --para N --ctrl N --props <JSON> [-o <출력>] [--dry-run] [--verify] [--json]";
    let mut file_path: Option<&str> = None;
    let mut section: Option<usize> = None;
    let mut para: Option<usize> = None;
    let mut ctrl: Option<usize> = None;
    let mut props: Option<String> = None;
    let mut out_path: Option<String> = None;
    let mut dry_run = false;
    let mut json_mode = false;
    let mut verify_mode = false;
    let mut i = 0;
    while i < args.len() {
        match args[i].as_str() {
            "--section" | "--para" | "--ctrl" => {
                let name = args[i].clone();
                i += 1;
                let Some(v) = args.get(i) else {
                    eprintln!("오류: {name} 뒤에 0 이상의 정수가 필요합니다.");
                    return EXIT_USAGE;
                };
                match v.parse::<usize>() {
                    Ok(n) => match name.as_str() {
                        "--section" => section = Some(n),
                        "--para" => para = Some(n),
                        _ => ctrl = Some(n),
                    },
                    Err(_) => {
                        eprintln!("오류: {name} 뒤에 0 이상의 정수가 필요합니다: {v}");
                        return EXIT_USAGE;
                    }
                }
            }
            "--props" => {
                i += 1;
                match args.get(i) {
                    Some(v) => props = Some(v.clone()),
                    None => {
                        eprintln!("오류: --props 뒤에 JSON 문자열이 필요합니다.");
                        return EXIT_USAGE;
                    }
                }
            }
            "-o" | "--output" => {
                i += 1;
                match args.get(i) {
                    Some(v) => out_path = Some(v.clone()),
                    None => {
                        eprintln!("오류: -o 뒤에 출력 파일 경로가 필요합니다.");
                        return EXIT_USAGE;
                    }
                }
            }
            "--dry-run" => dry_run = true,
            "--json" => json_mode = true,
            "--verify" => verify_mode = true,
            other if other.starts_with('-') => {
                eprintln!("알 수 없는 옵션: {other}");
                return EXIT_USAGE;
            }
            other => {
                if file_path.replace(other).is_some() {
                    eprintln!("오류: 입력 파일은 하나만 지정할 수 있습니다: {other}");
                    return EXIT_USAGE;
                }
            }
        }
        i += 1;
    }
    let (Some(file_path), Some(section), Some(para), Some(ctrl), Some(props)) =
        (file_path, section, para, ctrl, props)
    else {
        eprintln!("{USAGE}");
        return EXIT_USAGE;
    };
    let props = match rhwp::document_core::check_picture_props(&props) {
        Ok(props) => props,
        Err(e) => {
            eprintln!("오류: {e}");
            return EXIT_USAGE;
        }
    };
    let bytes = match fs::read(file_path) {
        Ok(d) => d,
        Err(e) => {
            eprintln!("오류: 파일을 읽을 수 없습니다 - {}: {}", file_path, e);
            return EXIT_RUNTIME;
        }
    };
    let mut doc = match load_document(&bytes) {
        Ok(d) => d,
        Err(e) => return e.report(),
    };
    if !dry_run {
        if let Err(e) = doc.set_picture_properties_native(section, para, ctrl, &props) {
            eprintln!("오류: 그림 속성 설정 실패 - {e}");
            return EXIT_RUNTIME;
        }
    }
    finish_edit_write(
        &mut doc,
        &bytes,
        file_path,
        out_path,
        "setpic",
        dry_run,
        json_mode,
        verify_mode,
        serde_json::json!({ "section": section, "paragraph": para, "ctrl": ctrl }),
        &[(section, para)],
        &format!("그림 속성 변경 예정: {file_path} 구역 {section} 문단 {para} 컨트롤 {ctrl}"),
        &format!("그림 속성 변경 완료: {file_path}"),
    )
}

/// `--table N --row N --col N [--cell-para N]` 칸 지정 인자 (#9020).
#[derive(Default)]
struct CellTargetArgs {
    table: Option<usize>,
    row: Option<u16>,
    col: Option<u16>,
    cell_para: usize,
    cell_para_given: bool,
}

impl CellTargetArgs {
    /// `name` 옵션의 값을 읽는다. 실패하면 사용법 오류 종료 코드를 돌려준다.
    fn parse(&mut self, name: &str, value: Option<&String>) -> Result<(), i32> {
        let Some(v) = value else {
            eprintln!("오류: {name} 뒤에 0 이상의 정수가 필요합니다.");
            return Err(EXIT_USAGE);
        };
        let bad = || {
            eprintln!("오류: {name} 뒤에 0 이상의 정수가 필요합니다: {v}");
            EXIT_USAGE
        };
        match name {
            "--table" => self.table = Some(v.parse().map_err(|_| bad())?),
            "--row" => self.row = Some(v.parse().map_err(|_| bad())?),
            "--col" => self.col = Some(v.parse().map_err(|_| bad())?),
            _ => {
                self.cell_para = v.parse().map_err(|_| bad())?;
                self.cell_para_given = true;
            }
        }
        Ok(())
    }

    /// 칸 지정을 (구역, 표를 담은 본문 문단, 칸 문단 경로) 로 바꾼다. 칸 지정이 없으면 `None`.
    ///
    /// `body_target_given` 은 같은 명령에 본문 문단 지정(`--section`/`--para` 등)이 함께 왔는지다.
    #[allow(clippy::type_complexity)]
    fn resolve(
        &self,
        doc: &rhwp::wasm_api::HwpDocument,
        body_target_given: bool,
    ) -> Result<Option<(usize, usize, Vec<(usize, usize, usize)>)>, i32> {
        let Some(table_no) = self.table else {
            if self.row.is_some() || self.col.is_some() || self.cell_para_given {
                eprintln!("오류: --row/--col/--cell-para 는 --table 과 함께 써야 합니다.");
                return Err(EXIT_USAGE);
            }
            return Ok(None);
        };
        if body_target_given {
            eprintln!("오류: --table 칸 지정과 본문 문단 지정은 함께 쓸 수 없습니다.");
            return Err(EXIT_USAGE);
        }
        let (Some(row), Some(col)) = (self.row, self.col) else {
            eprintln!("오류: --table 을 쓰면 --row 와 --col 도 필요합니다.");
            return Err(EXIT_USAGE);
        };
        let (sec, para, ctrl, cell_idx, para_lens, _) =
            match super::resolve_table_cell(doc.document(), table_no, row, col) {
                Ok(v) => v,
                Err(super::CellResolveError::Usage(msg)) => {
                    eprintln!("{msg}");
                    return Err(EXIT_USAGE);
                }
                Err(super::CellResolveError::Runtime(msg)) => {
                    eprintln!("{msg}");
                    return Err(EXIT_RUNTIME);
                }
            };
        if self.cell_para >= para_lens.len() {
            eprintln!(
                "오류: --cell-para 가 범위를 벗어났습니다 (칸 문단 0~{}): {}",
                para_lens.len().saturating_sub(1),
                self.cell_para
            );
            return Err(EXIT_USAGE);
        }
        Ok(Some((sec, para, vec![(ctrl, cell_idx, self.cell_para)])))
    }
}

/// 본문 문단 `para` 에서 `path`(표 컨트롤·칸·칸 문단 번호)를 따라간 문단.
fn paragraph_at<'a>(
    document: &'a rhwp::model::document::Document,
    section: usize,
    para: usize,
    path: &[(usize, usize, usize)],
) -> Option<&'a rhwp::model::paragraph::Paragraph> {
    use rhwp::model::control::Control;
    let mut current = document.sections.get(section)?.paragraphs.get(para)?;
    for &(ctrl, cell, cell_para) in path {
        current = match current.controls.get(ctrl)? {
            Control::Table(table) => table.cells.get(cell)?.paragraphs.get(cell_para)?,
            _ => return None,
        };
    }
    Some(current)
}

/// `edit move-picture` — 본문의 떠 있는 그림을 다른 본문 문단이나 표 칸 문단으로 옮긴다 (#9020).
/// 코어 `relocate_floating_picture_native`.
pub(super) fn edit_move_picture(args: &[String]) -> i32 {
    const USAGE: &str = "사용법: rhwp edit move-picture <파일> --section N --para N --ctrl N (--to-para N [--to-section N] | --table N --row N --col N [--cell-para N]) [--to-offset N] [--x N] [--y N] [-o <출력>] [--dry-run] [--verify] [--json]";
    let mut file_path: Option<&str> = None;
    let mut section: Option<usize> = None;
    let mut para: Option<usize> = None;
    let mut ctrl: Option<usize> = None;
    let mut to_section: Option<usize> = None;
    let mut to_para: Option<usize> = None;
    let mut to_offset: usize = 0;
    let mut x_arg: Option<i32> = None;
    let mut y_arg: Option<i32> = None;
    let mut cell_args = CellTargetArgs::default();
    let mut out_path: Option<String> = None;
    let mut dry_run = false;
    let mut json_mode = false;
    let mut verify_mode = false;
    let mut i = 0;
    while i < args.len() {
        match args[i].as_str() {
            "--section" | "--para" | "--ctrl" | "--to-section" | "--to-para" | "--to-offset" => {
                let name = args[i].clone();
                i += 1;
                let Some(v) = args.get(i) else {
                    eprintln!("오류: {name} 뒤에 0 이상의 정수가 필요합니다.");
                    return EXIT_USAGE;
                };
                let Ok(n) = v.parse::<usize>() else {
                    eprintln!("오류: {name} 뒤에 0 이상의 정수가 필요합니다: {v}");
                    return EXIT_USAGE;
                };
                match name.as_str() {
                    "--section" => section = Some(n),
                    "--para" => para = Some(n),
                    "--ctrl" => ctrl = Some(n),
                    "--to-section" => to_section = Some(n),
                    "--to-para" => to_para = Some(n),
                    _ => to_offset = n,
                }
            }
            "--x" | "--y" => {
                let name = args[i].clone();
                i += 1;
                let Some(Ok(n)) = args.get(i).map(|v| v.parse::<i32>()) else {
                    eprintln!("오류: {name} 뒤에 정수가 필요합니다 (HWPUNIT).");
                    return EXIT_USAGE;
                };
                if name == "--x" {
                    x_arg = Some(n);
                } else {
                    y_arg = Some(n);
                }
            }
            "--table" | "--row" | "--col" | "--cell-para" => {
                let name = args[i].clone();
                i += 1;
                if let Err(code) = cell_args.parse(&name, args.get(i)) {
                    return code;
                }
            }
            "-o" | "--output" => {
                i += 1;
                match args.get(i) {
                    Some(v) => out_path = Some(v.clone()),
                    None => {
                        eprintln!("오류: -o 뒤에 출력 파일 경로가 필요합니다.");
                        return EXIT_USAGE;
                    }
                }
            }
            "--dry-run" => dry_run = true,
            "--json" => json_mode = true,
            "--verify" => verify_mode = true,
            other if other.starts_with('-') => {
                eprintln!("알 수 없는 옵션: {other}");
                return EXIT_USAGE;
            }
            other => {
                if file_path.replace(other).is_some() {
                    eprintln!("오류: 입력 파일은 하나만 지정할 수 있습니다: {other}");
                    return EXIT_USAGE;
                }
            }
        }
        i += 1;
    }
    let (Some(file_path), Some(section), Some(para), Some(ctrl)) = (file_path, section, para, ctrl)
    else {
        eprintln!("{USAGE}");
        return EXIT_USAGE;
    };
    if to_para.is_none() && cell_args.table.is_none() {
        eprintln!("오류: 옮길 자리로 --to-para 나 --table/--row/--col 중 하나가 필요합니다.");
        eprintln!("{USAGE}");
        return EXIT_USAGE;
    }
    let bytes = match fs::read(file_path) {
        Ok(d) => d,
        Err(e) => {
            eprintln!("오류: 파일을 읽을 수 없습니다 - {}: {}", file_path, e);
            return EXIT_RUNTIME;
        }
    };
    let mut doc = match load_document(&bytes) {
        Ok(d) => d,
        Err(e) => return e.report(),
    };
    let body_target_given = to_para.is_some() || to_section.is_some();
    let (dst_section, dst_para, dst_path) = match cell_args.resolve(&doc, body_target_given) {
        Ok(Some(target)) => target,
        Ok(None) => (
            to_section.unwrap_or(section),
            to_para.unwrap_or(0),
            Vec::new(),
        ),
        Err(code) => return code,
    };
    if paragraph_at(doc.document(), dst_section, dst_para, &dst_path).is_none() {
        eprintln!("오류: 옮길 자리 구역 {dst_section} 문단 {dst_para} 가 없습니다.");
        return EXIT_USAGE;
    }
    // 옮길 그림의 현재 위치. 본문 문단으로 옮기면서 --x/--y 를 생략하면 그대로 쓴다.
    let current_offsets = match doc
        .document()
        .sections
        .get(section)
        .and_then(|s| s.paragraphs.get(para))
        .and_then(|p| p.controls.get(ctrl))
    {
        Some(rhwp::model::control::Control::Picture(pic)) if !pic.common.treat_as_char => (
            pic.common.horizontal_offset as i32,
            pic.common.vertical_offset as i32,
        ),
        Some(rhwp::model::control::Control::Picture(_)) => {
            eprintln!("오류: 글자처럼 취급하는 그림은 옮길 수 없습니다. set-picture 로 treatAsChar 를 끈 뒤 옮기세요.");
            return EXIT_RUNTIME;
        }
        _ => {
            eprintln!("오류: 구역 {section} 문단 {para} 컨트롤 {ctrl} 은 그림이 아닙니다.");
            return EXIT_RUNTIME;
        }
    };
    // 표 칸 문단으로 옮기면 기준이 칸 문단으로 바뀌므로, 생략한 거리는 0 으로 둔다.
    let default_offsets = if dst_path.is_empty() {
        current_offsets
    } else {
        (0, 0)
    };
    let x = x_arg.unwrap_or(default_offsets.0);
    let y = y_arg.unwrap_or(default_offsets.1);
    let mut new_ctrl = serde_json::Value::Null;
    if !dry_run {
        let moved = match doc.relocate_floating_picture_native(
            section,
            para,
            &[],
            ctrl,
            dst_section,
            dst_para,
            to_offset,
            &dst_path,
            x,
            y,
        ) {
            Ok(v) => v,
            Err(e) => {
                eprintln!("오류: 그림 옮기기 실패 - {e}");
                return EXIT_RUNTIME;
            }
        };
        new_ctrl = serde_json::from_str::<serde_json::Value>(&moved)
            .ok()
            .map(|v| v["controlIdx"].clone())
            .unwrap_or(serde_json::Value::Null);
    }
    let into_cell = !dst_path.is_empty();
    finish_edit_write(
        &mut doc,
        &bytes,
        file_path,
        out_path,
        "movepic",
        dry_run,
        json_mode,
        verify_mode,
        serde_json::json!({
            "section": section,
            "paragraph": para,
            "ctrl": ctrl,
            "toSection": dst_section,
            "toParagraph": dst_para,
            "toOffset": to_offset,
            "toCtrl": if into_cell { serde_json::Value::Null } else { new_ctrl.clone() },
            "table": cell_args.table,
            "row": cell_args.row,
            "col": cell_args.col,
            "cellPara": cell_args.table.map(|_| cell_args.cell_para),
            "cellCtrl": if into_cell { new_ctrl } else { serde_json::Value::Null },
            "x": x,
            "y": y,
        }),
        &[(section, para), (dst_section, dst_para)],
        &format!(
            "그림 옮기기 예정: {file_path} 구역 {section} 문단 {para} 컨트롤 {ctrl} → 구역 {dst_section} 문단 {dst_para}"
        ),
        &format!("그림 옮기기 완료: {file_path}"),
    )
}