hwpforge-blueprint 0.5.1

YAML-based style template system for HwpForge (Figma Design Token pattern)
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
//! Style types: character shapes, paragraph shapes, and their partial variants.
//!
//! The **two-type pattern** is central to Blueprint's design:
//!
//! - [`PartialCharShape`] / [`PartialParaShape`] — all fields `Option`,
//!   used for YAML deserialization and inheritance merging.
//! - [`CharShape`] / [`ParaShape`] — all fields required, produced after
//!   inheritance resolution when every field has a concrete value.
//!
//! This mirrors CSS inheritance: a child template can override only the
//! fields it cares about, inheriting the rest from the parent.

use hwpforge_core::{BulletDef, NumberingDef, ParagraphListRef};
use hwpforge_foundation::{
    Alignment, BorderFillIndex, BreakType, Color, EmbossType, EmphasisType, EngraveType,
    HeadingType, HwpUnit, LineSpacingType, OutlineType, ShadowType, StrikeoutShape, UnderlineType,
    VerticalPosition,
};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use crate::error::{BlueprintError, BlueprintResult};
use crate::serde_helpers::{
    de_color, de_color_opt, de_dim, de_dim_opt, de_pct_opt, ser_color, ser_color_opt, ser_dim,
    ser_dim_opt, ser_pct_opt,
};

// ---------------------------------------------------------------------------
// Helper types
// ---------------------------------------------------------------------------

/// Vertical spacing (before and after a paragraph).
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct Spacing {
    /// Space before the paragraph.
    #[serde(
        default,
        serialize_with = "ser_dim_opt",
        deserialize_with = "de_dim_opt",
        skip_serializing_if = "Option::is_none"
    )]
    pub before: Option<HwpUnit>,
    /// Space after the paragraph.
    #[serde(
        default,
        serialize_with = "ser_dim_opt",
        deserialize_with = "de_dim_opt",
        skip_serializing_if = "Option::is_none"
    )]
    pub after: Option<HwpUnit>,
}

/// Paragraph indentation.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct Indent {
    /// Left indentation.
    #[serde(
        default,
        serialize_with = "ser_dim_opt",
        deserialize_with = "de_dim_opt",
        skip_serializing_if = "Option::is_none"
    )]
    pub left: Option<HwpUnit>,
    /// Right indentation.
    #[serde(
        default,
        serialize_with = "ser_dim_opt",
        deserialize_with = "de_dim_opt",
        skip_serializing_if = "Option::is_none"
    )]
    pub right: Option<HwpUnit>,
    /// First-line indentation (can be negative for hanging indent).
    #[serde(
        default,
        serialize_with = "ser_dim_opt",
        deserialize_with = "de_dim_opt",
        skip_serializing_if = "Option::is_none"
    )]
    pub first_line: Option<HwpUnit>,
}

/// Line spacing configuration.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct LineSpacing {
    /// Spacing type (percentage, fixed, between-lines).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub spacing_type: Option<LineSpacingType>,
    /// The value: percentage (e.g. 160.0 for 160%) or fixed HwpUnit.
    #[serde(
        default,
        serialize_with = "ser_pct_opt",
        deserialize_with = "de_pct_opt",
        skip_serializing_if = "Option::is_none"
    )]
    pub value: Option<f64>,
}

// ---------------------------------------------------------------------------
// Partial types (for YAML and inheritance merging)
// ---------------------------------------------------------------------------

/// Character shape with all optional fields (for YAML parsing and inheritance).
///
/// After inheritance resolution, this is converted to [`CharShape`] where
/// all fields are guaranteed to be present.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, JsonSchema)]
pub struct PartialCharShape {
    /// Font name (e.g. "한컴바탕", "Arial").
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub font: Option<String>,
    /// Font size.
    #[serde(
        default,
        serialize_with = "ser_dim_opt",
        deserialize_with = "de_dim_opt",
        skip_serializing_if = "Option::is_none"
    )]
    pub size: Option<HwpUnit>,
    /// Bold weight.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bold: Option<bool>,
    /// Italic style.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub italic: Option<bool>,
    /// Text color in `#RRGGBB`.
    #[serde(
        default,
        serialize_with = "ser_color_opt",
        deserialize_with = "de_color_opt",
        skip_serializing_if = "Option::is_none"
    )]
    pub color: Option<Color>,

    /// Underline type (None/Bottom/Center/Top).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub underline_type: Option<UnderlineType>,
    /// Underline color (inherits text color if None).
    #[serde(
        default,
        serialize_with = "ser_color_opt",
        deserialize_with = "de_color_opt",
        skip_serializing_if = "Option::is_none"
    )]
    pub underline_color: Option<Color>,
    /// Strikeout line shape (None/Continuous/Dash/Dot/etc.).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub strikeout_shape: Option<StrikeoutShape>,
    /// Strikeout color (inherits text color if None).
    #[serde(
        default,
        serialize_with = "ser_color_opt",
        deserialize_with = "de_color_opt",
        skip_serializing_if = "Option::is_none"
    )]
    pub strikeout_color: Option<Color>,
    /// Text outline (1pt border around glyphs).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub outline: Option<OutlineType>,
    /// Drop shadow.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub shadow: Option<ShadowType>,
    /// Emboss effect (raised).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub emboss: Option<EmbossType>,
    /// Engrave effect (sunken).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub engrave: Option<EngraveType>,
    /// Vertical position (Normal/Superscript/Subscript).
    /// Replaces bool superscript/subscript (backward compat: both supported).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub vertical_position: Option<VerticalPosition>,
    /// Background shade color (character-level highlight).
    #[serde(
        default,
        serialize_with = "ser_color_opt",
        deserialize_with = "de_color_opt",
        skip_serializing_if = "Option::is_none"
    )]
    pub shade_color: Option<Color>,
    /// Emphasis mark type (symMark: NONE, DOT_ABOVE, etc.).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub emphasis: Option<EmphasisType>,
    /// Character width ratio (percent, uniform across all 7 lang groups).
    /// Default: 100. Range: 50-200.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ratio: Option<i32>,
    /// Inter-character spacing (percent, uniform).
    /// Default: 0. Negative = tighter.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub spacing: Option<i32>,
    /// Relative font size (percent, uniform).
    /// Default: 100.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rel_sz: Option<i32>,
    /// Vertical position offset (percent, uniform).
    /// Default: 0.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub offset: Option<i32>,
    /// Enable kerning (pair adjustment). Default: false.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub use_kerning: Option<bool>,
    /// Use font-defined inter-character spacing. Default: false.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub use_font_space: Option<bool>,
    /// Border/fill reference for character-level border.
    ///
    /// References a `borderFill` entry by raw ID. `None` = use the default
    /// `borderFillIDRef=2` (한글 default char background, no visible border).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub char_border_fill_id: Option<u32>,
}

/// Paragraph list semantics with unresolved definition ids.
///
/// Blueprint templates reference numbering/bullet definitions by their
/// declared ids. During registry construction those ids are resolved into the
/// branded shared IR indices stored by [`ParagraphListRef`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum PartialParagraphListRef {
    /// Outline heading semantics.
    Outline {
        /// Zero-based outline level (`0..=9`).
        level: u8,
    },
    /// Numbered list semantics.
    Number {
        /// Declared numbering definition id from the template.
        numbering_id: u32,
        /// Zero-based paragraph list level (`0..=9`).
        level: u8,
    },
    /// Bullet list semantics.
    Bullet {
        /// Declared bullet definition id from the template.
        bullet_id: u32,
        /// Zero-based paragraph list level (`0..=9`).
        level: u8,
    },
    /// Checkable bullet list semantics.
    CheckBullet {
        /// Declared bullet definition id from the template.
        bullet_id: u32,
        /// Zero-based paragraph list level (`0..=9`).
        level: u8,
        /// Whether the checkbox is currently checked.
        checked: bool,
    },
}

impl PartialParagraphListRef {
    fn resolve(
        self,
        style_name: &str,
        numberings: &[NumberingDef],
        bullets: &[BulletDef],
    ) -> BlueprintResult<ParagraphListRef> {
        let level = match self {
            Self::Outline { level }
            | Self::Number { level, .. }
            | Self::Bullet { level, .. }
            | Self::CheckBullet { level, .. } => level,
        };
        if level > ParagraphListRef::MAX_LEVEL {
            return Err(BlueprintError::InvalidListLevel {
                style_name: style_name.to_string(),
                level,
                max: ParagraphListRef::MAX_LEVEL,
            });
        }

        match self {
            Self::Outline { level } => Ok(ParagraphListRef::Outline { level }),
            Self::Number { numbering_id, level } => {
                let numbering_index = numberings
                    .iter()
                    .position(|numbering| numbering.id == numbering_id)
                    .ok_or_else(|| BlueprintError::InvalidListReference {
                        style_name: style_name.to_string(),
                        kind: "numbering".to_string(),
                        id: numbering_id,
                    })?;
                Ok(ParagraphListRef::Number {
                    numbering_id: hwpforge_foundation::NumberingIndex::new(numbering_index),
                    level,
                })
            }
            Self::Bullet { bullet_id, level } => {
                let bullet_index = bullets
                    .iter()
                    .position(|bullet| bullet.id == bullet_id)
                    .ok_or_else(|| BlueprintError::InvalidListReference {
                        style_name: style_name.to_string(),
                        kind: "bullet".to_string(),
                        id: bullet_id,
                    })?;
                let bullet = &bullets[bullet_index];
                if bullet.is_checkable() {
                    return Err(BlueprintError::InvalidPlainBulletDefinition {
                        style_name: style_name.to_string(),
                        bullet_id,
                    });
                }
                Ok(ParagraphListRef::Bullet {
                    bullet_id: hwpforge_foundation::BulletIndex::new(bullet_index),
                    level,
                })
            }
            Self::CheckBullet { bullet_id, level, checked } => {
                let bullet_index = bullets
                    .iter()
                    .position(|bullet| bullet.id == bullet_id)
                    .ok_or_else(|| BlueprintError::InvalidListReference {
                        style_name: style_name.to_string(),
                        kind: "bullet".to_string(),
                        id: bullet_id,
                    })?;
                let bullet = &bullets[bullet_index];
                if !bullet.is_checkable() {
                    return Err(BlueprintError::InvalidCheckableBulletDefinition {
                        style_name: style_name.to_string(),
                        bullet_id,
                    });
                }
                Ok(ParagraphListRef::CheckBullet {
                    bullet_id: hwpforge_foundation::BulletIndex::new(bullet_index),
                    level,
                    checked,
                })
            }
        }
    }
}

impl PartialCharShape {
    /// Merges `other` into `self` (child overrides parent).
    /// Fields in `other` with `Some` value override `self`.
    pub fn merge(&mut self, other: &PartialCharShape) {
        if other.font.is_some() {
            self.font.clone_from(&other.font);
        }
        if other.size.is_some() {
            self.size = other.size;
        }
        if other.bold.is_some() {
            self.bold = other.bold;
        }
        if other.italic.is_some() {
            self.italic = other.italic;
        }
        if other.color.is_some() {
            self.color = other.color;
        }
        if other.underline_type.is_some() {
            self.underline_type = other.underline_type;
        }
        if other.underline_color.is_some() {
            self.underline_color = other.underline_color;
        }
        if other.strikeout_shape.is_some() {
            self.strikeout_shape = other.strikeout_shape;
        }
        if other.strikeout_color.is_some() {
            self.strikeout_color = other.strikeout_color;
        }
        if other.outline.is_some() {
            self.outline = other.outline;
        }
        if other.shadow.is_some() {
            self.shadow = other.shadow;
        }
        if other.emboss.is_some() {
            self.emboss = other.emboss;
        }
        if other.engrave.is_some() {
            self.engrave = other.engrave;
        }
        if other.vertical_position.is_some() {
            self.vertical_position = other.vertical_position;
        }
        if other.shade_color.is_some() {
            self.shade_color = other.shade_color;
        }
        if other.emphasis.is_some() {
            self.emphasis = other.emphasis;
        }
        if other.ratio.is_some() {
            self.ratio = other.ratio;
        }
        if other.spacing.is_some() {
            self.spacing = other.spacing;
        }
        if other.rel_sz.is_some() {
            self.rel_sz = other.rel_sz;
        }
        if other.offset.is_some() {
            self.offset = other.offset;
        }
        if other.use_kerning.is_some() {
            self.use_kerning = other.use_kerning;
        }
        if other.use_font_space.is_some() {
            self.use_font_space = other.use_font_space;
        }
        if other.char_border_fill_id.is_some() {
            self.char_border_fill_id = other.char_border_fill_id;
        }
    }

    /// Attempts to resolve this partial into a fully-specified [`CharShape`].
    ///
    /// Returns an error naming the first missing required field.
    pub fn resolve(&self, style_name: &str) -> BlueprintResult<CharShape> {
        Ok(CharShape {
            font: self.font.clone().ok_or_else(|| BlueprintError::StyleResolution {
                style_name: style_name.to_string(),
                field: "font".to_string(),
            })?,
            size: self.size.ok_or_else(|| BlueprintError::StyleResolution {
                style_name: style_name.to_string(),
                field: "size".to_string(),
            })?,
            bold: self.bold.unwrap_or(false),
            italic: self.italic.unwrap_or(false),
            color: self.color.unwrap_or(Color::BLACK),
            underline_type: self.underline_type.unwrap_or(UnderlineType::None),
            underline_color: self.underline_color,
            strikeout_shape: self.strikeout_shape.unwrap_or(StrikeoutShape::None),
            strikeout_color: self.strikeout_color,
            outline: self.outline.unwrap_or(OutlineType::None),
            shadow: self.shadow.unwrap_or(ShadowType::None),
            emboss: self.emboss.unwrap_or(EmbossType::None),
            engrave: self.engrave.unwrap_or(EngraveType::None),
            vertical_position: self.vertical_position.unwrap_or(VerticalPosition::Normal),
            shade_color: self.shade_color,
            emphasis: self.emphasis.unwrap_or(EmphasisType::None),
            ratio: self.ratio.unwrap_or(100),
            spacing: self.spacing.unwrap_or(0),
            rel_sz: self.rel_sz.unwrap_or(100),
            offset: self.offset.unwrap_or(0),
            use_kerning: self.use_kerning.unwrap_or(false),
            use_font_space: self.use_font_space.unwrap_or(false),
            char_border_fill_id: self.char_border_fill_id,
        })
    }
}

/// Paragraph shape with all optional fields (for YAML parsing and inheritance).
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, JsonSchema)]
pub struct PartialParaShape {
    /// Text alignment.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub alignment: Option<Alignment>,
    /// Line spacing.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub line_spacing: Option<LineSpacing>,
    /// Vertical spacing (before/after paragraph).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub spacing: Option<Spacing>,
    /// Indentation.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub indent: Option<Indent>,

    // Advanced paragraph controls (NEW in Phase 5.3)
    /// Page/column break before paragraph.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub break_type: Option<BreakType>,
    /// Keep paragraph with next (prevent page break between).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub keep_with_next: Option<bool>,
    /// Keep lines together (prevent page break within paragraph).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub keep_lines_together: Option<bool>,
    /// Widow/orphan control (minimum 2 lines).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub widow_orphan: Option<bool>,
    /// Border/fill reference (for paragraph borders and backgrounds).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub border_fill_id: Option<BorderFillIndex>,
    /// Tab definition reference (`0` = default/no explicit custom stops).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tab_def_id: Option<u32>,
    /// Shared paragraph list semantics.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub list: Option<PartialParagraphListRef>,
    /// Heading type for outline/numbering styles.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub heading_type: Option<HeadingType>,
}

impl Spacing {
    /// Merges `other` into `self` (child fields override parent fields).
    pub fn merge(&mut self, other: &Spacing) {
        if other.before.is_some() {
            self.before = other.before;
        }
        if other.after.is_some() {
            self.after = other.after;
        }
    }
}

impl Indent {
    /// Merges `other` into `self` (child fields override parent fields).
    pub fn merge(&mut self, other: &Indent) {
        if other.left.is_some() {
            self.left = other.left;
        }
        if other.right.is_some() {
            self.right = other.right;
        }
        if other.first_line.is_some() {
            self.first_line = other.first_line;
        }
    }
}

impl LineSpacing {
    /// Merges `other` into `self` (child fields override parent fields).
    pub fn merge(&mut self, other: &LineSpacing) {
        if other.spacing_type.is_some() {
            self.spacing_type = other.spacing_type;
        }
        if other.value.is_some() {
            self.value = other.value;
        }
    }
}

impl PartialParaShape {
    /// Merges `other` into `self` (child overrides parent, field-level deep merge).
    ///
    /// Nested structs (line_spacing, spacing, indent) are merged at the field
    /// level, not replaced wholesale. This means a child can override
    /// `spacing.after` while inheriting `spacing.before` from the parent.
    pub fn merge(&mut self, other: &PartialParaShape) {
        if other.alignment.is_some() {
            self.alignment = other.alignment;
        }
        // Deep merge: merge nested struct fields individually
        match (&mut self.line_spacing, &other.line_spacing) {
            (Some(base), Some(child)) => base.merge(child),
            (None, Some(child)) => self.line_spacing = Some(*child),
            _ => {}
        }
        match (&mut self.spacing, &other.spacing) {
            (Some(base), Some(child)) => base.merge(child),
            (None, Some(child)) => self.spacing = Some(*child),
            _ => {}
        }
        match (&mut self.indent, &other.indent) {
            (Some(base), Some(child)) => base.merge(child),
            (None, Some(child)) => self.indent = Some(*child),
            _ => {}
        }
        if other.break_type.is_some() {
            self.break_type = other.break_type;
        }
        if other.keep_with_next.is_some() {
            self.keep_with_next = other.keep_with_next;
        }
        if other.keep_lines_together.is_some() {
            self.keep_lines_together = other.keep_lines_together;
        }
        if other.widow_orphan.is_some() {
            self.widow_orphan = other.widow_orphan;
        }
        if other.border_fill_id.is_some() {
            self.border_fill_id = other.border_fill_id;
        }
        if other.tab_def_id.is_some() {
            self.tab_def_id = other.tab_def_id;
        }
        if other.list.is_some() {
            self.list = other.list;
        }
        if other.heading_type.is_some() {
            self.heading_type = other.heading_type;
        }
    }

    /// Resolves into a fully-specified [`ParaShape`] with defaults.
    pub fn resolve(
        &self,
        style_name: &str,
        numberings: &[NumberingDef],
        bullets: &[BulletDef],
    ) -> BlueprintResult<ParaShape> {
        Ok(ParaShape {
            alignment: self.alignment.unwrap_or(Alignment::Left),
            line_spacing_type: self
                .line_spacing
                .and_then(|ls| ls.spacing_type)
                .unwrap_or(LineSpacingType::Percentage),
            line_spacing_value: self.line_spacing.and_then(|ls| ls.value).unwrap_or(160.0),
            space_before: self.spacing.and_then(|s| s.before).unwrap_or(HwpUnit::ZERO),
            space_after: self.spacing.and_then(|s| s.after).unwrap_or(HwpUnit::ZERO),
            indent_left: self.indent.and_then(|i| i.left).unwrap_or(HwpUnit::ZERO),
            indent_right: self.indent.and_then(|i| i.right).unwrap_or(HwpUnit::ZERO),
            indent_first_line: self.indent.and_then(|i| i.first_line).unwrap_or(HwpUnit::ZERO),
            break_type: self.break_type.unwrap_or(BreakType::None),
            keep_with_next: self.keep_with_next.unwrap_or(false),
            keep_lines_together: self.keep_lines_together.unwrap_or(false),
            widow_orphan: self.widow_orphan.unwrap_or(true), // Enabled by default in HWPX
            border_fill_id: self.border_fill_id,
            tab_def_id: self.tab_def_id.unwrap_or(0),
            list: self.resolve_list(style_name, numberings, bullets)?,
        })
    }

    fn resolve_list(
        &self,
        style_name: &str,
        numberings: &[NumberingDef],
        bullets: &[BulletDef],
    ) -> BlueprintResult<Option<ParagraphListRef>> {
        if let Some(list) = self.list {
            if matches!(
                self.heading_type,
                Some(HeadingType::Outline | HeadingType::Number | HeadingType::Bullet)
            ) {
                return Err(BlueprintError::ConflictingListSpecification {
                    style_name: style_name.to_string(),
                });
            }
            return list.resolve(style_name, numberings, bullets).map(Some);
        }

        match self.heading_type.unwrap_or(HeadingType::None) {
            HeadingType::None => Ok(None),
            HeadingType::Outline => Ok(Some(ParagraphListRef::Outline { level: 0 })),
            heading_type => Err(BlueprintError::UnsupportedLegacyHeadingType {
                style_name: style_name.to_string(),
                heading_type,
            }),
        }
    }
}

/// A composite style entry (char + para shape) with optional fields for YAML.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, JsonSchema)]
pub struct PartialStyle {
    /// Character formatting.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub char_shape: Option<PartialCharShape>,
    /// Paragraph formatting.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub para_shape: Option<PartialParaShape>,
}

impl PartialStyle {
    /// Merges `other` into `self`.
    pub fn merge(&mut self, other: &PartialStyle) {
        match (&mut self.char_shape, &other.char_shape) {
            (Some(base), Some(child)) => base.merge(child),
            (None, Some(child)) => self.char_shape = Some(child.clone()),
            _ => {}
        }
        match (&mut self.para_shape, &other.para_shape) {
            (Some(base), Some(child)) => base.merge(child),
            (None, Some(child)) => self.para_shape = Some(child.clone()),
            _ => {}
        }
    }
}

// ---------------------------------------------------------------------------
// Resolved (full) types
// ---------------------------------------------------------------------------

/// A fully-resolved character shape (all fields present).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct CharShape {
    /// Font name.
    pub font: String,
    /// Font size.
    #[serde(serialize_with = "ser_dim", deserialize_with = "de_dim")]
    pub size: HwpUnit,
    /// Bold.
    pub bold: bool,
    /// Italic.
    pub italic: bool,
    /// Text color.
    #[serde(serialize_with = "ser_color", deserialize_with = "de_color")]
    pub color: Color,
    /// Underline type.
    pub underline_type: UnderlineType,
    /// Underline color (None = inherit text color).
    #[serde(
        default,
        serialize_with = "ser_color_opt",
        deserialize_with = "de_color_opt",
        skip_serializing_if = "Option::is_none"
    )]
    pub underline_color: Option<Color>,
    /// Strikeout line shape.
    pub strikeout_shape: StrikeoutShape,
    /// Strikeout color (None = inherit text color).
    #[serde(
        default,
        serialize_with = "ser_color_opt",
        deserialize_with = "de_color_opt",
        skip_serializing_if = "Option::is_none"
    )]
    pub strikeout_color: Option<Color>,
    /// Text outline.
    pub outline: OutlineType,
    /// Drop shadow.
    pub shadow: ShadowType,
    /// Emboss effect.
    pub emboss: EmbossType,
    /// Engrave effect.
    pub engrave: EngraveType,
    /// Vertical position (replaces superscript/subscript bools).
    pub vertical_position: VerticalPosition,
    /// Background shade color (None = transparent).
    #[serde(
        default,
        serialize_with = "ser_color_opt",
        deserialize_with = "de_color_opt",
        skip_serializing_if = "Option::is_none"
    )]
    pub shade_color: Option<Color>,
    /// Emphasis mark type (symMark). Default: None.
    pub emphasis: EmphasisType,
    /// Character width ratio (percent, uniform). Default: 100.
    pub ratio: i32,
    /// Inter-character spacing (percent, uniform). Default: 0.
    pub spacing: i32,
    /// Relative font size (percent, uniform). Default: 100.
    pub rel_sz: i32,
    /// Vertical position offset (percent, uniform). Default: 0.
    pub offset: i32,
    /// Enable kerning. Default: false.
    pub use_kerning: bool,
    /// Use font-defined inter-character spacing. Default: false.
    pub use_font_space: bool,
    /// Border/fill reference for character-level border (None = default).
    ///
    /// When `None`, the HWPX encoder uses `borderFillIDRef=2` (the 한글 default
    /// char background, which has no visible border). Set to `Some(id)` to
    /// reference a custom borderFill entry for character-level borders.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub char_border_fill_id: Option<u32>,
}

/// A fully-resolved paragraph shape (all fields present).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct ParaShape {
    /// Text alignment.
    pub alignment: Alignment,
    /// Line spacing type.
    pub line_spacing_type: LineSpacingType,
    /// Line spacing value (percentage or fixed).
    pub line_spacing_value: f64,
    /// Space before paragraph.
    #[serde(serialize_with = "ser_dim", deserialize_with = "de_dim")]
    pub space_before: HwpUnit,
    /// Space after paragraph.
    #[serde(serialize_with = "ser_dim", deserialize_with = "de_dim")]
    pub space_after: HwpUnit,
    /// Left indentation.
    #[serde(serialize_with = "ser_dim", deserialize_with = "de_dim")]
    pub indent_left: HwpUnit,
    /// Right indentation.
    #[serde(serialize_with = "ser_dim", deserialize_with = "de_dim")]
    pub indent_right: HwpUnit,
    /// First-line indentation.
    #[serde(serialize_with = "ser_dim", deserialize_with = "de_dim")]
    pub indent_first_line: HwpUnit,

    // Advanced paragraph controls (NEW in Phase 5.3)
    /// Page/column break type.
    pub break_type: BreakType,
    /// Keep paragraph with next.
    pub keep_with_next: bool,
    /// Keep lines together.
    pub keep_lines_together: bool,
    /// Widow/orphan control (default: true).
    pub widow_orphan: bool,
    /// Border/fill reference (None = no border/fill).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub border_fill_id: Option<BorderFillIndex>,
    /// Tab definition reference (`0` = default/no explicit custom stops).
    #[serde(default)]
    pub tab_def_id: u32,
    /// Shared paragraph list semantics.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub list: Option<ParagraphListRef>,
}

#[cfg(test)]
mod tests {
    use super::*;
    use hwpforge_core::ParaHead;
    use hwpforge_foundation::{BulletIndex, NumberFormatType, NumberingIndex};
    use pretty_assertions::assert_eq;

    fn test_numbering_def(id: u32) -> NumberingDef {
        NumberingDef {
            id,
            start: 1,
            levels: vec![ParaHead {
                start: 1,
                level: 1,
                num_format: NumberFormatType::Digit,
                text: "^1.".into(),
                checkable: false,
            }],
        }
    }

    fn test_bullet_def(id: u32) -> BulletDef {
        BulletDef {
            id,
            bullet_char: "".into(),
            checked_char: None,
            use_image: false,
            para_head: ParaHead {
                start: 0,
                level: 1,
                num_format: NumberFormatType::Digit,
                text: String::new(),
                checkable: false,
            },
        }
    }

    #[test]
    fn partial_char_shape_default_is_all_none() {
        let p = PartialCharShape::default();
        assert!(p.font.is_none());
        assert!(p.size.is_none());
        assert!(p.bold.is_none());
        assert!(p.italic.is_none());
        assert!(p.color.is_none());
        assert!(p.underline_type.is_none());
        assert!(p.strikeout_shape.is_none());
        assert!(p.vertical_position.is_none());
    }

    #[test]
    fn partial_char_shape_merge_overrides() {
        let mut base = PartialCharShape {
            font: Some("Arial".into()),
            size: Some(HwpUnit::from_pt(10.0).unwrap()),
            bold: Some(false),
            ..Default::default()
        };
        let child = PartialCharShape {
            size: Some(HwpUnit::from_pt(16.0).unwrap()),
            bold: Some(true),
            ..Default::default()
        };
        base.merge(&child);
        assert_eq!(base.font, Some("Arial".into()));
        assert_eq!(base.size, Some(HwpUnit::from_pt(16.0).unwrap()));
        assert_eq!(base.bold, Some(true));
    }

    #[test]
    fn partial_char_shape_merge_none_does_not_override() {
        let mut base = PartialCharShape { font: Some("Batang".into()), ..Default::default() };
        let child = PartialCharShape::default();
        base.merge(&child);
        assert_eq!(base.font, Some("Batang".into()));
    }

    #[test]
    fn partial_char_shape_resolve_success() {
        let partial = PartialCharShape {
            font: Some("한컴바탕".into()),
            size: Some(HwpUnit::from_pt(10.0).unwrap()),
            ..Default::default()
        };
        let resolved = partial.resolve("body").unwrap();
        assert_eq!(resolved.font, "한컴바탕");
        assert_eq!(resolved.size, HwpUnit::from_pt(10.0).unwrap());
        assert!(!resolved.bold);
        assert_eq!(resolved.color, Color::BLACK);
    }

    #[test]
    fn partial_char_shape_resolve_missing_font() {
        let partial =
            PartialCharShape { size: Some(HwpUnit::from_pt(10.0).unwrap()), ..Default::default() };
        let err = partial.resolve("heading1").unwrap_err();
        assert!(err.to_string().contains("font"));
        assert!(err.to_string().contains("heading1"));
    }

    #[test]
    fn partial_char_shape_resolve_missing_size() {
        let partial = PartialCharShape { font: Some("Arial".into()), ..Default::default() };
        let err = partial.resolve("body").unwrap_err();
        assert!(err.to_string().contains("size"));
    }

    #[test]
    fn partial_para_shape_default_is_all_none() {
        let p = PartialParaShape::default();
        assert!(p.alignment.is_none());
        assert!(p.line_spacing.is_none());
        assert!(p.spacing.is_none());
        assert!(p.indent.is_none());
    }

    #[test]
    fn partial_para_shape_merge_overrides() {
        let mut base = PartialParaShape {
            alignment: Some(Alignment::Left),
            line_spacing: Some(LineSpacing {
                spacing_type: Some(LineSpacingType::Percentage),
                value: Some(160.0),
            }),
            ..Default::default()
        };
        let child = PartialParaShape {
            line_spacing: Some(LineSpacing { spacing_type: None, value: Some(170.0) }),
            ..Default::default()
        };
        base.merge(&child);
        assert_eq!(base.alignment, Some(Alignment::Left));
        let ls = base.line_spacing.unwrap();
        assert_eq!(ls.value, Some(170.0)); // Overridden by child
        assert_eq!(ls.spacing_type, Some(LineSpacingType::Percentage)); // Preserved from base (deep merge)
    }

    #[test]
    fn partial_para_shape_deep_merge_spacing() {
        let mut base = PartialParaShape {
            spacing: Some(Spacing { before: Some(HwpUnit::from_pt(6.0).unwrap()), after: None }),
            ..Default::default()
        };
        let child = PartialParaShape {
            spacing: Some(Spacing { before: None, after: Some(HwpUnit::from_pt(12.0).unwrap()) }),
            ..Default::default()
        };
        base.merge(&child);
        let sp = base.spacing.unwrap();
        assert_eq!(sp.before, Some(HwpUnit::from_pt(6.0).unwrap())); // Preserved from base
        assert_eq!(sp.after, Some(HwpUnit::from_pt(12.0).unwrap())); // Added by child
    }

    #[test]
    fn partial_para_shape_deep_merge_indent() {
        let mut base = PartialParaShape {
            indent: Some(Indent {
                left: Some(HwpUnit::from_pt(10.0).unwrap()),
                right: None,
                first_line: Some(HwpUnit::from_pt(5.0).unwrap()),
            }),
            ..Default::default()
        };
        let child = PartialParaShape {
            indent: Some(Indent {
                left: None,
                right: Some(HwpUnit::from_pt(8.0).unwrap()),
                first_line: None,
            }),
            ..Default::default()
        };
        base.merge(&child);
        let indent = base.indent.unwrap();
        assert_eq!(indent.left, Some(HwpUnit::from_pt(10.0).unwrap())); // Preserved
        assert_eq!(indent.right, Some(HwpUnit::from_pt(8.0).unwrap())); // Added
        assert_eq!(indent.first_line, Some(HwpUnit::from_pt(5.0).unwrap())); // Preserved
    }

    #[test]
    fn partial_para_shape_resolve_defaults() {
        let partial = PartialParaShape::default();
        let resolved = partial.resolve("body", &[], &[]).unwrap();
        assert_eq!(resolved.alignment, Alignment::Left);
        assert_eq!(resolved.line_spacing_type, LineSpacingType::Percentage);
        assert_eq!(resolved.line_spacing_value, 160.0);
        assert_eq!(resolved.space_before, HwpUnit::ZERO);
        assert_eq!(resolved.indent_left, HwpUnit::ZERO);
    }

    #[test]
    fn partial_para_shape_resolve_list_number_reference() {
        let partial = PartialParaShape {
            list: Some(PartialParagraphListRef::Number { numbering_id: 42, level: 2 }),
            ..Default::default()
        };

        let resolved = partial.resolve("body", &[test_numbering_def(42)], &[]).unwrap();
        assert_eq!(
            resolved.list,
            Some(ParagraphListRef::Number { numbering_id: NumberingIndex::new(0), level: 2 })
        );
    }

    #[test]
    fn partial_para_shape_resolve_list_bullet_reference() {
        let partial = PartialParaShape {
            list: Some(PartialParagraphListRef::Bullet { bullet_id: 7, level: 0 }),
            ..Default::default()
        };

        let resolved = partial.resolve("body", &[], &[test_bullet_def(7)]).unwrap();
        assert_eq!(
            resolved.list,
            Some(ParagraphListRef::Bullet { bullet_id: BulletIndex::new(0), level: 0 })
        );
    }

    #[test]
    fn partial_para_shape_resolve_rejects_checkable_bullet_as_plain_bullet_reference() {
        let partial = PartialParaShape {
            list: Some(PartialParagraphListRef::Bullet { bullet_id: 7, level: 0 }),
            ..Default::default()
        };
        let mut bullet = test_bullet_def(7);
        bullet.checked_char = Some("".into());
        bullet.para_head.checkable = true;

        let err = partial.resolve("body", &[], &[bullet]).unwrap_err();
        assert!(matches!(err, BlueprintError::InvalidPlainBulletDefinition { bullet_id: 7, .. }));
    }

    #[test]
    fn partial_para_shape_resolve_list_check_bullet_reference() {
        let partial = PartialParaShape {
            list: Some(PartialParagraphListRef::CheckBullet {
                bullet_id: 7,
                level: 1,
                checked: true,
            }),
            ..Default::default()
        };
        let mut bullet = test_bullet_def(7);
        bullet.checked_char = Some("".into());
        bullet.para_head.checkable = true;

        let resolved = partial.resolve("body", &[], &[bullet]).unwrap();
        assert_eq!(
            resolved.list,
            Some(ParagraphListRef::CheckBullet {
                bullet_id: BulletIndex::new(0),
                level: 1,
                checked: true,
            })
        );
    }

    #[test]
    fn partial_para_shape_resolve_rejects_non_checkable_check_bullet_reference() {
        let partial = PartialParaShape {
            list: Some(PartialParagraphListRef::CheckBullet {
                bullet_id: 7,
                level: 0,
                checked: false,
            }),
            ..Default::default()
        };

        let err = partial.resolve("body", &[], &[test_bullet_def(7)]).unwrap_err();
        assert!(matches!(
            err,
            BlueprintError::InvalidCheckableBulletDefinition { bullet_id: 7, .. }
        ));
    }

    #[test]
    fn partial_para_shape_resolve_legacy_outline_heading_type_migrates_to_list() {
        let partial =
            PartialParaShape { heading_type: Some(HeadingType::Outline), ..Default::default() };

        let resolved = partial.resolve("body", &[], &[]).unwrap();
        assert_eq!(resolved.list, Some(ParagraphListRef::Outline { level: 0 }));
    }

    #[test]
    fn partial_para_shape_resolve_rejects_conflicting_legacy_heading_and_list() {
        let partial = PartialParaShape {
            list: Some(PartialParagraphListRef::Outline { level: 1 }),
            heading_type: Some(HeadingType::Outline),
            ..Default::default()
        };

        let err = partial.resolve("body", &[], &[]).unwrap_err();
        assert!(matches!(err, BlueprintError::ConflictingListSpecification { .. }));
    }

    #[test]
    fn partial_para_shape_resolve_rejects_unsupported_legacy_number_heading_type() {
        let partial =
            PartialParaShape { heading_type: Some(HeadingType::Number), ..Default::default() };

        let err = partial.resolve("body", &[], &[]).unwrap_err();
        assert!(matches!(err, BlueprintError::UnsupportedLegacyHeadingType { .. }));
    }

    #[test]
    fn partial_para_shape_resolve_rejects_invalid_list_reference() {
        let partial = PartialParaShape {
            list: Some(PartialParagraphListRef::Number { numbering_id: 999, level: 0 }),
            ..Default::default()
        };

        let err = partial.resolve("body", &[test_numbering_def(42)], &[]).unwrap_err();
        assert!(matches!(err, BlueprintError::InvalidListReference { .. }));
    }

    #[test]
    fn partial_para_shape_resolve_rejects_invalid_list_level() {
        let partial = PartialParaShape {
            list: Some(PartialParagraphListRef::Outline { level: ParagraphListRef::MAX_LEVEL + 1 }),
            ..Default::default()
        };

        let err = partial.resolve("body", &[], &[]).unwrap_err();
        assert!(matches!(err, BlueprintError::InvalidListLevel { .. }));
    }

    #[test]
    fn partial_style_merge_both_present() {
        let mut base = PartialStyle {
            char_shape: Some(PartialCharShape {
                font: Some("Arial".into()),
                size: Some(HwpUnit::from_pt(10.0).unwrap()),
                ..Default::default()
            }),
            para_shape: Some(PartialParaShape {
                alignment: Some(Alignment::Left),
                ..Default::default()
            }),
        };
        let child = PartialStyle {
            char_shape: Some(PartialCharShape {
                size: Some(HwpUnit::from_pt(16.0).unwrap()),
                bold: Some(true),
                ..Default::default()
            }),
            para_shape: None,
        };
        base.merge(&child);
        let cs = base.char_shape.unwrap();
        assert_eq!(cs.font, Some("Arial".into()));
        assert_eq!(cs.size, Some(HwpUnit::from_pt(16.0).unwrap()));
        assert_eq!(cs.bold, Some(true));
    }

    #[test]
    fn partial_style_merge_none_base() {
        let mut base = PartialStyle::default();
        let child = PartialStyle {
            char_shape: Some(PartialCharShape { font: Some("Dotum".into()), ..Default::default() }),
            para_shape: None,
        };
        base.merge(&child);
        assert_eq!(base.char_shape.unwrap().font, Some("Dotum".into()));
    }

    #[test]
    fn char_shape_serde_roundtrip() {
        let original = CharShape {
            font: "한컴바탕".into(),
            size: HwpUnit::from_pt(16.0).unwrap(),
            bold: true,
            italic: false,
            color: Color::from_rgb(0x00, 0x33, 0x66),
            underline_type: UnderlineType::None,
            underline_color: None,
            strikeout_shape: StrikeoutShape::None,
            strikeout_color: None,
            outline: OutlineType::None,
            shadow: ShadowType::None,
            emboss: EmbossType::None,
            engrave: EngraveType::None,
            vertical_position: VerticalPosition::Normal,
            shade_color: None,
            emphasis: EmphasisType::None,
            ratio: 100,
            spacing: 0,
            rel_sz: 100,
            offset: 0,
            use_kerning: false,
            use_font_space: false,
            char_border_fill_id: None,
        };
        let yaml = serde_yaml::to_string(&original).unwrap();
        let back: CharShape = serde_yaml::from_str(&yaml).unwrap();
        assert_eq!(original, back);
    }

    #[test]
    fn char_shape_yaml_contains_human_readable() {
        let cs = CharShape {
            font: "Arial".into(),
            size: HwpUnit::from_pt(12.0).unwrap(),
            bold: false,
            italic: true,
            color: Color::RED,
            underline_type: UnderlineType::None,
            underline_color: None,
            strikeout_shape: StrikeoutShape::None,
            strikeout_color: None,
            outline: OutlineType::None,
            shadow: ShadowType::None,
            emboss: EmbossType::None,
            engrave: EngraveType::None,
            vertical_position: VerticalPosition::Normal,
            shade_color: None,
            emphasis: EmphasisType::None,
            ratio: 100,
            spacing: 0,
            rel_sz: 100,
            offset: 0,
            use_kerning: false,
            use_font_space: false,
            char_border_fill_id: None,
        };
        let yaml = serde_yaml::to_string(&cs).unwrap();
        assert!(yaml.contains("12pt"), "Expected '12pt' in: {yaml}");
        assert!(yaml.contains("#FF0000"), "Expected '#FF0000' in: {yaml}");
    }

    #[test]
    fn para_shape_serde_roundtrip() {
        let original = ParaShape {
            alignment: Alignment::Justify,
            line_spacing_type: LineSpacingType::Percentage,
            line_spacing_value: 170.0,
            space_before: HwpUnit::from_pt(6.0).unwrap(),
            space_after: HwpUnit::from_pt(6.0).unwrap(),
            indent_left: HwpUnit::ZERO,
            indent_right: HwpUnit::ZERO,
            indent_first_line: HwpUnit::ZERO,
            break_type: BreakType::None,
            keep_with_next: false,
            keep_lines_together: false,
            widow_orphan: true,
            border_fill_id: None,
            tab_def_id: 0,
            list: None,
        };
        let yaml = serde_yaml::to_string(&original).unwrap();
        let back: ParaShape = serde_yaml::from_str(&yaml).unwrap();
        assert_eq!(original, back);
    }

    #[test]
    fn para_shape_yaml_defaults_missing_tab_def_id_to_zero() {
        let yaml = r#"
alignment: Justify
line_spacing_type: Percentage
line_spacing_value: 160.0
space_before: 0pt
space_after: 0pt
indent_left: 0pt
indent_right: 0pt
indent_first_line: 0pt
break_type: None
keep_with_next: false
keep_lines_together: false
widow_orphan: true
"#;
        let parsed: ParaShape = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(parsed.tab_def_id, 0);
        assert_eq!(parsed.list, None);
    }

    #[test]
    fn partial_char_shape_from_yaml() {
        let yaml = "font: 한컴바탕\nsize: 16pt\nbold: true\ncolor: '#003366'\n";
        let partial: PartialCharShape = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(partial.font, Some("한컴바탕".into()));
        assert_eq!(partial.size, Some(HwpUnit::from_pt(16.0).unwrap()));
        assert_eq!(partial.bold, Some(true));
        assert_eq!(partial.color, Some(Color::from_rgb(0x00, 0x33, 0x66)));
        assert!(partial.italic.is_none());
    }

    #[test]
    fn partial_para_shape_from_yaml() {
        let yaml = "alignment: Justify\nline_spacing:\n  value: '170%'\nspacing:\n  before: '6pt'\n  after: '6pt'\n";
        let partial: PartialParaShape = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(partial.alignment, Some(Alignment::Justify));
        assert_eq!(partial.line_spacing.unwrap().value, Some(170.0));
        assert_eq!(partial.spacing.unwrap().before, Some(HwpUnit::from_pt(6.0).unwrap()));
    }

    #[test]
    fn partial_style_from_yaml() {
        let yaml = "char_shape:\n  font: Arial\n  size: '10pt'\npara_shape:\n  alignment: Left\n";
        let style: PartialStyle = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(style.char_shape.as_ref().unwrap().font, Some("Arial".into()));
        assert_eq!(style.para_shape.as_ref().unwrap().alignment, Some(Alignment::Left));
    }

    #[test]
    fn spacing_from_yaml() {
        let yaml = "before: '6pt'\nafter: '12pt'\n";
        let spacing: Spacing = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(spacing.before, Some(HwpUnit::from_pt(6.0).unwrap()));
        assert_eq!(spacing.after, Some(HwpUnit::from_pt(12.0).unwrap()));
    }

    #[test]
    fn indent_from_yaml() {
        let yaml = "left: '20mm'\nfirst_line: '10pt'\n";
        let indent: Indent = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(indent.left, Some(HwpUnit::from_mm(20.0).unwrap()));
        assert_eq!(indent.first_line, Some(HwpUnit::from_pt(10.0).unwrap()));
        assert!(indent.right.is_none());
    }

    #[test]
    fn line_spacing_from_yaml() {
        let yaml = "spacing_type: Percentage\nvalue: '160%'\n";
        let ls: LineSpacing = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(ls.spacing_type, Some(LineSpacingType::Percentage));
        assert_eq!(ls.value, Some(160.0));
    }
}