kreuzberg 4.9.7

High-performance document intelligence library for Rust. Extract text, metadata, and structured data from PDFs, Office documents, images, and 91+ formats and 248 programming languages via tree-sitter code intelligence with async/sync APIs.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
//! DOCX style resolution from `word/styles.xml`.
//!
//! Parses the styles XML and resolves style inheritance chains to produce
//! fully-flattened run and paragraph properties for any given style ID.

use ahash::AHashMap;

use crate::error::{KreuzbergError, Result};
use crate::extraction::ooxml_constants::WORDPROCESSINGML_NAMESPACE;

// --- Types ---

/// The type of a style definition in DOCX.
#[derive(Debug, Clone, PartialEq)]
pub enum StyleType {
    Paragraph,
    Character,
    Table,
    Numbering,
}

/// Run-level formatting properties (bold, italic, font, size, color, etc.).
///
/// All fields are `Option` so that inheritance resolution can distinguish
/// "not set" (`None`) from "explicitly set" (`Some`).
#[derive(Debug, Clone, Default, PartialEq)]
pub struct RunProperties {
    pub bold: Option<bool>,
    pub italic: Option<bool>,
    pub underline: Option<bool>,
    pub strikethrough: Option<bool>,
    /// Hex RGB color, e.g. `"2F5496"`.
    pub color: Option<String>,
    /// Font size in half-points (`w:sz` val). Divide by 2 to get points.
    pub font_size_half_points: Option<i32>,
    /// ASCII font family (`w:rFonts w:ascii`).
    pub font_ascii: Option<String>,
    /// ASCII theme font (`w:rFonts w:asciiTheme`).
    pub font_ascii_theme: Option<String>,
    /// Vertical alignment: "superscript", "subscript", or "baseline".
    pub vert_align: Option<String>,
    /// High ANSI font family (w:rFonts w:hAnsi).
    pub font_h_ansi: Option<String>,
    /// Complex script font family (w:rFonts w:cs).
    pub font_cs: Option<String>,
    /// East Asian font family (w:rFonts w:eastAsia).
    pub font_east_asia: Option<String>,
    /// Highlight color name (e.g., "yellow", "green", "cyan").
    pub highlight: Option<String>,
    /// All caps text transformation.
    pub caps: Option<bool>,
    /// Small caps text transformation.
    pub small_caps: Option<bool>,
    /// Text shadow effect.
    pub shadow: Option<bool>,
    /// Text outline effect.
    pub outline: Option<bool>,
    /// Text emboss effect.
    pub emboss: Option<bool>,
    /// Text imprint (engrave) effect.
    pub imprint: Option<bool>,
    /// Character spacing in twips (from w:spacing w:val).
    pub char_spacing: Option<i32>,
    /// Vertical position offset in half-points (from w:position w:val).
    pub position: Option<i32>,
    /// Kerning threshold in half-points (from w:kern w:val).
    pub kern: Option<i32>,
    /// Theme color reference (e.g., "accent1", "dk1").
    pub theme_color: Option<String>,
    /// Theme color tint modification (hex value).
    pub theme_tint: Option<String>,
    /// Theme color shade modification (hex value).
    pub theme_shade: Option<String>,
}

/// Paragraph-level formatting properties (alignment, spacing, indentation, etc.).
#[derive(Debug, Clone, Default, PartialEq)]
pub struct ParagraphProperties {
    /// `"left"`, `"center"`, `"right"`, `"both"` (justified).
    pub alignment: Option<String>,
    /// Spacing before paragraph in twips.
    pub spacing_before: Option<i32>,
    /// Spacing after paragraph in twips.
    pub spacing_after: Option<i32>,
    /// Line spacing in twips or 240ths of a line.
    pub spacing_line: Option<i32>,
    /// Line spacing rule: "auto", "exact", or "atLeast".
    pub spacing_line_rule: Option<String>,
    /// Left indentation in twips.
    pub indent_left: Option<i32>,
    /// Right indentation in twips.
    pub indent_right: Option<i32>,
    /// First-line indentation in twips.
    pub indent_first_line: Option<i32>,
    /// Hanging indentation in twips.
    pub indent_hanging: Option<i32>,
    /// Outline level 0-8 for heading levels.
    pub outline_level: Option<u8>,
    /// Keep with next paragraph on same page.
    pub keep_next: Option<bool>,
    /// Keep all lines of paragraph on same page.
    pub keep_lines: Option<bool>,
    /// Force page break before paragraph.
    pub page_break_before: Option<bool>,
    /// Prevent widow/orphan lines.
    pub widow_control: Option<bool>,
    /// Suppress automatic hyphenation.
    pub suppress_auto_hyphens: Option<bool>,
    /// Right-to-left paragraph direction.
    pub bidi: Option<bool>,
    /// Background color hex value (from w:shd w:fill).
    pub shading_fill: Option<String>,
    /// Shading pattern value (from w:shd w:val).
    pub shading_val: Option<String>,
    /// Top border style (from w:pBdr/w:top w:val).
    pub border_top: Option<String>,
    /// Bottom border style (from w:pBdr/w:bottom w:val).
    pub border_bottom: Option<String>,
    /// Left border style (from w:pBdr/w:left w:val).
    pub border_left: Option<String>,
    /// Right border style (from w:pBdr/w:right w:val).
    pub border_right: Option<String>,
}

/// A single style definition parsed from `<w:style>` in `word/styles.xml`.
#[derive(Debug, Clone)]
pub struct StyleDefinition {
    /// The style ID (`w:styleId` attribute).
    pub id: String,
    /// Human-readable name (`<w:name w:val="..."/>`).
    pub name: Option<String>,
    /// Style type: paragraph, character, table, or numbering.
    pub style_type: StyleType,
    /// ID of the parent style (`<w:basedOn w:val="..."/>`).
    pub based_on: Option<String>,
    /// ID of the style to apply to the next paragraph (`<w:next w:val="..."/>`).
    pub next_style: Option<String>,
    /// Whether this is the default style for its type.
    pub is_default: bool,
    /// Paragraph properties defined directly on this style.
    pub paragraph_properties: ParagraphProperties,
    /// Run properties defined directly on this style.
    pub run_properties: RunProperties,
}

/// Fully resolved (flattened) style after walking the inheritance chain.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct ResolvedStyle {
    pub paragraph_properties: ParagraphProperties,
    pub run_properties: RunProperties,
}

/// Catalog of all styles parsed from `word/styles.xml`, plus document defaults.
#[derive(Debug, Clone, Default)]
pub struct StyleCatalog {
    pub styles: AHashMap<String, StyleDefinition>,
    pub default_paragraph_properties: ParagraphProperties,
    pub default_run_properties: RunProperties,
}

// --- Parsing ---

/// Parse `word/styles.xml` content into a `StyleCatalog`.
///
/// Uses `roxmltree` for tree-based XML parsing, consistent with the
/// office metadata parsing approach used elsewhere in the codebase.
pub fn parse_styles_xml(xml: &str) -> Result<StyleCatalog> {
    let doc = roxmltree::Document::parse(xml)
        .map_err(|e| KreuzbergError::parsing(format!("Failed to parse styles.xml: {}", e)))?;

    let root = doc.root_element();

    let mut catalog = StyleCatalog::default();

    for child in root.children() {
        if !child.is_element() {
            continue;
        }

        match child.tag_name().name() {
            "docDefaults" => parse_doc_defaults(&child, &mut catalog),
            "style" => {
                if let Some(style_def) = parse_style_element(&child) {
                    catalog.styles.insert(style_def.id.clone(), style_def);
                }
            }
            // Skip latentStyles and anything else
            _ => {}
        }
    }

    Ok(catalog)
}

/// Parse `<w:docDefaults>` to extract default run and paragraph properties.
fn parse_doc_defaults(node: &roxmltree::Node, catalog: &mut StyleCatalog) {
    for child in node.children() {
        if !child.is_element() {
            continue;
        }

        match child.tag_name().name() {
            "rPrDefault" => {
                // Look for <w:rPr> inside <w:rPrDefault>
                if let Some(rpr) = find_child_element(&child, "rPr") {
                    catalog.default_run_properties = parse_run_properties(&rpr);
                }
            }
            "pPrDefault" => {
                // Look for <w:pPr> inside <w:pPrDefault>
                if let Some(ppr) = find_child_element(&child, "pPr") {
                    catalog.default_paragraph_properties = parse_paragraph_properties(&ppr);
                }
            }
            _ => {}
        }
    }
}

/// Parse a single `<w:style>` element into a `StyleDefinition`.
///
/// Returns `None` if the element lacks a `w:styleId` or `w:type` attribute.
fn parse_style_element(node: &roxmltree::Node) -> Option<StyleDefinition> {
    let style_id = node.attribute((WORDPROCESSINGML_NAMESPACE, "styleId"))?;

    let type_str = node.attribute((WORDPROCESSINGML_NAMESPACE, "type"))?;
    let style_type = match type_str {
        "paragraph" => StyleType::Paragraph,
        "character" => StyleType::Character,
        "table" => StyleType::Table,
        "numbering" => StyleType::Numbering,
        _ => return None,
    };

    let is_default = node
        .attribute((WORDPROCESSINGML_NAMESPACE, "default"))
        .is_some_and(|v| v == "1" || v == "true");

    let mut name = None;
    let mut based_on = None;
    let mut next_style = None;
    let mut paragraph_properties = ParagraphProperties::default();
    let mut run_properties = RunProperties::default();

    for child in node.children() {
        if !child.is_element() {
            continue;
        }

        match child.tag_name().name() {
            "name" => {
                name = get_w_val(&child).map(String::from);
            }
            "basedOn" => {
                based_on = get_w_val(&child).map(String::from);
            }
            "next" => {
                next_style = get_w_val(&child).map(String::from);
            }
            "pPr" => {
                paragraph_properties = parse_paragraph_properties(&child);
            }
            "rPr" => {
                run_properties = parse_run_properties(&child);
            }
            _ => {}
        }
    }

    Some(StyleDefinition {
        id: style_id.to_string(),
        name,
        style_type,
        based_on,
        next_style,
        is_default,
        paragraph_properties,
        run_properties,
    })
}

/// Parse `<w:rPr>` run properties from a node's children.
fn parse_run_properties(node: &roxmltree::Node) -> RunProperties {
    let mut props = RunProperties::default();

    for child in node.children() {
        if !child.is_element() {
            continue;
        }

        match child.tag_name().name() {
            "b" => props.bold = Some(parse_toggle_property(&child)),
            "i" => props.italic = Some(parse_toggle_property(&child)),
            "u" => {
                // <w:u/> or <w:u w:val="single"/> means underlined;
                // <w:u w:val="none"/> means not underlined.
                let val = get_w_val(&child);
                props.underline = Some(!matches!(val, Some("none")));
            }
            "strike" | "dstrike" => props.strikethrough = Some(parse_toggle_property(&child)),
            "color" => {
                props.color = get_w_val(&child).map(String::from);
                props.theme_color = get_w_attr_string(&child, "themeColor");
                props.theme_tint = get_w_attr_string(&child, "themeTint");
                props.theme_shade = get_w_attr_string(&child, "themeShade");
            }
            "sz" => {
                props.font_size_half_points = get_w_val(&child).and_then(|v| v.parse::<i32>().ok());
            }
            "rFonts" => {
                props.font_ascii = child.attribute((WORDPROCESSINGML_NAMESPACE, "ascii")).map(String::from);
                props.font_ascii_theme = child
                    .attribute((WORDPROCESSINGML_NAMESPACE, "asciiTheme"))
                    .map(String::from);
                props.font_h_ansi = child.attribute((WORDPROCESSINGML_NAMESPACE, "hAnsi")).map(String::from);
                props.font_cs = child.attribute((WORDPROCESSINGML_NAMESPACE, "cs")).map(String::from);
                props.font_east_asia = child
                    .attribute((WORDPROCESSINGML_NAMESPACE, "eastAsia"))
                    .map(String::from);
            }
            "vertAlign" => {
                props.vert_align = get_w_val(&child).map(String::from);
            }
            "highlight" => {
                props.highlight = get_w_val(&child).map(String::from);
            }
            "caps" => {
                props.caps = Some(parse_toggle_property(&child));
            }
            "smallCaps" => {
                props.small_caps = Some(parse_toggle_property(&child));
            }
            "shadow" => {
                props.shadow = Some(parse_toggle_property(&child));
            }
            "outline" => {
                props.outline = Some(parse_toggle_property(&child));
            }
            "emboss" => {
                props.emboss = Some(parse_toggle_property(&child));
            }
            "imprint" => {
                props.imprint = Some(parse_toggle_property(&child));
            }
            "spacing" => {
                props.char_spacing = get_w_val(&child).and_then(|v| v.parse::<i32>().ok());
            }
            "position" => {
                props.position = get_w_val(&child).and_then(|v| v.parse::<i32>().ok());
            }
            "kern" => {
                props.kern = get_w_val(&child).and_then(|v| v.parse::<i32>().ok());
            }
            _ => {}
        }
    }

    props
}

/// Parse `<w:pPr>` paragraph properties from a node's children.
fn parse_paragraph_properties(node: &roxmltree::Node) -> ParagraphProperties {
    let mut props = ParagraphProperties::default();

    for child in node.children() {
        if !child.is_element() {
            continue;
        }

        match child.tag_name().name() {
            "jc" => {
                props.alignment = get_w_val(&child).map(String::from);
            }
            "spacing" => {
                props.spacing_before = get_w_attr_i32(&child, "before");
                props.spacing_after = get_w_attr_i32(&child, "after");
                props.spacing_line = get_w_attr_i32(&child, "line");
                props.spacing_line_rule = get_w_attr_string(&child, "lineRule");
            }
            "ind" => {
                props.indent_left = get_w_attr_i32(&child, "left");
                props.indent_right = get_w_attr_i32(&child, "right");
                props.indent_first_line = get_w_attr_i32(&child, "firstLine");
                props.indent_hanging = get_w_attr_i32(&child, "hanging");
            }
            "outlineLvl" => {
                props.outline_level = get_w_val(&child).and_then(|v| v.parse::<u8>().ok());
            }
            "keepNext" => {
                props.keep_next = Some(parse_toggle_property(&child));
            }
            "keepLines" => {
                props.keep_lines = Some(parse_toggle_property(&child));
            }
            "pageBreakBefore" => {
                props.page_break_before = Some(parse_toggle_property(&child));
            }
            "widowControl" => {
                props.widow_control = Some(parse_toggle_property(&child));
            }
            "suppressAutoHyphens" => {
                props.suppress_auto_hyphens = Some(parse_toggle_property(&child));
            }
            "bidi" => {
                props.bidi = Some(parse_toggle_property(&child));
            }
            "shd" => {
                props.shading_fill = get_w_attr_string(&child, "fill");
                props.shading_val = get_w_attr_string(&child, "val");
            }
            "pBdr" => {
                for border_child in child.children() {
                    if !border_child.is_element() {
                        continue;
                    }
                    match border_child.tag_name().name() {
                        "top" => props.border_top = get_w_val(&border_child).map(String::from),
                        "bottom" => props.border_bottom = get_w_val(&border_child).map(String::from),
                        "left" | "start" => props.border_left = get_w_val(&border_child).map(String::from),
                        "right" | "end" => props.border_right = get_w_val(&border_child).map(String::from),
                        _ => {}
                    }
                }
            }
            _ => {}
        }
    }

    props
}

// --- Style Resolution ---

impl StyleCatalog {
    /// Resolve a style by walking its `basedOn` inheritance chain.
    ///
    /// The resolution order is:
    /// 1. Document defaults (`<w:docDefaults>`)
    /// 2. Base style chain (walking `basedOn` from root to leaf)
    /// 3. The style itself
    ///
    /// For `Option` fields, a child value of `Some(x)` overrides the parent.
    /// A value of `None` inherits from the parent. For boolean toggle properties,
    /// `Some(false)` explicitly disables the property.
    ///
    /// The chain depth is limited to 20 to prevent infinite loops from circular references.
    pub fn resolve_style(&self, style_id: &str) -> ResolvedStyle {
        // Start with document defaults
        let mut resolved = ResolvedStyle {
            paragraph_properties: self.default_paragraph_properties.clone(),
            run_properties: self.default_run_properties.clone(),
        };

        // Collect the inheritance chain (from root ancestor to the style itself)
        let chain = self.collect_chain(style_id);

        // Apply each style in order (root ancestor first, target style last)
        for style_def in &chain {
            merge_paragraph_properties(&mut resolved.paragraph_properties, &style_def.paragraph_properties);
            merge_run_properties(&mut resolved.run_properties, &style_def.run_properties);
        }

        resolved
    }

    /// Collect the basedOn chain for a style, ordered from root ancestor to the style itself.
    ///
    /// Limited to 20 levels to prevent cycles.
    fn collect_chain(&self, style_id: &str) -> Vec<&StyleDefinition> {
        const MAX_DEPTH: usize = 20;

        let mut chain = Vec::new();
        let mut current_id = Some(style_id.to_string());
        let mut visited = Vec::new();

        while let Some(id) = current_id {
            if visited.len() >= MAX_DEPTH {
                break;
            }
            if visited.contains(&id) {
                // Cycle detected
                break;
            }

            if let Some(style_def) = self.styles.get(&id) {
                visited.push(id);
                chain.push(style_def);
                current_id = style_def.based_on.clone();
            } else {
                break;
            }
        }

        // Reverse so root ancestor is first and the target style is last
        chain.reverse();
        chain
    }
}

// --- Merge helpers ---

/// Merge child run properties onto parent, where `Some` in child overrides parent.
fn merge_run_properties(base: &mut RunProperties, overlay: &RunProperties) {
    if overlay.bold.is_some() {
        base.bold = overlay.bold;
    }
    if overlay.italic.is_some() {
        base.italic = overlay.italic;
    }
    if overlay.underline.is_some() {
        base.underline = overlay.underline;
    }
    if overlay.strikethrough.is_some() {
        base.strikethrough = overlay.strikethrough;
    }
    if overlay.color.is_some() {
        base.color.clone_from(&overlay.color);
    }
    if overlay.font_size_half_points.is_some() {
        base.font_size_half_points = overlay.font_size_half_points;
    }
    if overlay.font_ascii.is_some() {
        base.font_ascii.clone_from(&overlay.font_ascii);
    }
    if overlay.font_ascii_theme.is_some() {
        base.font_ascii_theme.clone_from(&overlay.font_ascii_theme);
    }
    if overlay.vert_align.is_some() {
        base.vert_align.clone_from(&overlay.vert_align);
    }
    if overlay.font_h_ansi.is_some() {
        base.font_h_ansi.clone_from(&overlay.font_h_ansi);
    }
    if overlay.font_cs.is_some() {
        base.font_cs.clone_from(&overlay.font_cs);
    }
    if overlay.font_east_asia.is_some() {
        base.font_east_asia.clone_from(&overlay.font_east_asia);
    }
    if overlay.highlight.is_some() {
        base.highlight.clone_from(&overlay.highlight);
    }
    if overlay.caps.is_some() {
        base.caps = overlay.caps;
    }
    if overlay.small_caps.is_some() {
        base.small_caps = overlay.small_caps;
    }
    if overlay.shadow.is_some() {
        base.shadow = overlay.shadow;
    }
    if overlay.outline.is_some() {
        base.outline = overlay.outline;
    }
    if overlay.emboss.is_some() {
        base.emboss = overlay.emboss;
    }
    if overlay.imprint.is_some() {
        base.imprint = overlay.imprint;
    }
    if overlay.char_spacing.is_some() {
        base.char_spacing = overlay.char_spacing;
    }
    if overlay.position.is_some() {
        base.position = overlay.position;
    }
    if overlay.kern.is_some() {
        base.kern = overlay.kern;
    }
    // Theme color, tint, and shade form an atomic group: if theme_color changes,
    // tint/shade from the parent must not leak through.
    if overlay.theme_color.is_some() {
        base.theme_color.clone_from(&overlay.theme_color);
        base.theme_tint = overlay.theme_tint.clone();
        base.theme_shade = overlay.theme_shade.clone();
    } else {
        if overlay.theme_tint.is_some() {
            base.theme_tint.clone_from(&overlay.theme_tint);
        }
        if overlay.theme_shade.is_some() {
            base.theme_shade.clone_from(&overlay.theme_shade);
        }
    }
}

/// Merge child paragraph properties onto parent, where `Some` in child overrides parent.
fn merge_paragraph_properties(base: &mut ParagraphProperties, overlay: &ParagraphProperties) {
    if overlay.alignment.is_some() {
        base.alignment.clone_from(&overlay.alignment);
    }
    if overlay.spacing_before.is_some() {
        base.spacing_before = overlay.spacing_before;
    }
    if overlay.spacing_after.is_some() {
        base.spacing_after = overlay.spacing_after;
    }
    if overlay.spacing_line.is_some() {
        base.spacing_line = overlay.spacing_line;
    }
    if overlay.spacing_line_rule.is_some() {
        base.spacing_line_rule.clone_from(&overlay.spacing_line_rule);
    }
    if overlay.indent_left.is_some() {
        base.indent_left = overlay.indent_left;
    }
    if overlay.indent_right.is_some() {
        base.indent_right = overlay.indent_right;
    }
    if overlay.indent_first_line.is_some() {
        base.indent_first_line = overlay.indent_first_line;
    }
    if overlay.indent_hanging.is_some() {
        base.indent_hanging = overlay.indent_hanging;
    }
    if overlay.outline_level.is_some() {
        base.outline_level = overlay.outline_level;
    }
    if overlay.keep_next.is_some() {
        base.keep_next = overlay.keep_next;
    }
    if overlay.keep_lines.is_some() {
        base.keep_lines = overlay.keep_lines;
    }
    if overlay.page_break_before.is_some() {
        base.page_break_before = overlay.page_break_before;
    }
    if overlay.widow_control.is_some() {
        base.widow_control = overlay.widow_control;
    }
    if overlay.suppress_auto_hyphens.is_some() {
        base.suppress_auto_hyphens = overlay.suppress_auto_hyphens;
    }
    if overlay.bidi.is_some() {
        base.bidi = overlay.bidi;
    }
    if overlay.shading_fill.is_some() {
        base.shading_fill.clone_from(&overlay.shading_fill);
    }
    if overlay.shading_val.is_some() {
        base.shading_val.clone_from(&overlay.shading_val);
    }
    if overlay.border_top.is_some() {
        base.border_top.clone_from(&overlay.border_top);
    }
    if overlay.border_bottom.is_some() {
        base.border_bottom.clone_from(&overlay.border_bottom);
    }
    if overlay.border_left.is_some() {
        base.border_left.clone_from(&overlay.border_left);
    }
    if overlay.border_right.is_some() {
        base.border_right.clone_from(&overlay.border_right);
    }
}

// --- XML helpers ---

/// Get the `w:val` attribute from a node.
///
/// Tries namespaced attribute first, then falls back to unqualified `val`.
fn get_w_val<'a>(node: &'a roxmltree::Node) -> Option<&'a str> {
    node.attribute((WORDPROCESSINGML_NAMESPACE, "val"))
        .or_else(|| node.attribute("val"))
}

/// Get a namespaced integer attribute from a node (e.g., `w:before`, `w:left`).
fn get_w_attr_i32(node: &roxmltree::Node, local_name: &str) -> Option<i32> {
    node.attribute((WORDPROCESSINGML_NAMESPACE, local_name))
        .or_else(|| node.attribute(local_name))
        .and_then(|v| v.parse::<i32>().ok())
}

/// Get a namespaced string attribute from a node.
fn get_w_attr_string(node: &roxmltree::Node, local_name: &str) -> Option<String> {
    node.attribute((WORDPROCESSINGML_NAMESPACE, local_name))
        .or_else(|| node.attribute(local_name))
        .map(String::from)
}

/// Find the first child element with the given local name.
fn find_child_element<'a>(node: &'a roxmltree::Node, local_name: &str) -> Option<roxmltree::Node<'a, 'a>> {
    node.children()
        .find(|c| c.is_element() && c.tag_name().name() == local_name)
}

/// Parse a toggle (boolean) property element.
///
/// - `<w:b/>` (no val attribute) -> `true`
/// - `<w:b w:val="1"/>` or `<w:b w:val="true"/>` -> `true`
/// - `<w:b w:val="0"/>` or `<w:b w:val="false"/>` -> `false`
fn parse_toggle_property(node: &roxmltree::Node) -> bool {
    match get_w_val(node) {
        None => true, // bare element like <w:b/> means enabled
        Some(val) => !matches!(val, "0" | "false"),
    }
}

// --- Tests ---

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

    /// Namespace prefix for building test XML.
    const W_NS: &str = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";

    fn make_styles_xml(body: &str) -> String {
        format!(
            r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<w:styles xmlns:w="{W_NS}">
{body}
</w:styles>"#
        )
    }

    #[test]
    fn test_parse_empty_styles() {
        let xml = make_styles_xml("");
        let catalog = parse_styles_xml(&xml).expect("should parse empty styles");
        assert!(catalog.styles.is_empty());
        assert_eq!(catalog.default_run_properties, RunProperties::default());
        assert_eq!(catalog.default_paragraph_properties, ParagraphProperties::default());
    }

    #[test]
    fn test_parse_doc_defaults() {
        let xml = make_styles_xml(
            r#"
            <w:docDefaults>
                <w:rPrDefault>
                    <w:rPr>
                        <w:sz w:val="24"/>
                        <w:rFonts w:ascii="Calibri" w:asciiTheme="minorHAnsi"/>
                    </w:rPr>
                </w:rPrDefault>
                <w:pPrDefault>
                    <w:pPr>
                        <w:spacing w:after="160" w:line="259"/>
                    </w:pPr>
                </w:pPrDefault>
            </w:docDefaults>
            "#,
        );
        let catalog = parse_styles_xml(&xml).expect("should parse doc defaults");

        assert_eq!(catalog.default_run_properties.font_size_half_points, Some(24));
        assert_eq!(catalog.default_run_properties.font_ascii.as_deref(), Some("Calibri"));
        assert_eq!(
            catalog.default_run_properties.font_ascii_theme.as_deref(),
            Some("minorHAnsi")
        );
        assert_eq!(catalog.default_paragraph_properties.spacing_after, Some(160));
        assert_eq!(catalog.default_paragraph_properties.spacing_line, Some(259));
    }

    #[test]
    fn test_parse_style_definitions() {
        let xml = make_styles_xml(
            r#"
            <w:style w:type="paragraph" w:default="1" w:styleId="Normal">
                <w:name w:val="Normal"/>
                <w:pPr>
                    <w:spacing w:after="200"/>
                    <w:jc w:val="left"/>
                </w:pPr>
                <w:rPr>
                    <w:sz w:val="22"/>
                </w:rPr>
            </w:style>
            <w:style w:type="paragraph" w:styleId="Heading1">
                <w:name w:val="heading 1"/>
                <w:basedOn w:val="Normal"/>
                <w:next w:val="Normal"/>
                <w:pPr>
                    <w:keepNext/>
                    <w:keepLines/>
                    <w:spacing w:before="240"/>
                    <w:outlineLvl w:val="0"/>
                </w:pPr>
                <w:rPr>
                    <w:b/>
                    <w:color w:val="2F5496"/>
                    <w:sz w:val="32"/>
                    <w:rFonts w:asciiTheme="majorHAnsi"/>
                </w:rPr>
            </w:style>
            <w:style w:type="character" w:styleId="Strong">
                <w:name w:val="Strong"/>
                <w:rPr>
                    <w:b/>
                </w:rPr>
            </w:style>
            "#,
        );
        let catalog = parse_styles_xml(&xml).expect("should parse style definitions");

        assert_eq!(catalog.styles.len(), 3);

        // Normal
        let normal = catalog.styles.get("Normal").expect("Normal style must exist");
        assert_eq!(normal.style_type, StyleType::Paragraph);
        assert!(normal.is_default);
        assert_eq!(normal.name.as_deref(), Some("Normal"));
        assert_eq!(normal.paragraph_properties.spacing_after, Some(200));
        assert_eq!(normal.paragraph_properties.alignment.as_deref(), Some("left"));
        assert_eq!(normal.run_properties.font_size_half_points, Some(22));

        // Heading1
        let heading1 = catalog.styles.get("Heading1").expect("Heading1 style must exist");
        assert_eq!(heading1.style_type, StyleType::Paragraph);
        assert!(!heading1.is_default);
        assert_eq!(heading1.name.as_deref(), Some("heading 1"));
        assert_eq!(heading1.based_on.as_deref(), Some("Normal"));
        assert_eq!(heading1.next_style.as_deref(), Some("Normal"));
        assert_eq!(heading1.paragraph_properties.keep_next, Some(true));
        assert_eq!(heading1.paragraph_properties.keep_lines, Some(true));
        assert_eq!(heading1.paragraph_properties.spacing_before, Some(240));
        assert_eq!(heading1.paragraph_properties.outline_level, Some(0));
        assert_eq!(heading1.run_properties.bold, Some(true));
        assert_eq!(heading1.run_properties.color.as_deref(), Some("2F5496"));
        assert_eq!(heading1.run_properties.font_size_half_points, Some(32));
        assert_eq!(heading1.run_properties.font_ascii_theme.as_deref(), Some("majorHAnsi"));

        // Strong (character style)
        let strong = catalog.styles.get("Strong").expect("Strong style must exist");
        assert_eq!(strong.style_type, StyleType::Character);
        assert_eq!(strong.run_properties.bold, Some(true));
    }

    #[test]
    fn test_resolve_style_inheritance() {
        // 3-level chain: docDefaults -> Normal -> Heading1
        let xml = make_styles_xml(
            r#"
            <w:docDefaults>
                <w:rPrDefault>
                    <w:rPr>
                        <w:sz w:val="24"/>
                        <w:rFonts w:ascii="Calibri"/>
                    </w:rPr>
                </w:rPrDefault>
                <w:pPrDefault>
                    <w:pPr>
                        <w:spacing w:after="160"/>
                    </w:pPr>
                </w:pPrDefault>
            </w:docDefaults>
            <w:style w:type="paragraph" w:default="1" w:styleId="Normal">
                <w:name w:val="Normal"/>
                <w:pPr>
                    <w:spacing w:after="200"/>
                    <w:jc w:val="left"/>
                </w:pPr>
            </w:style>
            <w:style w:type="paragraph" w:styleId="Heading1">
                <w:name w:val="heading 1"/>
                <w:basedOn w:val="Normal"/>
                <w:pPr>
                    <w:keepNext/>
                    <w:spacing w:before="240"/>
                    <w:outlineLvl w:val="0"/>
                    <w:jc w:val="center"/>
                </w:pPr>
                <w:rPr>
                    <w:b/>
                    <w:sz w:val="32"/>
                </w:rPr>
            </w:style>
            "#,
        );
        let catalog = parse_styles_xml(&xml).expect("should parse");

        let resolved = catalog.resolve_style("Heading1");

        // Run properties: docDefaults font_ascii=Calibri, sz=24; Heading1 overrides sz=32, adds bold
        assert_eq!(resolved.run_properties.font_ascii.as_deref(), Some("Calibri"));
        assert_eq!(resolved.run_properties.font_size_half_points, Some(32));
        assert_eq!(resolved.run_properties.bold, Some(true));

        // Paragraph properties: docDefaults spacing_after=160; Normal overrides to 200 and sets jc=left;
        // Heading1 overrides jc=center, adds spacing_before=240, keep_next=true, outline_level=0
        assert_eq!(resolved.paragraph_properties.spacing_after, Some(200));
        assert_eq!(resolved.paragraph_properties.alignment.as_deref(), Some("center"));
        assert_eq!(resolved.paragraph_properties.spacing_before, Some(240));
        assert_eq!(resolved.paragraph_properties.keep_next, Some(true));
        assert_eq!(resolved.paragraph_properties.outline_level, Some(0));
    }

    #[test]
    fn test_resolve_style_toggle() {
        // basedOn has bold=true, derived explicitly disables bold with w:val="0"
        let xml = make_styles_xml(
            r#"
            <w:style w:type="paragraph" w:styleId="BoldBase">
                <w:name w:val="Bold Base"/>
                <w:rPr>
                    <w:b/>
                    <w:i/>
                </w:rPr>
            </w:style>
            <w:style w:type="paragraph" w:styleId="NoBold">
                <w:name w:val="No Bold"/>
                <w:basedOn w:val="BoldBase"/>
                <w:rPr>
                    <w:b w:val="0"/>
                </w:rPr>
            </w:style>
            "#,
        );
        let catalog = parse_styles_xml(&xml).expect("should parse");

        let resolved = catalog.resolve_style("NoBold");

        // Bold should be explicitly false (overridden)
        assert_eq!(resolved.run_properties.bold, Some(false));
        // Italic should be inherited from BoldBase
        assert_eq!(resolved.run_properties.italic, Some(true));
    }

    #[test]
    fn test_resolve_style_cycle_protection() {
        // Create a circular basedOn chain: A -> B -> A
        let xml = make_styles_xml(
            r#"
            <w:style w:type="paragraph" w:styleId="StyleA">
                <w:name w:val="Style A"/>
                <w:basedOn w:val="StyleB"/>
                <w:rPr>
                    <w:b/>
                </w:rPr>
            </w:style>
            <w:style w:type="paragraph" w:styleId="StyleB">
                <w:name w:val="Style B"/>
                <w:basedOn w:val="StyleA"/>
                <w:rPr>
                    <w:i/>
                </w:rPr>
            </w:style>
            "#,
        );
        let catalog = parse_styles_xml(&xml).expect("should parse");

        // Must not panic or infinite loop
        let resolved = catalog.resolve_style("StyleA");

        // Both bold and italic should be present (the cycle is broken, and
        // both styles in the chain contribute their properties)
        assert_eq!(resolved.run_properties.bold, Some(true));
        assert_eq!(resolved.run_properties.italic, Some(true));
    }

    #[test]
    fn test_resolve_nonexistent_style() {
        let xml = make_styles_xml("");
        let catalog = parse_styles_xml(&xml).expect("should parse");

        let resolved = catalog.resolve_style("DoesNotExist");

        // Should return empty defaults without panicking
        assert_eq!(resolved, ResolvedStyle::default());
    }

    #[test]
    fn test_resolve_style_with_missing_base() {
        // Style references a basedOn that doesn't exist in the catalog
        let xml = make_styles_xml(
            r#"
            <w:style w:type="paragraph" w:styleId="Orphan">
                <w:name w:val="Orphan"/>
                <w:basedOn w:val="NonexistentBase"/>
                <w:rPr>
                    <w:b/>
                </w:rPr>
            </w:style>
            "#,
        );
        let catalog = parse_styles_xml(&xml).expect("should parse");

        let resolved = catalog.resolve_style("Orphan");

        // Should resolve with just the style's own properties
        assert_eq!(resolved.run_properties.bold, Some(true));
    }

    #[test]
    fn test_parse_indentation() {
        let xml = make_styles_xml(
            r#"
            <w:style w:type="paragraph" w:styleId="Indented">
                <w:name w:val="Indented"/>
                <w:pPr>
                    <w:ind w:left="720" w:right="360" w:firstLine="360" w:hanging="180"/>
                </w:pPr>
            </w:style>
            "#,
        );
        let catalog = parse_styles_xml(&xml).expect("should parse");

        let style = catalog.styles.get("Indented").expect("style must exist");
        assert_eq!(style.paragraph_properties.indent_left, Some(720));
        assert_eq!(style.paragraph_properties.indent_right, Some(360));
        assert_eq!(style.paragraph_properties.indent_first_line, Some(360));
        assert_eq!(style.paragraph_properties.indent_hanging, Some(180));
    }

    #[test]
    fn test_parse_underline_none() {
        let xml = make_styles_xml(
            r#"
            <w:style w:type="character" w:styleId="NoUnderline">
                <w:name w:val="No Underline"/>
                <w:rPr>
                    <w:u w:val="none"/>
                </w:rPr>
            </w:style>
            "#,
        );
        let catalog = parse_styles_xml(&xml).expect("should parse");

        let style = catalog.styles.get("NoUnderline").expect("style must exist");
        assert_eq!(style.run_properties.underline, Some(false));
    }

    #[test]
    fn test_parse_underline_single() {
        let xml = make_styles_xml(
            r#"
            <w:style w:type="character" w:styleId="Underlined">
                <w:name w:val="Underlined"/>
                <w:rPr>
                    <w:u w:val="single"/>
                </w:rPr>
            </w:style>
            "#,
        );
        let catalog = parse_styles_xml(&xml).expect("should parse");

        let style = catalog.styles.get("Underlined").expect("style must exist");
        assert_eq!(style.run_properties.underline, Some(true));
    }

    #[test]
    fn test_parse_underline_bare() {
        // Test for bare <w:u/> (no val attribute) -> underline should be Some(true)
        let xml = make_styles_xml(
            r#"
            <w:style w:type="character" w:styleId="BareUnderline">
                <w:name w:val="Bare Underline"/>
                <w:rPr>
                    <w:u/>
                </w:rPr>
            </w:style>
            "#,
        );
        let catalog = parse_styles_xml(&xml).expect("should parse");

        let style = catalog.styles.get("BareUnderline").expect("style must exist");
        assert_eq!(style.run_properties.underline, Some(true));
    }

    #[test]
    fn test_parse_bold_explicit_true() {
        // Test for <w:b w:val="true"/> -> bold should be Some(true)
        let xml = make_styles_xml(
            r#"
            <w:style w:type="character" w:styleId="ExplicitBold">
                <w:name w:val="Explicit Bold"/>
                <w:rPr>
                    <w:b w:val="true"/>
                </w:rPr>
            </w:style>
            "#,
        );
        let catalog = parse_styles_xml(&xml).expect("should parse");

        let style = catalog.styles.get("ExplicitBold").expect("style must exist");
        assert_eq!(style.run_properties.bold, Some(true));
    }

    #[test]
    fn test_parse_invalid_xml() {
        let result = parse_styles_xml("<<<not valid xml");
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_spacing_line_rule() {
        // Test for spacing_line_rule parsing
        let xml = make_styles_xml(
            r#"
            <w:style w:type="paragraph" w:styleId="SpacingRule">
                <w:name w:val="Spacing Rule"/>
                <w:pPr>
                    <w:spacing w:line="360" w:lineRule="exact"/>
                </w:pPr>
            </w:style>
            "#,
        );
        let catalog = parse_styles_xml(&xml).expect("should parse");

        let style = catalog.styles.get("SpacingRule").expect("style must exist");
        assert_eq!(style.paragraph_properties.spacing_line, Some(360));
        assert_eq!(style.paragraph_properties.spacing_line_rule.as_deref(), Some("exact"));
    }

    #[test]
    fn test_parse_latent_styles_skipped() {
        let xml = make_styles_xml(
            r#"
            <w:latentStyles w:defLockedState="0" w:defUIPriority="99">
                <w:lsdException w:name="Normal" w:uiPriority="0" w:qFormat="1"/>
            </w:latentStyles>
            <w:style w:type="paragraph" w:styleId="Normal">
                <w:name w:val="Normal"/>
            </w:style>
            "#,
        );
        let catalog = parse_styles_xml(&xml).expect("should parse");

        // latentStyles should be skipped, only the actual style parsed
        assert_eq!(catalog.styles.len(), 1);
        assert!(catalog.styles.contains_key("Normal"));
    }

    #[test]
    fn test_parse_vert_align() {
        // Test for vert_align parsing
        let xml = make_styles_xml(
            r#"
            <w:style w:type="character" w:styleId="Superscript">
                <w:name w:val="Superscript"/>
                <w:rPr>
                    <w:vertAlign w:val="superscript"/>
                </w:rPr>
            </w:style>
            <w:style w:type="character" w:styleId="Subscript">
                <w:name w:val="Subscript"/>
                <w:rPr>
                    <w:vertAlign w:val="subscript"/>
                </w:rPr>
            </w:style>
            "#,
        );
        let catalog = parse_styles_xml(&xml).expect("should parse");

        let super_style = catalog.styles.get("Superscript").expect("style must exist");
        assert_eq!(super_style.run_properties.vert_align.as_deref(), Some("superscript"));

        let sub_style = catalog.styles.get("Subscript").expect("style must exist");
        assert_eq!(sub_style.run_properties.vert_align.as_deref(), Some("subscript"));
    }

    #[test]
    fn test_parse_multilingual_fonts() {
        // Test for multilingual rFonts parsing
        let xml = make_styles_xml(
            r#"
            <w:style w:type="character" w:styleId="MultiLang">
                <w:name w:val="MultiLang"/>
                <w:rPr>
                    <w:rFonts w:ascii="Calibri" w:hAnsi="Arial" w:cs="Courier" w:eastAsia="SimSun"/>
                </w:rPr>
            </w:style>
            "#,
        );
        let catalog = parse_styles_xml(&xml).expect("should parse");

        let style = catalog.styles.get("MultiLang").expect("style must exist");
        assert_eq!(style.run_properties.font_ascii.as_deref(), Some("Calibri"));
        assert_eq!(style.run_properties.font_h_ansi.as_deref(), Some("Arial"));
        assert_eq!(style.run_properties.font_cs.as_deref(), Some("Courier"));
        assert_eq!(style.run_properties.font_east_asia.as_deref(), Some("SimSun"));
    }

    #[test]
    fn test_resolve_character_style() {
        // Test for character style resolution
        let xml = make_styles_xml(
            r#"
            <w:style w:type="character" w:styleId="BaseChar">
                <w:name w:val="Base Char"/>
                <w:rPr>
                    <w:b/>
                    <w:sz w:val="24"/>
                </w:rPr>
            </w:style>
            <w:style w:type="character" w:styleId="DerivedChar">
                <w:name w:val="Derived Char"/>
                <w:basedOn w:val="BaseChar"/>
                <w:rPr>
                    <w:i/>
                    <w:color w:val="FF0000"/>
                </w:rPr>
            </w:style>
            "#,
        );
        let catalog = parse_styles_xml(&xml).expect("should parse");

        let resolved = catalog.resolve_style("DerivedChar");

        // Should inherit bold and size from BaseChar, add italic and color
        assert_eq!(resolved.run_properties.bold, Some(true));
        assert_eq!(resolved.run_properties.font_size_half_points, Some(24));
        assert_eq!(resolved.run_properties.italic, Some(true));
        assert_eq!(resolved.run_properties.color.as_deref(), Some("FF0000"));
    }

    #[test]
    fn test_deep_inheritance_chain() {
        // Build a 5-level chain: Level0 -> Level1 -> Level2 -> Level3 -> Level4
        let xml = make_styles_xml(
            r#"
            <w:style w:type="paragraph" w:styleId="Level0">
                <w:name w:val="Level 0"/>
                <w:rPr>
                    <w:sz w:val="20"/>
                </w:rPr>
                <w:pPr>
                    <w:spacing w:after="100"/>
                </w:pPr>
            </w:style>
            <w:style w:type="paragraph" w:styleId="Level1">
                <w:name w:val="Level 1"/>
                <w:basedOn w:val="Level0"/>
                <w:rPr>
                    <w:b/>
                </w:rPr>
            </w:style>
            <w:style w:type="paragraph" w:styleId="Level2">
                <w:name w:val="Level 2"/>
                <w:basedOn w:val="Level1"/>
                <w:rPr>
                    <w:i/>
                </w:rPr>
            </w:style>
            <w:style w:type="paragraph" w:styleId="Level3">
                <w:name w:val="Level 3"/>
                <w:basedOn w:val="Level2"/>
                <w:pPr>
                    <w:jc w:val="center"/>
                </w:pPr>
            </w:style>
            <w:style w:type="paragraph" w:styleId="Level4">
                <w:name w:val="Level 4"/>
                <w:basedOn w:val="Level3"/>
                <w:rPr>
                    <w:sz w:val="40"/>
                </w:rPr>
            </w:style>
            "#,
        );
        let catalog = parse_styles_xml(&xml).expect("should parse");

        let resolved = catalog.resolve_style("Level4");

        // sz: Level0=20, overridden by Level4=40
        assert_eq!(resolved.run_properties.font_size_half_points, Some(40));
        // bold: from Level1
        assert_eq!(resolved.run_properties.bold, Some(true));
        // italic: from Level2
        assert_eq!(resolved.run_properties.italic, Some(true));
        // alignment: from Level3
        assert_eq!(resolved.paragraph_properties.alignment.as_deref(), Some("center"));
        // spacing_after: from Level0 (not overridden)
        assert_eq!(resolved.paragraph_properties.spacing_after, Some(100));
    }

    #[test]
    fn test_parse_page_break_before() {
        let xml = make_styles_xml(
            r#"
            <w:style w:type="paragraph" w:styleId="PageBreakStyle">
                <w:name w:val="Page Break Style"/>
                <w:pPr>
                    <w:pageBreakBefore/>
                </w:pPr>
            </w:style>
            "#,
        );
        let catalog = parse_styles_xml(&xml).expect("should parse");

        let style = catalog.styles.get("PageBreakStyle").expect("style must exist");
        assert_eq!(style.paragraph_properties.page_break_before, Some(true));
    }

    #[test]
    fn test_parse_widow_control() {
        let xml = make_styles_xml(
            r#"
            <w:style w:type="paragraph" w:styleId="WidowControl">
                <w:name w:val="Widow Control"/>
                <w:pPr>
                    <w:widowControl w:val="0"/>
                </w:pPr>
            </w:style>
            "#,
        );
        let catalog = parse_styles_xml(&xml).expect("should parse");

        let style = catalog.styles.get("WidowControl").expect("style must exist");
        assert_eq!(style.paragraph_properties.widow_control, Some(false));
    }

    #[test]
    fn test_parse_bidi() {
        let xml = make_styles_xml(
            r#"
            <w:style w:type="paragraph" w:styleId="RightToLeft">
                <w:name w:val="Right to Left"/>
                <w:pPr>
                    <w:bidi/>
                </w:pPr>
            </w:style>
            "#,
        );
        let catalog = parse_styles_xml(&xml).expect("should parse");

        let style = catalog.styles.get("RightToLeft").expect("style must exist");
        assert_eq!(style.paragraph_properties.bidi, Some(true));
    }

    #[test]
    fn test_parse_shading() {
        let xml = make_styles_xml(
            r#"
            <w:style w:type="paragraph" w:styleId="ShadedPara">
                <w:name w:val="Shaded Paragraph"/>
                <w:pPr>
                    <w:shd w:val="clear" w:fill="FFFF00"/>
                </w:pPr>
            </w:style>
            "#,
        );
        let catalog = parse_styles_xml(&xml).expect("should parse");

        let style = catalog.styles.get("ShadedPara").expect("style must exist");
        assert_eq!(style.paragraph_properties.shading_val.as_deref(), Some("clear"));
        assert_eq!(style.paragraph_properties.shading_fill.as_deref(), Some("FFFF00"));
    }

    #[test]
    fn test_parse_paragraph_borders() {
        let xml = make_styles_xml(
            r#"
            <w:style w:type="paragraph" w:styleId="BorderedPara">
                <w:name w:val="Bordered Paragraph"/>
                <w:pPr>
                    <w:pBdr>
                        <w:top w:val="single"/>
                        <w:bottom w:val="double"/>
                        <w:left w:val="triple"/>
                        <w:right w:val="dashed"/>
                    </w:pBdr>
                </w:pPr>
            </w:style>
            "#,
        );
        let catalog = parse_styles_xml(&xml).expect("should parse");

        let style = catalog.styles.get("BorderedPara").expect("style must exist");
        assert_eq!(style.paragraph_properties.border_top.as_deref(), Some("single"));
        assert_eq!(style.paragraph_properties.border_bottom.as_deref(), Some("double"));
        assert_eq!(style.paragraph_properties.border_left.as_deref(), Some("triple"));
        assert_eq!(style.paragraph_properties.border_right.as_deref(), Some("dashed"));
    }

    #[test]
    fn test_paragraph_properties_inheritance() {
        // Test that page_break_before inherits through basedOn chain
        let xml = make_styles_xml(
            r#"
            <w:style w:type="paragraph" w:styleId="BaseStyle">
                <w:name w:val="Base Style"/>
                <w:pPr>
                    <w:pageBreakBefore/>
                    <w:spacing w:after="100"/>
                </w:pPr>
            </w:style>
            <w:style w:type="paragraph" w:styleId="DerivedStyle">
                <w:name w:val="Derived Style"/>
                <w:basedOn w:val="BaseStyle"/>
                <w:pPr>
                    <w:spacing w:before="50"/>
                </w:pPr>
            </w:style>
            "#,
        );
        let catalog = parse_styles_xml(&xml).expect("should parse");

        let resolved = catalog.resolve_style("DerivedStyle");

        // page_break_before should inherit from BaseStyle
        assert_eq!(resolved.paragraph_properties.page_break_before, Some(true));
        // spacing_before should come from DerivedStyle
        assert_eq!(resolved.paragraph_properties.spacing_before, Some(50));
        // spacing_after should inherit from BaseStyle
        assert_eq!(resolved.paragraph_properties.spacing_after, Some(100));
    }

    #[test]
    fn test_parse_highlight() {
        let xml = make_styles_xml(
            r#"
            <w:style w:type="character" w:styleId="HighlightStyle">
                <w:name w:val="Highlight Style"/>
                <w:rPr>
                    <w:highlight w:val="yellow"/>
                </w:rPr>
            </w:style>
            "#,
        );
        let catalog = parse_styles_xml(&xml).expect("should parse");

        let style = catalog.styles.get("HighlightStyle").expect("style must exist");
        assert_eq!(style.run_properties.highlight.as_deref(), Some("yellow"));
    }

    #[test]
    fn test_parse_caps_and_small_caps() {
        let xml = make_styles_xml(
            r#"
            <w:style w:type="character" w:styleId="CapsStyle">
                <w:name w:val="Caps Style"/>
                <w:rPr>
                    <w:caps/>
                    <w:smallCaps/>
                </w:rPr>
            </w:style>
            "#,
        );
        let catalog = parse_styles_xml(&xml).expect("should parse");

        let style = catalog.styles.get("CapsStyle").expect("style must exist");
        assert_eq!(style.run_properties.caps, Some(true));
        assert_eq!(style.run_properties.small_caps, Some(true));
    }

    #[test]
    fn test_parse_text_effects() {
        let xml = make_styles_xml(
            r#"
            <w:style w:type="character" w:styleId="EffectsStyle">
                <w:name w:val="Effects Style"/>
                <w:rPr>
                    <w:shadow/>
                    <w:outline/>
                    <w:emboss/>
                    <w:imprint/>
                </w:rPr>
            </w:style>
            "#,
        );
        let catalog = parse_styles_xml(&xml).expect("should parse");

        let style = catalog.styles.get("EffectsStyle").expect("style must exist");
        assert_eq!(style.run_properties.shadow, Some(true));
        assert_eq!(style.run_properties.outline, Some(true));
        assert_eq!(style.run_properties.emboss, Some(true));
        assert_eq!(style.run_properties.imprint, Some(true));
    }

    #[test]
    fn test_parse_char_spacing() {
        let xml = make_styles_xml(
            r#"
            <w:style w:type="character" w:styleId="SpacingStyle">
                <w:name w:val="Spacing Style"/>
                <w:rPr>
                    <w:spacing w:val="20"/>
                </w:rPr>
            </w:style>
            "#,
        );
        let catalog = parse_styles_xml(&xml).expect("should parse");

        let style = catalog.styles.get("SpacingStyle").expect("style must exist");
        assert_eq!(style.run_properties.char_spacing, Some(20));
    }

    #[test]
    fn test_parse_theme_color() {
        let xml = make_styles_xml(
            r#"
            <w:style w:type="character" w:styleId="ThemeColorStyle">
                <w:name w:val="Theme Color Style"/>
                <w:rPr>
                    <w:color w:val="2F5496" w:themeColor="accent1" w:themeTint="BF" w:themeShade="4D"/>
                </w:rPr>
            </w:style>
            "#,
        );
        let catalog = parse_styles_xml(&xml).expect("should parse");

        let style = catalog.styles.get("ThemeColorStyle").expect("style must exist");
        assert_eq!(style.run_properties.color.as_deref(), Some("2F5496"));
        assert_eq!(style.run_properties.theme_color.as_deref(), Some("accent1"));
        assert_eq!(style.run_properties.theme_tint.as_deref(), Some("BF"));
        assert_eq!(style.run_properties.theme_shade.as_deref(), Some("4D"));
    }

    #[test]
    fn test_run_properties_inheritance_with_effects() {
        // Test that caps/shadow inherit through basedOn chain
        let xml = make_styles_xml(
            r#"
            <w:style w:type="character" w:styleId="BaseCharStyle">
                <w:name w:val="Base Char"/>
                <w:rPr>
                    <w:b/>
                    <w:caps/>
                </w:rPr>
            </w:style>
            <w:style w:type="character" w:styleId="DerivedCharStyle">
                <w:name w:val="Derived Char"/>
                <w:basedOn w:val="BaseCharStyle"/>
                <w:rPr>
                    <w:i/>
                    <w:shadow/>
                </w:rPr>
            </w:style>
            "#,
        );
        let catalog = parse_styles_xml(&xml).expect("should parse");

        let resolved = catalog.resolve_style("DerivedCharStyle");

        // bold and caps should inherit from BaseCharStyle
        assert_eq!(resolved.run_properties.bold, Some(true));
        assert_eq!(resolved.run_properties.caps, Some(true));
        // italic and shadow should come from DerivedCharStyle
        assert_eq!(resolved.run_properties.italic, Some(true));
        assert_eq!(resolved.run_properties.shadow, Some(true));
    }
}