rlsp-yaml 0.11.0

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

use std::fmt::Write as _;

use rlsp_yaml_parser::node::{Document, Node};
use rlsp_yaml_parser::{LineIndex, Pos, Span};
use tower_lsp::lsp_types::{Hover, HoverContents, MarkupContent, MarkupKind, Position};

use crate::schema::JsonSchema;

// ──────────────────────────────────────────────────────────────────────────────
// Constants
// ──────────────────────────────────────────────────────────────────────────────

/// Maximum number of examples to display in hover output.
const MAX_EXAMPLES: usize = 3;

/// Maximum characters for a schema description before truncation.
const MAX_DESCRIPTION_LEN: usize = 200;

/// Maximum characters for an example value before truncation.
const MAX_EXAMPLE_LEN: usize = 100;

// ──────────────────────────────────────────────────────────────────────────────
// Public API
// ──────────────────────────────────────────────────────────────────────────────

/// Compute hover information for the AST documents at the given cursor position.
///
/// Returns `None` if the cursor falls outside all node spans (whitespace, comment,
/// document separator, empty line) or when `docs` is empty.
#[must_use]
pub fn hover_at(
    docs: &[Document<Span>],
    position: Position,
    schema: Option<&JsonSchema>,
) -> Option<Hover> {
    if docs.is_empty() {
        return None;
    }

    // LSP Position is 0-based line; parser Pos is 1-based line, 0-based column.
    let cursor = Pos {
        byte_offset: 0,
        line: position.line as usize + 1,
        column: position.character as usize,
    };

    let (path, node) = ast_walk(docs, cursor)?;

    let formatted_path = format_path(&path);
    let yaml_type = yaml_type_name(node);
    let value = scalar_value(node);

    let mut markdown = format_hover_markdown(&formatted_path, &yaml_type, value.as_deref());

    if let Some(s) = schema {
        let key_path = build_schema_key_path(&formatted_path);
        if let Some(prop_schema) = resolve_schema_path(s, &key_path) {
            let schema_section = format_schema_section(prop_schema);
            if !schema_section.is_empty() {
                markdown.push('\n');
                markdown.push_str(&schema_section);
            }
        }
    }

    Some(Hover {
        contents: HoverContents::Markup(MarkupContent {
            kind: MarkupKind::Markdown,
            value: markdown,
        }),
        range: None,
    })
}

// ──────────────────────────────────────────────────────────────────────────────
// AST walk — cursor resolution
// ──────────────────────────────────────────────────────────────────────────────

/// A segment in a YAML key path.
#[derive(Debug, Clone)]
enum PathSegment {
    Key(String),
    Index(usize),
}

/// Walk all documents and return the path + deepest node whose span contains `cursor`.
fn ast_walk(docs: &[Document<Span>], cursor: Pos) -> Option<(Vec<PathSegment>, &Node<Span>)> {
    for doc in docs {
        let idx = doc.line_index();
        if span_contains(node_loc(&doc.root), cursor, idx) {
            let mut path = Vec::new();
            if let Some(result) = walk_node(&doc.root, cursor, &mut path, idx) {
                return Some(result);
            }
        }
    }
    None
}

/// Recursively descend into `node` accumulating `path`. Returns the deepest
/// (path, node) pair whose span contains `cursor`.
fn walk_node<'a>(
    node: &'a Node<Span>,
    cursor: Pos,
    path: &mut Vec<PathSegment>,
    idx: &LineIndex,
) -> Option<(Vec<PathSegment>, &'a Node<Span>)> {
    match node {
        Node::Mapping { entries, .. } => {
            for (key, value) in entries {
                let key_name = match key {
                    Node::Scalar { value, .. } => value.clone(),
                    Node::Mapping { .. } | Node::Sequence { .. } | Node::Alias { .. } => continue,
                };

                if span_contains(node_loc(key), cursor, idx) {
                    // Cursor is on the key — hover shows the value at this key.
                    path.push(PathSegment::Key(key_name));
                    return Some((path.clone(), value));
                }

                if span_contains(node_loc(value), cursor, idx) {
                    path.push(PathSegment::Key(key_name));
                    return walk_node(value, cursor, path, idx)
                        .or_else(|| Some((path.clone(), value)));
                }
            }
            None
        }
        Node::Sequence { items, .. } => {
            for (i, item) in items.iter().enumerate() {
                if span_contains(node_loc(item), cursor, idx) {
                    path.push(PathSegment::Index(i));
                    return walk_node(item, cursor, path, idx)
                        .or_else(|| Some((path.clone(), item)));
                }
            }
            None
        }
        // Scalar or Alias: leaf node — already confirmed span contains cursor.
        Node::Scalar { .. } | Node::Alias { .. } => Some((path.clone(), node)),
    }
}

/// Returns `true` when `cursor` is within `span` using half-open `[start, end)`.
///
/// Comparison is lexicographic on `(line, column)`.
fn span_contains(span: Span, cursor: Pos, idx: &LineIndex) -> bool {
    let (start_line, start_col) = idx.line_column(span.start);
    let (end_line, end_col) = idx.line_column(span.end);
    let start = (start_line as usize, start_col as usize);
    let end = (end_line as usize, end_col as usize);
    let pos = (cursor.line, cursor.column);
    start <= pos && pos < end
}

/// Extract the `loc` span from any AST node.
const fn node_loc(node: &Node<Span>) -> Span {
    match node {
        Node::Scalar { loc, .. }
        | Node::Mapping { loc, .. }
        | Node::Sequence { loc, .. }
        | Node::Alias { loc, .. } => *loc,
    }
}

// ──────────────────────────────────────────────────────────────────────────────
// Path formatting
// ──────────────────────────────────────────────────────────────────────────────

/// Format the path segments into a dotted path string.
fn format_path(path: &[PathSegment]) -> String {
    let mut result = String::new();
    for (i, segment) in path.iter().enumerate() {
        match segment {
            PathSegment::Key(key) => {
                if i > 0 {
                    result.push('.');
                }
                result.push_str(key);
            }
            PathSegment::Index(idx) => {
                result.push('[');
                result.push_str(&idx.to_string());
                result.push(']');
            }
        }
    }
    result
}

// ──────────────────────────────────────────────────────────────────────────────
// Node info helpers
// ──────────────────────────────────────────────────────────────────────────────

/// Get the type name for a YAML node.
fn yaml_type_name(node: &Node<Span>) -> String {
    match node {
        Node::Mapping { .. } => "mapping".to_string(),
        Node::Sequence { .. } => "sequence".to_string(),
        Node::Scalar { .. } => "scalar".to_string(),
        Node::Alias { .. } => "alias".to_string(),
    }
}

/// Get the scalar value representation for display.
fn scalar_value(node: &Node<Span>) -> Option<String> {
    match node {
        Node::Scalar { value, .. } => Some(value.clone()),
        Node::Mapping { .. } | Node::Sequence { .. } | Node::Alias { .. } => None,
    }
}

// ──────────────────────────────────────────────────────────────────────────────
// Markdown formatting
// ──────────────────────────────────────────────────────────────────────────────

/// Escape backtick characters in a string for safe embedding in a markdown code span.
fn escape_for_code_span(s: &str) -> String {
    s.replace('`', "\\`")
}

/// Truncate a string to at most `max_chars` characters.
/// If truncated, appends the Unicode ellipsis character (U+2026).
fn truncate_to(s: &str, max_chars: usize) -> String {
    if s.chars().count() <= max_chars {
        return s.to_string();
    }
    let keep = max_chars - 1;
    let truncated: String = s
        .char_indices()
        .nth(keep)
        .map_or_else(|| s.to_string(), |(byte_idx, _)| s[..byte_idx].to_string());
    format!("{truncated}\u{2026}")
}

/// Format the hover content as Markdown.
fn format_hover_markdown(path: &str, yaml_type: &str, value: Option<&str>) -> String {
    let mut md = String::new();
    let escaped_path = escape_for_code_span(path);
    let _ = write!(md, "**Path:** `{escaped_path}`\n\n");
    let _ = writeln!(md, "**Type:** {yaml_type}");
    if let Some(val) = value {
        let escaped_val = escape_for_code_span(val);
        let _ = write!(md, "\n**Value:** `{escaped_val}`\n");
    }
    md
}

// ──────────────────────────────────────────────────────────────────────────────
// Schema lookup
// ──────────────────────────────────────────────────────────────────────────────

/// Build a schema key path (list of string keys) from a dotted path string like "a.b.c".
/// Array index segments like "[0]" are represented as "[]" to match schema `items` lookups.
fn build_schema_key_path(dotted_path: &str) -> Vec<String> {
    dotted_path
        .split('.')
        .flat_map(|segment| {
            // Handle "foo[0]" → ["foo", "[]"]
            segment.find('[').map_or_else(
                || vec![segment.to_string()],
                |bracket_pos| {
                    let key = &segment[..bracket_pos];
                    if key.is_empty() {
                        vec!["[]".to_string()]
                    } else {
                        vec![key.to_string(), "[]".to_string()]
                    }
                },
            )
        })
        .filter(|s| !s.is_empty())
        .collect()
}

/// Resolve a dotted key path through a `JsonSchema`, returning the matching sub-schema
/// for the final key. Returns `None` if the path cannot be resolved.
fn resolve_schema_path<'a>(schema: &'a JsonSchema, path: &[String]) -> Option<&'a JsonSchema> {
    let [key, rest @ ..] = path else {
        return None;
    };

    // Look in direct properties
    let found = schema
        .properties
        .as_ref()
        .and_then(|props| props.get(key.as_str()));

    // If not in direct properties, check composition branches
    let found = found.or_else(|| find_in_branches(schema, key));

    let child = found?;

    if rest.is_empty() {
        Some(child)
    } else {
        resolve_schema_path(child, rest)
    }
}

/// Search composition branches (allOf / anyOf / oneOf) for a property key.
fn find_in_branches<'a>(schema: &'a JsonSchema, key: &str) -> Option<&'a JsonSchema> {
    schema
        .all_of
        .iter()
        .flatten()
        .chain(schema.any_of.iter().flatten())
        .chain(schema.one_of.iter().flatten())
        .find_map(|branch| branch.properties.as_ref()?.get(key))
}

/// Format the schema information section appended below the structural hover.
fn format_schema_section(schema: &JsonSchema) -> String {
    let mut md = String::new();

    // Description takes priority over title; skip empty strings
    let text = schema
        .description
        .as_deref()
        .filter(|d| !d.is_empty())
        .or_else(|| schema.title.as_deref().filter(|t| !t.is_empty()));

    if let Some(desc) = text {
        let truncated = truncate_to(desc, MAX_DESCRIPTION_LEN);
        let _ = writeln!(md, "\n**Description:** {truncated}");
    }

    // Schema type
    if let Some(schema_type) = &schema.schema_type {
        let type_str = match schema_type {
            crate::schema::SchemaType::Single(t) => t.clone(),
            crate::schema::SchemaType::Multiple(ts) => ts.join(" | "),
        };
        let _ = writeln!(md, "\n**Schema type:** {type_str}");
    }

    // Default value
    if let Some(default) = &schema.default {
        let _ = writeln!(md, "\n**Default:** {default}");
    }

    // Examples — at most MAX_EXAMPLES, with "and N more" note
    if let Some(examples) = &schema.examples
        && !examples.is_empty()
    {
        let shown = examples.len().min(MAX_EXAMPLES);
        let _ = write!(md, "\n**Examples:**");
        examples.iter().take(shown).for_each(|ex| {
            match ex {
                serde_json::Value::Object(_) | serde_json::Value::Array(_) => {
                    // Pretty-print objects/arrays in a fenced code block.
                    // Fall back to compact inline if pretty form exceeds the limit
                    // (a truncated code block renders incorrectly).
                    if let Ok(pretty) = serde_json::to_string_pretty(ex) {
                        if pretty.chars().count() <= MAX_EXAMPLE_LEN {
                            let _ = write!(md, "\n```json\n{pretty}\n```");
                        } else {
                            let compact = json_value_to_display_string(ex);
                            let truncated = truncate_to(&compact, MAX_EXAMPLE_LEN);
                            let _ = write!(md, "\n- {truncated}");
                        }
                    } else {
                        let truncated =
                            truncate_to(&json_value_to_display_string(ex), MAX_EXAMPLE_LEN);
                        let _ = write!(md, "\n- {truncated}");
                    }
                }
                serde_json::Value::Null
                | serde_json::Value::Bool(_)
                | serde_json::Value::Number(_)
                | serde_json::Value::String(_) => {
                    let truncated = truncate_to(&json_value_to_display_string(ex), MAX_EXAMPLE_LEN);
                    let _ = write!(md, "\n- {truncated}");
                }
            }
        });
        let remaining = examples.len().saturating_sub(shown);
        if remaining > 0 {
            let _ = write!(md, "\n- *and {remaining} more*");
        }
        md.push('\n');
    }

    md
}

/// Convert a `serde_json::Value` to a display string for hover output.
/// Uses `Value::to_string()` which produces the JSON representation.
fn json_value_to_display_string(value: &serde_json::Value) -> String {
    match value {
        serde_json::Value::String(s) => s.clone(),
        serde_json::Value::Null
        | serde_json::Value::Bool(_)
        | serde_json::Value::Number(_)
        | serde_json::Value::Array(_)
        | serde_json::Value::Object(_) => value.to_string(),
    }
}

#[cfg(test)]
#[expect(
    clippy::expect_used,
    clippy::unwrap_used,
    clippy::panic,
    reason = "test code"
)]
mod tests {
    use std::collections::HashMap;

    use rstest::rstest;
    use serde_json::Value as JsonValue;
    use serde_json::json;

    use super::*;
    use crate::schema::{JsonSchema, SchemaType};
    use crate::test_utils::parse_docs;

    fn pos(line: u32, character: u32) -> Position {
        Position::new(line, character)
    }

    fn hover_content(hover: &Hover) -> &str {
        match &hover.contents {
            HoverContents::Markup(m) => &m.value,
            HoverContents::Scalar(_) | HoverContents::Array(_) => panic!("expected MarkupContent"),
        }
    }

    fn schema_with_description(description: &str) -> JsonSchema {
        JsonSchema {
            description: Some(description.to_string()),
            ..Default::default()
        }
    }

    // Tests 1, 5, 6 — hover contains key path and scalar type mention
    #[rstest]
    #[case::simple_key("name: Alice\n", pos(0, 0), "name")]
    #[case::nested_key("server:\n  port: 8080\n", pos(1, 2), "server.port")]
    #[case::deeply_nested_key("a:\n  b:\n    c: deep\n", pos(2, 4), "a.b.c")]
    fn hover_contains_key_path_and_scalar_type(
        #[case] text: &str,
        #[case] cursor: Position,
        #[case] expected_path: &str,
    ) {
        let docs = parse_docs(text);
        let hover = hover_at(&docs, cursor, None).expect("should return hover");
        let content = hover_content(&hover);
        assert!(
            content.contains(expected_path),
            "should contain key path {expected_path:?}, got: {content}"
        );
        assert!(
            content.to_lowercase().contains("scalar"),
            "should mention scalar type, got: {content}"
        );
    }

    // Test 2
    #[test]
    fn should_return_hover_for_simple_value() {
        let text = "name: Alice\n";
        let docs = parse_docs(text);
        let result = hover_at(&docs, pos(0, 6), None);

        let hover = result.expect("should return hover");
        let content = hover_content(&hover);
        assert!(content.contains("name"), "should contain key path 'name'");
        assert!(
            content.to_lowercase().contains("scalar"),
            "should mention scalar type"
        );
        assert!(content.contains("Alice"), "should contain value 'Alice'");
    }

    // Tests 3, 4, 12, 15, 16 — hover returns None for degenerate structural positions
    #[rstest]
    #[case::whitespace("key: value\n\n", pos(1, 0))]
    #[case::comment("# comment\nkey: value\n", pos(0, 2))]
    #[case::empty_document("", pos(0, 0))]
    #[case::position_beyond_document("key: value\n", pos(5, 0))]
    #[case::document_separator_line("key1: value1\n---\nkey2: value2\n", pos(1, 0))]
    fn hover_returns_none_for_structural_cases(#[case] text: &str, #[case] cursor: Position) {
        let docs = parse_docs(text);
        let result = hover_at(&docs, cursor, None);
        assert!(result.is_none(), "expected None but got Some hover");
    }

    // Test 7
    #[test]
    fn should_return_hover_for_sequence_item() {
        let text = "items:\n  - first\n  - second\n";
        let docs = parse_docs(text);
        let result = hover_at(&docs, pos(1, 4), None);

        let hover = result.expect("should return hover");
        let content = hover_content(&hover);
        assert!(
            content.contains("items[0]") || content.contains("items.0"),
            "should contain path like 'items[0]' or 'items.0'"
        );
        assert!(content.contains("first"), "should contain value 'first'");
    }

    // Tests 8, 9 — hover contains key path and compound (mapping/sequence) type mention
    #[rstest]
    #[case::mapping_value_type("server:\n  port: 8080\n", pos(0, 0), "server", "mapping")]
    #[case::sequence_value_type("items:\n  - one\n  - two\n", pos(0, 0), "items", "sequence")]
    fn hover_contains_key_path_and_compound_type(
        #[case] text: &str,
        #[case] cursor: Position,
        #[case] expected_path: &str,
        #[case] expected_type: &str,
    ) {
        let docs = parse_docs(text);
        let hover = hover_at(&docs, cursor, None).expect("should return hover");
        let content = hover_content(&hover);
        assert!(
            content.contains(expected_path),
            "should contain key path {expected_path:?}, got: {content}"
        );
        assert!(
            content.to_lowercase().contains(expected_type),
            "should mention {expected_type:?} type, got: {content}"
        );
    }

    // Test 10
    #[test]
    fn should_return_hover_with_scalar_value() {
        let text = "port: 8080\n";
        let docs = parse_docs(text);
        let result = hover_at(&docs, pos(0, 6), None);

        let hover = result.expect("should return hover");
        let content = hover_content(&hover);
        assert!(content.contains("8080"), "should contain value '8080'");
    }

    // Test 11
    #[test]
    fn should_format_hover_as_markdown() {
        let text = "key: value\n";
        let docs = parse_docs(text);
        let result = hover_at(&docs, pos(0, 0), None);

        let hover = result.expect("should return hover");
        match &hover.contents {
            HoverContents::Markup(m) => {
                assert_eq!(m.kind, MarkupKind::Markdown);
            }
            HoverContents::Scalar(_) | HoverContents::Array(_) => panic!("expected MarkupContent"),
        }
    }

    // Test 13 (adapted) — empty docs slice simulates failed parse
    #[test]
    fn should_return_none_when_document_failed_to_parse() {
        let result = hover_at(&[], pos(0, 0), None);
        assert!(result.is_none());
    }

    // Test 14
    #[test]
    fn should_return_hover_in_multi_document_yaml() {
        let text = "doc1key: value1\n---\ndoc2key: value2\n";
        let docs = parse_docs(text);
        let result = hover_at(&docs, pos(2, 0), None);

        let hover = result.expect("should return hover");
        let content = hover_content(&hover);
        assert!(
            content.contains("doc2key"),
            "should contain key path 'doc2key'"
        );
    }

    // Test 17
    #[test]
    fn should_return_hover_for_boolean_value() {
        let text = "enabled: true\n";
        let docs = parse_docs(text);
        let result = hover_at(&docs, pos(0, 9), None);

        let hover = result.expect("should return hover");
        let content = hover_content(&hover);
        assert!(
            content.to_lowercase().contains("scalar") || content.to_lowercase().contains("boolean"),
            "should mention scalar or boolean type"
        );
        assert!(content.contains("true"), "should contain value 'true'");
    }

    // Test 18
    #[test]
    fn should_return_hover_for_null_value() {
        let text = "empty: ~\n";
        let docs = parse_docs(text);
        let result = hover_at(&docs, pos(0, 7), None);

        let hover = result.expect("should return hover");
        let content = hover_content(&hover);
        assert!(
            content.to_lowercase().contains("scalar") || content.to_lowercase().contains("null"),
            "should mention scalar or null type"
        );
    }

    // ──────────────────────────────────────────────────────────────────────────
    // Group B — Schema info at key position (Tests 19–24)
    // ──────────────────────────────────────────────────────────────────────────

    // Test 19 — schema with description appended below structural hover
    #[test]
    fn schema_description_appended_for_key_at_root() {
        let text = "name: Alice\n";
        let docs = parse_docs(text);
        let mut props = HashMap::new();
        props.insert(
            "name".to_string(),
            schema_with_description("The user's display name"),
        );
        let schema = JsonSchema {
            properties: Some(props),
            ..Default::default()
        };
        let result = hover_at(&docs, pos(0, 0), Some(&schema));

        let hover = result.expect("should return hover");
        let content = hover_content(&hover);
        assert!(content.contains("name"), "should contain key path 'name'");
        assert!(
            content.contains("The user's display name"),
            "should contain schema description"
        );
    }

    // Test 20 — schema type shown in hover
    #[test]
    fn schema_type_shown_for_key() {
        let text = "port: 8080\n";
        let docs = parse_docs(text);
        let mut props = HashMap::new();
        props.insert(
            "port".to_string(),
            JsonSchema {
                schema_type: Some(SchemaType::Single("integer".to_string())),
                ..Default::default()
            },
        );
        let schema = JsonSchema {
            properties: Some(props),
            ..Default::default()
        };
        let result = hover_at(&docs, pos(0, 0), Some(&schema));

        let hover = result.expect("should return hover");
        let content = hover_content(&hover);
        assert!(
            content.contains("integer"),
            "should contain schema type 'integer'"
        );
    }

    // Test 21 — schema default shown in hover
    #[test]
    fn schema_default_shown_for_key() {
        let text = "timeout: 30\n";
        let docs = parse_docs(text);
        let mut props = HashMap::new();
        props.insert(
            "timeout".to_string(),
            JsonSchema {
                default: Some(JsonValue::Number(30.into())),
                ..Default::default()
            },
        );
        let schema = JsonSchema {
            properties: Some(props),
            ..Default::default()
        };
        let result = hover_at(&docs, pos(0, 0), Some(&schema));

        let hover = result.expect("should return hover");
        let content = hover_content(&hover);
        assert!(content.contains("30"), "should contain default value '30'");
        assert!(
            content.to_lowercase().contains("default"),
            "should mention 'default'"
        );
    }

    // Test 22 — schema examples shown in hover (up to 3)
    #[test]
    fn schema_examples_shown_for_key() {
        let text = "name: Alice\n";
        let docs = parse_docs(text);
        let mut props = HashMap::new();
        props.insert(
            "name".to_string(),
            JsonSchema {
                examples: Some(vec![
                    JsonValue::String("Alice".to_string()),
                    JsonValue::String("Bob".to_string()),
                ]),
                ..Default::default()
            },
        );
        let schema = JsonSchema {
            properties: Some(props),
            ..Default::default()
        };
        let result = hover_at(&docs, pos(0, 0), Some(&schema));

        let hover = result.expect("should return hover");
        let content = hover_content(&hover);
        assert!(
            content.to_lowercase().contains("example"),
            "should mention examples"
        );
        assert!(content.contains("Alice"), "should show first example");
        assert!(content.contains("Bob"), "should show second example");
    }

    // Test 23 — no schema info when key not in schema properties
    #[test]
    fn no_schema_info_for_unknown_key() {
        let text = "unknown: value\n";
        let docs = parse_docs(text);
        let mut props = HashMap::new();
        props.insert(
            "known".to_string(),
            schema_with_description("A known property"),
        );
        let schema = JsonSchema {
            properties: Some(props),
            ..Default::default()
        };
        let result = hover_at(&docs, pos(0, 0), Some(&schema));

        // Structural hover still works
        let hover = result.expect("should return hover");
        let content = hover_content(&hover);
        assert!(
            content.contains("unknown"),
            "should contain key path 'unknown'"
        );
        // Schema description not shown for unknown key
        assert!(
            !content.contains("A known property"),
            "should not show description for unknown key"
        );
    }

    // Test 24 — schema info for nested key resolves through properties
    #[test]
    fn schema_description_for_nested_key() {
        let text = "server:\n  port: 8080\n";
        let docs = parse_docs(text);
        let mut port_props = HashMap::new();
        port_props.insert(
            "port".to_string(),
            JsonSchema {
                description: Some("HTTP port number".to_string()),
                schema_type: Some(SchemaType::Single("integer".to_string())),
                ..Default::default()
            },
        );
        let mut root_props = HashMap::new();
        root_props.insert(
            "server".to_string(),
            JsonSchema {
                properties: Some(port_props),
                ..Default::default()
            },
        );
        let schema = JsonSchema {
            properties: Some(root_props),
            ..Default::default()
        };
        let result = hover_at(&docs, pos(1, 2), Some(&schema));

        let hover = result.expect("should return hover");
        let content = hover_content(&hover);
        assert!(
            content.contains("server.port"),
            "should contain nested path"
        );
        assert!(
            content.contains("HTTP port number"),
            "should contain nested schema description"
        );
    }

    // ──────────────────────────────────────────────────────────────────────────
    // Group C — Schema info at value position (Tests 25–26)
    // ──────────────────────────────────────────────────────────────────────────

    // Test 25 — hovering on value shows schema description for the parent key
    #[test]
    fn schema_description_shown_for_value_position() {
        let text = "name: Alice\n";
        let docs = parse_docs(text);
        let mut props = HashMap::new();
        props.insert(
            "name".to_string(),
            schema_with_description("The user's display name"),
        );
        let schema = JsonSchema {
            properties: Some(props),
            ..Default::default()
        };
        let result = hover_at(&docs, pos(0, 6), Some(&schema));

        let hover = result.expect("should return hover");
        let content = hover_content(&hover);
        assert!(
            content.contains("The user's display name"),
            "should show schema description when hovering on value"
        );
    }

    // Test 26 — hovering on value shows schema type for the parent key
    #[test]
    fn schema_type_shown_for_value_position() {
        let text = "port: 8080\n";
        let docs = parse_docs(text);
        let mut props = HashMap::new();
        props.insert(
            "port".to_string(),
            JsonSchema {
                schema_type: Some(SchemaType::Single("integer".to_string())),
                ..Default::default()
            },
        );
        let schema = JsonSchema {
            properties: Some(props),
            ..Default::default()
        };
        let result = hover_at(&docs, pos(0, 6), Some(&schema));

        let hover = result.expect("should return hover");
        let content = hover_content(&hover);
        assert!(
            content.contains("integer"),
            "should show schema type when hovering on value"
        );
    }

    // ──────────────────────────────────────────────────────────────────────────
    // Group D — Formatting and truncation (Tests 27–31)
    // ──────────────────────────────────────────────────────────────────────────

    // Test 27 — existing structural hover section present before schema section
    #[test]
    fn schema_info_appended_below_structural_hover() {
        let text = "name: Alice\n";
        let docs = parse_docs(text);
        let mut props = HashMap::new();
        props.insert(
            "name".to_string(),
            schema_with_description("The user's display name"),
        );
        let schema = JsonSchema {
            properties: Some(props),
            ..Default::default()
        };
        let result = hover_at(&docs, pos(0, 0), Some(&schema));

        let hover = result.expect("should return hover");
        let content = hover_content(&hover);
        let path_pos = content.find("Path").expect("should contain 'Path'");
        let schema_pos = content
            .find("The user's display name")
            .expect("should contain description");
        assert!(
            path_pos < schema_pos,
            "structural hover (Path) should appear before schema info"
        );
    }

    // Test 28 — long description is truncated to ≤200 chars + ellipsis
    #[test]
    fn long_description_truncated() {
        let text = "name: Alice\n";
        let docs = parse_docs(text);
        let long_desc = "A".repeat(500);
        let mut props = HashMap::new();
        props.insert("name".to_string(), schema_with_description(&long_desc));
        let schema = JsonSchema {
            properties: Some(props),
            ..Default::default()
        };
        let result = hover_at(&docs, pos(0, 0), Some(&schema));

        let hover = result.expect("should return hover");
        let content = hover_content(&hover);
        // The full 500-char description must not appear verbatim
        assert!(
            !content.contains(&long_desc),
            "full 500-char description must not appear"
        );
        assert!(
            content.contains('\u{2026}'),
            "truncated description must end with ellipsis"
        );
        // Description body must be ≤199 chars (plus ellipsis = 200)
        let a_run: String = content
            .chars()
            .skip_while(|&c| c != 'A')
            .take_while(|&c| c == 'A')
            .collect();
        assert!(
            a_run.chars().count() <= 199,
            "truncated description body must be ≤199 chars (plus ellipsis = 200), got {}",
            a_run.chars().count()
        );
    }

    // Test 29/30/46 (consolidated) — long example value truncated to ≤100 chars (char-based)
    #[rstest]
    #[case::ascii_200("a".repeat(200), 'a')]
    #[case::unicode_200("é".repeat(200), 'é')]
    fn long_example_value_truncated(#[case] long_example: String, #[case] marker_char: char) {
        let text = "key: v\n";
        let docs = parse_docs(text);
        let mut props = HashMap::new();
        props.insert(
            "key".to_string(),
            JsonSchema {
                examples: Some(vec![JsonValue::String(long_example.clone())]),
                ..Default::default()
            },
        );
        let schema = JsonSchema {
            properties: Some(props),
            ..Default::default()
        };
        let result = hover_at(&docs, pos(0, 0), Some(&schema));

        let hover = result.expect("should return hover");
        let content = hover_content(&hover);
        assert!(
            !content.contains(&long_example),
            "full 200-char example must not appear verbatim"
        );
        assert!(
            content.contains('\u{2026}'),
            "truncated example must end with ellipsis"
        );
        let char_run: String = content
            .chars()
            .skip_while(|&c| c != marker_char)
            .take_while(|&c| c == marker_char)
            .collect();
        assert!(
            char_run.chars().count() <= 100,
            "displayed example must be at most 100 chars (got {})",
            char_run.chars().count()
        );
    }

    // Test 31 — at most 3 examples shown; "and N more" note for overflow
    #[test]
    fn should_show_at_most_3_examples_with_overflow_note() {
        let text = "key: v\n";
        let docs = parse_docs(text);
        let mut props = HashMap::new();
        props.insert(
            "key".to_string(),
            JsonSchema {
                examples: Some(vec![
                    JsonValue::String("a".to_string()),
                    JsonValue::String("b".to_string()),
                    JsonValue::String("c".to_string()),
                    JsonValue::String("d".to_string()),
                    JsonValue::String("e".to_string()),
                ]),
                ..Default::default()
            },
        );
        let schema = JsonSchema {
            properties: Some(props),
            ..Default::default()
        };
        let result = hover_at(&docs, pos(0, 0), Some(&schema));

        let hover = result.expect("should return hover");
        let content = hover_content(&hover);
        // Cap is 3, not 5
        assert!(
            content.contains("and 2 more") || content.contains("2 more"),
            "should show 'and 2 more' note for 5 examples capped at 3, got: {content}"
        );
        // items 4–5 must be absent as standalone example values
        let lines_with_d = content
            .lines()
            .filter(|l| l.trim() == "- d" || l.trim() == "d")
            .count();
        let lines_with_e = content
            .lines()
            .filter(|l| l.trim() == "- e" || l.trim() == "e")
            .count();
        assert_eq!(
            lines_with_d, 0,
            "example 'd' (4th) must not appear as a list item"
        );
        assert_eq!(
            lines_with_e, 0,
            "example 'e' (5th) must not appear as a list item"
        );
    }

    // ──────────────────────────────────────────────────────────────────────────
    // Group E — Nested paths through schema (Tests 32–33)
    // ──────────────────────────────────────────────────────────────────────────

    // Test 32 — schema info for two-level nested key
    #[test]
    fn schema_info_for_two_level_nested_key() {
        let text = "database:\n  host: localhost\n";
        let docs = parse_docs(text);
        let mut db_props = HashMap::new();
        db_props.insert(
            "host".to_string(),
            schema_with_description("Database host address"),
        );
        let mut root_props = HashMap::new();
        root_props.insert(
            "database".to_string(),
            JsonSchema {
                properties: Some(db_props),
                ..Default::default()
            },
        );
        let schema = JsonSchema {
            properties: Some(root_props),
            ..Default::default()
        };
        let result = hover_at(&docs, pos(1, 2), Some(&schema));

        let hover = result.expect("should return hover");
        let content = hover_content(&hover);
        assert!(
            content.contains("database.host"),
            "should contain nested path"
        );
        assert!(
            content.contains("Database host address"),
            "should contain nested schema description"
        );
    }

    // Test 33 — schema info not shown for key two levels deeper than schema has
    #[test]
    fn no_schema_info_for_deeper_than_schema_provides() {
        let text = "a:\n  b:\n    c: deep\n";
        let docs = parse_docs(text);
        // Schema only describes 'a' with no nested properties
        let mut root_props = HashMap::new();
        root_props.insert("a".to_string(), schema_with_description("Top level A"));
        let schema = JsonSchema {
            properties: Some(root_props),
            ..Default::default()
        };
        let result = hover_at(&docs, pos(2, 4), Some(&schema));

        // Structural hover for a.b.c should still work
        let hover = result.expect("structural hover should work");
        let content = hover_content(&hover);
        assert!(content.contains("a.b.c"), "should contain path a.b.c");
        // Schema description for 'a' should NOT appear when on 'c'
        assert!(
            !content.contains("Top level A"),
            "should not show parent description when on nested key"
        );
    }

    // ──────────────────────────────────────────────────────────────────────────
    // Group F — Composition schemas (allOf / anyOf) (Tests 34–35)
    // ──────────────────────────────────────────────────────────────────────────

    // Test 34 — allOf branch: property description found in first matching branch
    #[test]
    fn schema_info_from_all_of_branch() {
        let text = "name: Alice\n";
        let docs = parse_docs(text);
        let mut branch_props = HashMap::new();
        branch_props.insert(
            "name".to_string(),
            schema_with_description("Name from allOf branch"),
        );
        let schema = JsonSchema {
            all_of: Some(vec![JsonSchema {
                properties: Some(branch_props),
                ..Default::default()
            }]),
            ..Default::default()
        };
        let result = hover_at(&docs, pos(0, 0), Some(&schema));

        let hover = result.expect("should return hover");
        let content = hover_content(&hover);
        assert!(
            content.contains("Name from allOf branch"),
            "should find property description from allOf branch"
        );
    }

    // Test 35 — anyOf branch: property description found in first matching branch
    #[test]
    fn schema_info_from_any_of_branch() {
        let text = "name: Alice\n";
        let docs = parse_docs(text);
        let mut branch_props = HashMap::new();
        branch_props.insert(
            "name".to_string(),
            schema_with_description("Name from anyOf branch"),
        );
        let schema = JsonSchema {
            any_of: Some(vec![JsonSchema {
                properties: Some(branch_props),
                ..Default::default()
            }]),
            ..Default::default()
        };
        let result = hover_at(&docs, pos(0, 0), Some(&schema));

        let hover = result.expect("should return hover");
        let content = hover_content(&hover);
        assert!(
            content.contains("Name from anyOf branch"),
            "should find property description from anyOf branch"
        );
    }

    // ──────────────────────────────────────────────────────────────────────────
    // Group G — Fallback behaviour (Tests 36–38)
    // ──────────────────────────────────────────────────────────────────────────

    // Test 36 — None schema: structural hover works, no schema section appended
    #[test]
    fn no_schema_hover_unchanged() {
        let text = "port: 8080\n";
        let docs = parse_docs(text);
        let result = hover_at(&docs, pos(0, 0), None);

        let hover = result.expect("should return hover with None schema");
        let content = hover_content(&hover);
        assert!(
            content.contains("port"),
            "structural hover path must be present"
        );
        assert!(
            !content.contains("---"),
            "no schema section must be appended when schema is None"
        );
    }

    // Test 37 — Schema with no properties for cursor key: structural hover only
    #[test]
    fn schema_without_matching_property_shows_structural_only() {
        let text = "port: 8080\n";
        let docs = parse_docs(text);
        // Schema has description at root but no properties
        let schema = schema_with_description("Root schema description");
        let result = hover_at(&docs, pos(0, 0), Some(&schema));

        let hover = result.expect("should return hover");
        let content = hover_content(&hover);
        assert!(content.contains("port"), "structural hover path present");
        assert!(
            !content.contains("Root schema description"),
            "root description should not appear for a specific key"
        );
    }

    // Test 38 (adapted) — Schema present but empty docs: returns None
    #[test]
    fn schema_present_but_parse_fails_returns_none() {
        let schema = schema_with_description("some desc");
        let result = hover_at(&[], pos(0, 0), Some(&schema));

        assert!(result.is_none(), "should return None when no parsed docs");
    }

    // ──────────────────────────────────────────────────────────────────────────
    // Group H — Edge cases (Tests 39–42)
    // ──────────────────────────────────────────────────────────────────────────

    // Test 39 — empty description string: schema section not shown
    #[test]
    fn empty_description_not_shown() {
        let text = "name: Alice\n";
        let docs = parse_docs(text);
        let mut props = HashMap::new();
        props.insert(
            "name".to_string(),
            JsonSchema {
                description: Some(String::new()),
                ..Default::default()
            },
        );
        let schema = JsonSchema {
            properties: Some(props),
            ..Default::default()
        };
        let result = hover_at(&docs, pos(0, 0), Some(&schema));

        let hover = result.expect("should return hover");
        let content = hover_content(&hover);
        // Should still contain structural hover
        assert!(content.contains("name"), "structural hover present");
        // Schema section should not be added for empty description
        assert!(
            !content.contains("**Description:**"),
            "should not show description section for empty description"
        );
    }

    // Test 40 — title shown when description absent
    #[test]
    fn title_shown_when_description_absent() {
        let text = "name: Alice\n";
        let docs = parse_docs(text);
        let mut props = HashMap::new();
        props.insert(
            "name".to_string(),
            JsonSchema {
                title: Some("User Name".to_string()),
                description: None,
                ..Default::default()
            },
        );
        let schema = JsonSchema {
            properties: Some(props),
            ..Default::default()
        };
        let result = hover_at(&docs, pos(0, 0), Some(&schema));

        let hover = result.expect("should return hover");
        let content = hover_content(&hover);
        assert!(
            content.contains("User Name"),
            "should show title when description is absent"
        );
    }

    // Test 41 — null default value shown
    #[test]
    fn null_default_shown() {
        let text = "name: Alice\n";
        let docs = parse_docs(text);
        let mut props = HashMap::new();
        props.insert(
            "name".to_string(),
            JsonSchema {
                default: Some(JsonValue::Null),
                ..Default::default()
            },
        );
        let schema = JsonSchema {
            properties: Some(props),
            ..Default::default()
        };
        let result = hover_at(&docs, pos(0, 0), Some(&schema));

        let hover = result.expect("should return hover");
        let content = hover_content(&hover);
        assert!(
            content.to_lowercase().contains("null"),
            "should show null default"
        );
        assert!(
            content.to_lowercase().contains("default"),
            "should label the default"
        );
    }

    // Test 42 — title NOT shown when description present (description takes priority)
    #[test]
    fn description_takes_priority_over_title() {
        let text = "name: Alice\n";
        let docs = parse_docs(text);
        let mut props = HashMap::new();
        props.insert(
            "name".to_string(),
            JsonSchema {
                title: Some("User Name".to_string()),
                description: Some("The full display name of the user".to_string()),
                ..Default::default()
            },
        );
        let schema = JsonSchema {
            properties: Some(props),
            ..Default::default()
        };
        let result = hover_at(&docs, pos(0, 0), Some(&schema));

        let hover = result.expect("should return hover");
        let content = hover_content(&hover);
        assert!(
            content.contains("The full display name of the user"),
            "should show description"
        );
        // Title should not appear when description is present
        assert!(
            !content.contains("User Name"),
            "should not show title when description is present"
        );
    }

    // Test 42b — 10 examples: show first 3, note "and 7 more"
    #[test]
    fn should_show_only_first_3_examples_when_10_provided() {
        let text = "key: v\n";
        let docs = parse_docs(text);
        let examples: Vec<JsonValue> = (0..10)
            .map(|i| JsonValue::String(format!("ex{i}")))
            .collect();
        let mut props = HashMap::new();
        props.insert(
            "key".to_string(),
            JsonSchema {
                examples: Some(examples),
                ..Default::default()
            },
        );
        let schema = JsonSchema {
            properties: Some(props),
            ..Default::default()
        };
        let result = hover_at(&docs, pos(0, 0), Some(&schema));

        let hover = result.expect("should return hover");
        let content = hover_content(&hover);
        // First 3 shown; ex3 through ex9 must be absent as list items
        assert!(content.contains("ex0"), "ex0 must appear");
        for i in 3..10 {
            let item = format!("ex{i}");
            let lines_with_item = content
                .lines()
                .filter(|l| l.trim() == format!("- {item}") || l.trim() == item)
                .count();
            assert_eq!(
                lines_with_item, 0,
                "example '{item}' must not appear as a list item"
            );
        }
        // "and 7 more" note expected
        assert!(
            content.contains("7 more"),
            "should contain 'and 7 more' note, got: {content}"
        );
    }

    // ──────────────────────────────────────────────────────────────────────────
    // Security tests (Tests 43–47)
    // ──────────────────────────────────────────────────────────────────────────

    // Test 43 — description truncation is char-based (not byte-based), cap is 200 chars
    #[test]
    fn should_truncate_long_description_in_hover_at_200_chars() {
        let text = "name: Alice\n";
        let docs = parse_docs(text);
        // 300 × 'é' = 600 bytes but 300 chars; truncated at 200 chars (199 body + ellipsis)
        let long_desc: String = "é".repeat(300);
        let mut props = HashMap::new();
        props.insert("name".to_string(), schema_with_description(&long_desc));
        let schema = JsonSchema {
            properties: Some(props),
            ..Default::default()
        };
        let result = hover_at(&docs, pos(0, 0), Some(&schema));

        let hover = result.expect("should return hover");
        let content = hover_content(&hover);
        // Extract the é-run from the content
        let e_run: String = content
            .chars()
            .skip_while(|&c| c != 'é')
            .take_while(|&c| c == 'é')
            .collect();
        assert!(
            e_run.chars().count() <= 199,
            "truncation must use chars not bytes; body must be ≤199 chars (got {})",
            e_run.chars().count()
        );
        assert!(
            content.contains('\u{2026}'),
            "truncated description must end with ellipsis"
        );
    }

    // Test 44 — backtick in schema default value rendered safely
    #[test]
    fn should_escape_backtick_in_schema_default_value() {
        let text = "key: value\n";
        let docs = parse_docs(text);
        let mut props = HashMap::new();
        props.insert(
            "key".to_string(),
            JsonSchema {
                default: Some(JsonValue::String("foo`bar".to_string())),
                ..Default::default()
            },
        );
        let schema = JsonSchema {
            properties: Some(props),
            ..Default::default()
        };
        let result = hover_at(&docs, pos(0, 0), Some(&schema));

        let hover = result.expect("should return hover");
        let content = hover_content(&hover);
        // Must NOT contain a broken code span pattern "`foo`bar`"
        assert!(
            !content.contains("`foo`bar`"),
            "must not contain broken code span '`foo`bar`', got: {content}"
        );
        // Must still render something that includes "foo" (the default appears)
        assert!(
            content.contains("foo"),
            "default value 'foo' must appear somewhere"
        );
    }

    // Test 47 — backtick in YAML value escaped in **Value:** code span
    #[test]
    fn should_escape_backtick_in_yaml_value_display() {
        // YAML value contains a backtick — must be escaped so the code span doesn't break
        let text = "foo: bar`baz\n";
        let docs = parse_docs(text);
        let result = hover_at(&docs, pos(0, 5), None);

        assert!(result.is_some(), "should return hover");
        let hover = result.unwrap();
        let content = hover_content(&hover);
        // The raw markdown must not contain the broken pattern "`bar`baz`"
        assert!(
            !content.contains("`bar`baz`"),
            "must not contain broken code span '`bar`baz`', got: {content}"
        );
        // "bar" must still appear in some form
        assert!(content.contains("bar"), "value 'bar' must appear in hover");
    }

    // Test 48 — no schema section when schema has no info for the hovered key
    #[test]
    fn should_show_structural_only_when_schema_has_no_info_for_hovered_key() {
        let text = "name: Alice\n";
        let docs = parse_docs(text);
        let mut props = HashMap::new();
        props.insert("other".to_string(), schema_with_description("Other"));
        let schema = JsonSchema {
            properties: Some(props),
            ..Default::default()
        };
        let result = hover_at(&docs, pos(0, 0), Some(&schema));

        assert!(result.is_some(), "should return hover");
        let hover = result.unwrap();
        let content = hover_content(&hover);
        // No schema section separator or "Other" description
        assert!(
            !content.contains("---"),
            "should not contain schema section separator"
        );
        assert!(
            !content.contains("Other"),
            "should not show 'Other' description"
        );
    }

    // ──────────────────────────────────────────────────────────────────────────
    // Group I — Previously uncovered paths (Tests 56–65, adapted)
    // ──────────────────────────────────────────────────────────────────────────

    // Test 57 — cursor on sequence item
    #[test]
    fn hover_returns_sequence_value_when_cursor_on_item() {
        let text = "items:\n  - first\n";
        let docs = parse_docs(text);
        let result = hover_at(&docs, pos(1, 4), None);

        let hover = result.expect("should return hover for sequence item");
        let content = hover_content(&hover);
        assert!(
            content.contains("items"),
            "should contain parent key 'items'"
        );
    }

    // Test 59 — plain scalar sequence item (no colon)
    #[test]
    fn hover_on_plain_scalar_line_returns_value_token() {
        let text = "- plainvalue\n";
        let docs = parse_docs(text);
        let result = hover_at(&docs, pos(0, 4), None);

        let hover = result.expect("should return hover for plain scalar in sequence");
        let content = hover_content(&hover);
        assert!(
            content.contains('0') || content.contains("plainvalue"),
            "should contain sequence index or value"
        );
    }

    // Test 60 (strengthened) — key with no value: parser produces null scalar, AST finds it
    #[test]
    fn hover_on_sequence_item_key_with_no_value_returns_hover() {
        let text = "items:\n  - name:\n";
        let docs = parse_docs(text);
        let result = hover_at(&docs, pos(1, 6), None);

        // Parser produces a null scalar for "name:" — AST walk must find it.
        let hover = result.expect("should return hover for key with null value");
        let content = hover_content(&hover);
        assert!(
            content.contains("name") || content.contains("items"),
            "path should reference the key"
        );
    }

    // Test 61 — mapping value token when cursor is on value side
    #[test]
    fn hover_on_value_side_of_mapping_returns_value_token() {
        let text = "status: active\n";
        let docs = parse_docs(text);
        let result = hover_at(&docs, pos(0, 8), None);

        let hover = result.expect("should return hover for value side of mapping");
        let content = hover_content(&hover);
        assert!(
            content.contains("status"),
            "path should contain key 'status'"
        );
        assert!(content.contains("active"), "should contain value 'active'");
    }

    // Tests 58, 65 — hover returns None for degenerate input
    #[rstest]
    #[case::ellipsis_terminator("key: value\n...\n", pos(1, 0))]
    fn hover_returns_none_for_degenerate_input(#[case] text: &str, #[case] cursor: Position) {
        let docs = parse_docs(text);
        let result = hover_at(&docs, cursor, None);
        assert!(result.is_none(), "expected None but got Some hover");
    }

    // Test 62 — key with empty name after colon strip: must not panic
    #[test]
    fn hover_does_not_panic_for_line_starting_with_colon() {
        let text = ": orphan\n";
        let docs = parse_docs(text);
        let _result = hover_at(&docs, pos(0, 0), None);
    }

    // Tests 63, 64 — hover does not panic on sequence item positions
    #[rstest]
    #[case::key_before_colon("people:\n  - name: Alice\n", pos(1, 5))]
    #[case::value_after_colon("people:\n  - name: Alice\n", pos(1, 12))]
    fn hover_does_not_panic_on_sequence_item_positions(
        #[case] text: &str,
        #[case] cursor: Position,
    ) {
        let docs = parse_docs(text);
        let _result = hover_at(&docs, cursor, None);
        // must not panic — AST path resolution may or may not find the node
    }

    // ──────────────────────────────────────────────────────────────────────────
    // Group J — Hover examples formatting (Tests 51–55)
    // ──────────────────────────────────────────────────────────────────────────

    fn schema_with_examples(examples: Vec<JsonValue>) -> JsonSchema {
        let mut props = HashMap::new();
        props.insert(
            "key".to_string(),
            JsonSchema {
                examples: Some(examples),
                ..Default::default()
            },
        );
        JsonSchema {
            properties: Some(props),
            ..Default::default()
        }
    }

    // Test 51 — object example renders as fenced ```json code block
    #[test]
    fn object_example_renders_as_fenced_code_block() {
        let schema = schema_with_examples(vec![json!({"name": "Alice", "age": 30})]);
        let text = "key: v\n";
        let docs = parse_docs(text);
        let result = hover_at(&docs, pos(0, 0), Some(&schema));

        let hover = result.expect("should return hover");
        let content = hover_content(&hover);
        assert!(
            content.contains("```json"),
            "object example should be in a fenced json code block, got: {content}"
        );
        // Pretty-printed: each key on its own line
        assert!(
            content.contains("\"name\": \"Alice\"") || content.contains("\"age\": 30"),
            "object example should be pretty-printed, got: {content}"
        );
    }

    // Test 52 — array example renders as fenced ```json code block
    #[test]
    fn array_example_renders_as_fenced_code_block() {
        let schema = schema_with_examples(vec![json!(["a", "b", "c"])]);
        let text = "key: v\n";
        let docs = parse_docs(text);
        let result = hover_at(&docs, pos(0, 0), Some(&schema));

        let hover = result.expect("should return hover");
        let content = hover_content(&hover);
        assert!(
            content.contains("```json"),
            "array example should be in a fenced json code block, got: {content}"
        );
    }

    // Test 53 — simple value (string, number, bool) uses list-item format, no code block
    #[test]
    fn simple_value_examples_use_list_item_format() {
        let schema = schema_with_examples(vec![json!("hello"), json!(42), json!(true)]);
        let text = "key: v\n";
        let docs = parse_docs(text);
        let result = hover_at(&docs, pos(0, 0), Some(&schema));

        let hover = result.expect("should return hover");
        let content = hover_content(&hover);
        assert!(
            !content.contains("```json"),
            "simple examples must not use code blocks, got: {content}"
        );
        assert!(
            content.contains("- hello"),
            "string example should appear as list item '- hello', got: {content}"
        );
        assert!(
            content.contains("- 42"),
            "number example should appear as list item '- 42', got: {content}"
        );
        assert!(
            content.contains("- true"),
            "bool example should appear as list item '- true', got: {content}"
        );
    }

    // Test 54 — mixed examples: object gets code block, simple gets list item
    #[test]
    fn mixed_examples_dispatch_correctly_per_type() {
        let schema = schema_with_examples(vec![json!({"host": "localhost"}), json!("simple")]);
        let text = "key: v\n";
        let docs = parse_docs(text);
        let result = hover_at(&docs, pos(0, 0), Some(&schema));

        let hover = result.expect("should return hover");
        let content = hover_content(&hover);
        assert!(
            content.contains("```json"),
            "object example should use code block, got: {content}"
        );
        assert!(
            content.contains("- simple"),
            "string example should use list item format, got: {content}"
        );
    }

    // Test 55 — long object exceeding MAX_EXAMPLE_LEN falls back to compact inline
    #[test]
    fn long_object_example_falls_back_to_compact_inline() {
        // Build an object whose pretty-printed form exceeds 100 chars
        let big_value: String = "x".repeat(50);
        let schema = schema_with_examples(vec![json!({
            "field_a": big_value,
            "field_b": "another long value that pushes past the limit"
        })]);
        let text = "key: v\n";
        let docs = parse_docs(text);
        let result = hover_at(&docs, pos(0, 0), Some(&schema));

        let hover = result.expect("should return hover");
        let content = hover_content(&hover);
        // The pretty form exceeds 100 chars, so no code block should appear
        assert!(
            !content.contains("```json"),
            "long object should fall back to compact inline (no code block), got: {content}"
        );
    }

    // ──────────────────────────────────────────────────────────────────────────
    // Group K — AST span walk regression tests (new)
    // ──────────────────────────────────────────────────────────────────────────

    // New test 4 — multi-doc: correct document from span, not --- counting
    #[test]
    fn hover_uses_span_containment_not_line_counting() {
        let text = "a: 1\n---\nb: 2\n";
        let docs = parse_docs(text);
        let result = hover_at(&docs, pos(2, 0), None);

        let hover = result.expect("should return hover for second document");
        let content = hover_content(&hover);
        assert!(
            content.contains('b'),
            "should resolve to second document key 'b', got: {content}"
        );
        assert!(
            !content.contains("**Path:** `a`"),
            "should not resolve to first document key 'a'"
        );
    }

    // New test 7 — empty line between nodes returns None
    #[test]
    fn hover_on_empty_line_between_nodes_returns_none() {
        let text = "a: 1\n\nb: 2\n";
        let docs = parse_docs(text);
        let result = hover_at(&docs, pos(1, 0), None);
        assert!(result.is_none(), "empty line should return None");
    }

    // New test 8 — trailing comment position returns None
    #[test]
    fn hover_on_trailing_comment_returns_none() {
        let text = "key: value  # comment\n";
        let docs = parse_docs(text);
        // col 13 is within "# comment"
        let result = hover_at(&docs, pos(0, 13), None);
        assert!(
            result.is_none(),
            "cursor in comment region should return None"
        );
    }

    // New test 10 — sequence index is 0-based, third item = index 2
    #[test]
    fn hover_on_sequence_item_path_uses_zero_based_index() {
        let text = "items:\n  - first\n  - second\n  - third\n";
        let docs = parse_docs(text);
        let result = hover_at(&docs, pos(3, 4), None);

        let hover = result.expect("should return hover for third item");
        let content = hover_content(&hover);
        assert!(
            content.contains("items[2]") || content.contains("items.2"),
            "third item should have 0-based index 2, got: {content}"
        );
    }

    // New test 11 — second sequence item index
    #[test]
    fn hover_on_second_sequence_item_has_correct_index() {
        let text = "list:\n  - a\n  - b\n";
        let docs = parse_docs(text);
        let result = hover_at(&docs, pos(2, 4), None);

        let hover = result.expect("should return hover for second item");
        let content = hover_content(&hover);
        assert!(
            content.contains("list[1]") || content.contains("list.1"),
            "second item should have index 1, got: {content}"
        );
    }

    // New test 12 — nested mapping value path
    #[test]
    fn hover_on_nested_mapping_value_returns_correct_path() {
        let text = "outer:\n  inner: hello\n";
        let docs = parse_docs(text);
        let result = hover_at(&docs, pos(1, 9), None);

        let hover = result.expect("should return hover for nested value");
        let content = hover_content(&hover);
        assert!(
            content.contains("outer.inner"),
            "should contain nested path 'outer.inner', got: {content}"
        );
        assert!(content.contains("hello"), "should contain value 'hello'");
    }

    // New test 13 — flow mapping: at minimum no panic
    #[test]
    fn hover_on_flow_mapping_key_does_not_panic() {
        let text = "meta: {name: Alice}\n";
        let docs = parse_docs(text);
        // Cursor on "meta" key
        let _result = hover_at(&docs, pos(0, 0), None);
        // Must not panic; result depends on parser span granularity for flow content
    }

    // New test 14 — three-document stream: correct document resolved
    #[test]
    fn hover_returns_correct_document_in_three_doc_stream() {
        let text = "a: 1\n---\nb: 2\n---\nc: 3\n";
        let docs = parse_docs(text);
        let result = hover_at(&docs, pos(4, 0), None);

        let hover = result.expect("should return hover for third document");
        let content = hover_content(&hover);
        assert!(
            content.contains('c'),
            "should resolve to third document key 'c', got: {content}"
        );
    }

    // Span boundary: start is inclusive
    #[test]
    fn hover_at_span_start_is_inclusive() {
        let text = "key: val\n";
        let docs = parse_docs(text);
        // col 5 is the start of "val" (after "key: ")
        let result = hover_at(&docs, pos(0, 5), None);
        assert!(
            result.is_some(),
            "cursor at span start should be included (start-inclusive)"
        );
    }
}