seshat-scanner 0.7.1

Tree-sitter parsing and file discovery for Seshat
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
//! Documentation ingestion for the knowledge graph.
//!
//! Parses structured information from documentation files into
//! [`KnowledgeNode`]s that enrich the knowledge graph. Supports:
//!
//! - **Markdown** (`.md`): headings and lists extracted as Fact/Rule nodes
//! - **JSON Schema** (`.json`): data structure definitions extracted as Fact nodes
//! - **OpenAPI** (`.yaml`, `.yml`): endpoint definitions extracted as Fact nodes
//!
//! All documentation-sourced nodes are tagged with `"source": "documentation"`
//! in their `ext_data` field. No NLP or prose-level convention extraction is
//! performed — only structured information is extracted.

use std::path::{Path, PathBuf};

use seshat_core::{BranchId, KnowledgeNature, KnowledgeNode, KnowledgeWeight, NodeId};

use crate::error::ScanError;

/// The type of documentation file being parsed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DocType {
    /// Markdown documentation (`.md`).
    Markdown,
    /// JSON Schema definition (`.json`).
    JsonSchema,
    /// OpenAPI specification (`.yaml` / `.yml`).
    OpenApi,
}

impl DocType {
    /// Detect documentation type from file extension.
    ///
    /// Returns `None` if the extension is not a recognised documentation format.
    pub fn from_extension(ext: &str) -> Option<Self> {
        match ext.to_lowercase().as_str() {
            "md" => Some(Self::Markdown),
            "json" => Some(Self::JsonSchema),
            "yaml" | "yml" => Some(Self::OpenApi),
            _ => None,
        }
    }
}

/// Result of parsing a single documentation file.
#[derive(Debug, Clone)]
pub struct DocumentationResult {
    /// The path to the documentation file (relative to project root).
    pub path: PathBuf,
    /// The type of documentation file.
    pub doc_type: DocType,
    /// Knowledge nodes extracted from this file.
    pub nodes: Vec<KnowledgeNode>,
}

/// Parse a documentation file and extract structured knowledge nodes.
///
/// # Arguments
///
/// * `path` - Relative path from the project root.
/// * `content` - The raw file content as a string.
/// * `branch_id` - The branch identifier for the knowledge graph nodes.
///
/// # Returns
///
/// A [`DocumentationResult`] containing the extracted knowledge nodes, or a
/// [`ScanError::DocumentationError`] if the file cannot be parsed.
pub fn parse_documentation(
    path: &Path,
    content: &str,
    branch_id: &BranchId,
) -> Result<DocumentationResult, ScanError> {
    let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");

    let doc_type = DocType::from_extension(ext).ok_or_else(|| ScanError::DocumentationError {
        path: path.to_path_buf(),
        reason: format!("Unsupported documentation extension: {ext}"),
    })?;

    let nodes = match doc_type {
        DocType::Markdown => parse_markdown(path, content, branch_id),
        DocType::JsonSchema => parse_json_schema(path, content, branch_id)?,
        DocType::OpenApi => parse_openapi(path, content, branch_id)?,
    };

    Ok(DocumentationResult {
        path: path.to_path_buf(),
        doc_type,
        nodes,
    })
}

// ---------------------------------------------------------------------------
// Markdown parsing
// ---------------------------------------------------------------------------

/// Parse Markdown content and extract H1/H2 sections as knowledge nodes.
///
/// Each H1 or H2 heading starts a new section node. Everything between two
/// H1/H2 headings — including H3-H6 sub-headings, list items, and prose —
/// is collected as the section's `content` in `ext_data` rather than
/// generating separate nodes. This prevents a single large Markdown file
/// from producing thousands of noisy nodes in the knowledge graph.
///
/// Files with no H1/H2 headings produce no nodes (prose-only files are
/// intentionally skipped).
fn parse_markdown(path: &Path, content: &str, branch_id: &BranchId) -> Vec<KnowledgeNode> {
    /// Emit a completed section as a [`KnowledgeNode`], if `section` is `Some`.
    fn flush_section(
        counter: &mut i64,
        nodes: &mut Vec<KnowledgeNode>,
        section: Option<(String, u32, Vec<String>)>,
        path: &Path,
        branch_id: &BranchId,
    ) {
        let Some((title, level, body_lines)) = section else {
            return;
        };
        // Trim trailing blank lines from body.
        let body = body_lines
            .iter()
            .map(String::as_str)
            .collect::<Vec<_>>()
            .join("\n")
            .trim_end()
            .to_owned();
        *counter += 1;
        nodes.push(make_doc_node(
            NodeId(*counter),
            branch_id,
            KnowledgeNature::Fact,
            KnowledgeWeight::Info,
            title,
            serde_json::json!({
                "source": "documentation",
                "doc_type": "markdown",
                "file": path.to_string_lossy(),
                "element": "section",
                "level": level,
                "content": body,
            }),
        ));
    }

    let mut nodes = Vec::new();
    let mut node_counter: i64 = 0;

    // Current open section: (heading_text, heading_level, content_lines).
    let mut current: Option<(String, u32, Vec<String>)> = None;

    for line in content.lines() {
        let trimmed = line.trim();

        if let Some(heading) = parse_heading(trimmed) {
            // Only H1 and H2 open new section nodes; H3+ are body content.
            if heading.level <= 2 {
                // Flush the previous section.
                flush_section(
                    &mut node_counter,
                    &mut nodes,
                    current.take(),
                    path,
                    branch_id,
                );
                current = Some((heading.text, heading.level, Vec::new()));
                continue;
            }
        }

        // Everything else (H3+, lists, prose, blank lines) is body content
        // of the current section.
        if let Some((_, _, ref mut body)) = current {
            body.push(line.to_owned());
        }
        // Lines before the first H1/H2 are silently discarded.
    }

    // Flush the final section.
    flush_section(&mut node_counter, &mut nodes, current, path, branch_id);

    nodes
}

/// A parsed Markdown heading.
struct HeadingInfo {
    level: u32,
    text: String,
}

/// Try to parse a line as a Markdown heading (`# Heading`).
fn parse_heading(line: &str) -> Option<HeadingInfo> {
    if !line.starts_with('#') {
        return None;
    }

    let hashes = line.chars().take_while(|&c| c == '#').count() as u32;
    if hashes > 6 {
        return None;
    }

    let rest = &line[hashes as usize..];
    // Must be followed by a space (ATX heading requirement)
    if !rest.starts_with(' ') {
        return None;
    }

    let text = rest.trim().to_string();
    if text.is_empty() {
        return None;
    }

    Some(HeadingInfo {
        level: hashes,
        text,
    })
}

// ---------------------------------------------------------------------------
// JSON Schema parsing
// ---------------------------------------------------------------------------

/// Parse a JSON Schema file and extract data structure definitions.
///
/// Extracts the schema title/description and all property definitions as
/// Fact/Info knowledge nodes.
fn parse_json_schema(
    path: &Path,
    content: &str,
    branch_id: &BranchId,
) -> Result<Vec<KnowledgeNode>, ScanError> {
    let value: serde_json::Value =
        serde_json::from_str(content).map_err(|e| ScanError::DocumentationError {
            path: path.to_path_buf(),
            reason: format!("Invalid JSON: {e}"),
        })?;

    // Verify this looks like a JSON Schema (has "$schema", "type", or "properties")
    let obj = value
        .as_object()
        .ok_or_else(|| ScanError::DocumentationError {
            path: path.to_path_buf(),
            reason: "JSON Schema must be an object".to_string(),
        })?;

    let is_schema = obj.contains_key("$schema")
        || obj.contains_key("properties")
        || (obj.contains_key("type") && obj.contains_key("title"));

    if !is_schema {
        return Ok(Vec::new());
    }

    let mut nodes = Vec::new();
    let mut node_counter: i64 = 0;

    // Extract the root schema definition
    let schema_title = obj
        .get("title")
        .and_then(|v| v.as_str())
        .unwrap_or("Untitled Schema");

    let schema_description = obj
        .get("description")
        .and_then(|v| v.as_str())
        .unwrap_or("");

    let description = if schema_description.is_empty() {
        format!("JSON Schema: {schema_title}")
    } else {
        format!("JSON Schema: {schema_title}{schema_description}")
    };

    node_counter += 1;
    nodes.push(make_doc_node(
        NodeId(node_counter),
        branch_id,
        KnowledgeNature::Fact,
        KnowledgeWeight::Info,
        description,
        serde_json::json!({
            "source": "documentation",
            "doc_type": "json_schema",
            "file": path.to_string_lossy(),
            "element": "schema",
            "schema_title": schema_title,
        }),
    ));

    // Extract properties as individual nodes
    if let Some(properties) = obj.get("properties").and_then(|v| v.as_object()) {
        let required: Vec<&str> = obj
            .get("required")
            .and_then(|v| v.as_array())
            .map(|arr| arr.iter().filter_map(|v| v.as_str()).collect())
            .unwrap_or_default();

        for (prop_name, prop_value) in properties {
            let prop_type = prop_value
                .get("type")
                .and_then(|v| v.as_str())
                .unwrap_or("unknown");
            let prop_desc = prop_value
                .get("description")
                .and_then(|v| v.as_str())
                .unwrap_or("");
            let is_required = required.contains(&prop_name.as_str());

            let desc = if prop_desc.is_empty() {
                format!(
                    "Property: {prop_name} ({prop_type}{})",
                    if is_required { ", required" } else { "" }
                )
            } else {
                format!(
                    "Property: {prop_name} ({prop_type}{}) — {prop_desc}",
                    if is_required { ", required" } else { "" }
                )
            };

            node_counter += 1;
            nodes.push(make_doc_node(
                NodeId(node_counter),
                branch_id,
                KnowledgeNature::Fact,
                KnowledgeWeight::Info,
                desc,
                serde_json::json!({
                    "source": "documentation",
                    "doc_type": "json_schema",
                    "file": path.to_string_lossy(),
                    "element": "property",
                    "schema_title": schema_title,
                    "property_name": prop_name,
                    "property_type": prop_type,
                    "required": is_required,
                }),
            ));
        }
    }

    // Extract definitions/$defs as additional type nodes
    let defs = obj
        .get("definitions")
        .or_else(|| obj.get("$defs"))
        .and_then(|v| v.as_object());

    if let Some(definitions) = defs {
        for (def_name, def_value) in definitions {
            let def_desc = def_value
                .get("description")
                .and_then(|v| v.as_str())
                .unwrap_or("");
            let def_type = def_value
                .get("type")
                .and_then(|v| v.as_str())
                .unwrap_or("object");

            let desc = if def_desc.is_empty() {
                format!("Definition: {def_name} ({def_type})")
            } else {
                format!("Definition: {def_name} ({def_type}) — {def_desc}")
            };

            node_counter += 1;
            nodes.push(make_doc_node(
                NodeId(node_counter),
                branch_id,
                KnowledgeNature::Fact,
                KnowledgeWeight::Info,
                desc,
                serde_json::json!({
                    "source": "documentation",
                    "doc_type": "json_schema",
                    "file": path.to_string_lossy(),
                    "element": "definition",
                    "definition_name": def_name,
                    "definition_type": def_type,
                }),
            ));
        }
    }

    Ok(nodes)
}

// ---------------------------------------------------------------------------
// OpenAPI parsing
// ---------------------------------------------------------------------------

/// Parse an OpenAPI specification and extract endpoint definitions.
///
/// Extracts each path + method combination as a Fact/Info knowledge node.
fn parse_openapi(
    path: &Path,
    content: &str,
    branch_id: &BranchId,
) -> Result<Vec<KnowledgeNode>, ScanError> {
    let value: serde_norway::Value =
        serde_norway::from_str(content).map_err(|e| ScanError::DocumentationError {
            path: path.to_path_buf(),
            reason: format!("Invalid YAML: {e}"),
        })?;

    // Verify this looks like an OpenAPI spec
    let mapping = value
        .as_mapping()
        .ok_or_else(|| ScanError::DocumentationError {
            path: path.to_path_buf(),
            reason: "OpenAPI spec must be a YAML mapping".to_string(),
        })?;

    let has_openapi = mapping.contains_key(yaml_key("openapi"));
    let has_swagger = mapping.contains_key(yaml_key("swagger"));

    if !has_openapi && !has_swagger {
        return Ok(Vec::new());
    }

    let mut nodes = Vec::new();
    let mut node_counter: i64 = 0;

    // Extract API title from info.title
    let api_title = yaml_get_mapping(mapping, "info")
        .and_then(|m| yaml_get_str(m, "title"))
        .unwrap_or("Untitled API");

    let api_version = yaml_get_mapping(mapping, "info")
        .and_then(|m| yaml_get_str(m, "version"))
        .unwrap_or("");

    let api_desc = if api_version.is_empty() {
        format!("API: {api_title}")
    } else {
        format!("API: {api_title} (v{api_version})")
    };

    node_counter += 1;
    nodes.push(make_doc_node(
        NodeId(node_counter),
        branch_id,
        KnowledgeNature::Fact,
        KnowledgeWeight::Info,
        api_desc,
        serde_json::json!({
            "source": "documentation",
            "doc_type": "openapi",
            "file": path.to_string_lossy(),
            "element": "api",
            "api_title": api_title,
            "api_version": api_version,
        }),
    ));

    // Extract paths/endpoints
    if let Some(paths) = yaml_get_mapping(mapping, "paths") {
        let http_methods = [
            "get", "post", "put", "delete", "patch", "options", "head", "trace",
        ];

        for (path_key, path_value) in paths {
            let endpoint_path = match path_key.as_str() {
                Some(p) => p,
                None => continue,
            };

            let methods = match path_value.as_mapping() {
                Some(m) => m,
                None => continue,
            };

            for method_name in &http_methods {
                let method_key = serde_norway::Value::String(method_name.to_string());
                if let Some(method_value) = methods.get(&method_key) {
                    let method_map = method_value.as_mapping();

                    let summary = method_map
                        .and_then(|m| yaml_get_str(m, "summary"))
                        .unwrap_or("");

                    let operation_id = method_map
                        .and_then(|m| yaml_get_str(m, "operationId"))
                        .unwrap_or("");

                    let method_upper = method_name.to_uppercase();
                    let desc = if summary.is_empty() {
                        format!("Endpoint: {method_upper} {endpoint_path}")
                    } else {
                        format!("Endpoint: {method_upper} {endpoint_path}{summary}")
                    };

                    // Extract response codes
                    let response_codes: Vec<String> = method_map
                        .and_then(|m| yaml_get_mapping(m, "responses"))
                        .map(|responses| {
                            responses
                                .keys()
                                .filter_map(|k| k.as_str().map(String::from))
                                .collect()
                        })
                        .unwrap_or_default();

                    // Extract tags
                    let tags: Vec<String> = method_map
                        .and_then(|m| yaml_get_seq(m, "tags"))
                        .map(|seq| {
                            seq.iter()
                                .filter_map(|v| v.as_str().map(String::from))
                                .collect()
                        })
                        .unwrap_or_default();

                    node_counter += 1;
                    nodes.push(make_doc_node(
                        NodeId(node_counter),
                        branch_id,
                        KnowledgeNature::Fact,
                        KnowledgeWeight::Info,
                        desc,
                        serde_json::json!({
                            "source": "documentation",
                            "doc_type": "openapi",
                            "file": path.to_string_lossy(),
                            "element": "endpoint",
                            "api_title": api_title,
                            "path": endpoint_path,
                            "method": method_upper,
                            "operation_id": operation_id,
                            "response_codes": response_codes,
                            "tags": tags,
                        }),
                    ));
                }
            }
        }
    }

    // Extract component schemas (OpenAPI 3.x)
    if let Some(schemas) =
        yaml_get_mapping(mapping, "components").and_then(|m| yaml_get_mapping(m, "schemas"))
    {
        for (schema_key, schema_value) in schemas {
            let schema_name = match schema_key.as_str() {
                Some(n) => n,
                None => continue,
            };

            let schema_map = schema_value.as_mapping();

            let schema_type = schema_map
                .and_then(|m| yaml_get_str(m, "type"))
                .unwrap_or("object");

            let schema_desc = schema_map
                .and_then(|m| yaml_get_str(m, "description"))
                .unwrap_or("");

            let desc = if schema_desc.is_empty() {
                format!("Schema: {schema_name} ({schema_type})")
            } else {
                format!("Schema: {schema_name} ({schema_type}) — {schema_desc}")
            };

            node_counter += 1;
            nodes.push(make_doc_node(
                NodeId(node_counter),
                branch_id,
                KnowledgeNature::Fact,
                KnowledgeWeight::Info,
                desc,
                serde_json::json!({
                    "source": "documentation",
                    "doc_type": "openapi",
                    "file": path.to_string_lossy(),
                    "element": "schema",
                    "api_title": api_title,
                    "schema_name": schema_name,
                    "schema_type": schema_type,
                }),
            ));
        }
    }

    // Extract Swagger 2.0 definitions
    if let Some(definitions) = yaml_get_mapping(mapping, "definitions") {
        for (def_key, def_value) in definitions {
            let def_name = match def_key.as_str() {
                Some(n) => n,
                None => continue,
            };

            let def_map = def_value.as_mapping();

            let def_type = def_map
                .and_then(|m| yaml_get_str(m, "type"))
                .unwrap_or("object");

            let def_desc = def_map
                .and_then(|m| yaml_get_str(m, "description"))
                .unwrap_or("");

            let desc = if def_desc.is_empty() {
                format!("Schema: {def_name} ({def_type})")
            } else {
                format!("Schema: {def_name} ({def_type}) — {def_desc}")
            };

            node_counter += 1;
            nodes.push(make_doc_node(
                NodeId(node_counter),
                branch_id,
                KnowledgeNature::Fact,
                KnowledgeWeight::Info,
                desc,
                serde_json::json!({
                    "source": "documentation",
                    "doc_type": "openapi",
                    "file": path.to_string_lossy(),
                    "element": "schema",
                    "api_title": api_title,
                    "schema_name": def_name,
                    "schema_type": def_type,
                }),
            ));
        }
    }

    Ok(nodes)
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// Create a `serde_norway::Value::String` key for YAML mapping lookups.
fn yaml_key(key: &str) -> serde_norway::Value {
    serde_norway::Value::String(key.to_string())
}

/// Get a string value from a YAML mapping by key.
fn yaml_get_str<'a>(mapping: &'a serde_norway::Mapping, key: &str) -> Option<&'a str> {
    mapping.get(yaml_key(key)).and_then(|v| v.as_str())
}

/// Get a nested mapping from a YAML mapping by key.
fn yaml_get_mapping<'a>(
    mapping: &'a serde_norway::Mapping,
    key: &str,
) -> Option<&'a serde_norway::Mapping> {
    mapping.get(yaml_key(key)).and_then(|v| v.as_mapping())
}

/// Get a nested sequence from a YAML mapping by key.
fn yaml_get_seq<'a>(
    mapping: &'a serde_norway::Mapping,
    key: &str,
) -> Option<&'a serde_norway::Sequence> {
    mapping.get(yaml_key(key)).and_then(|v| v.as_sequence())
}

/// Create a documentation-sourced knowledge node with standard fields.
fn make_doc_node(
    id: NodeId,
    branch_id: &BranchId,
    nature: KnowledgeNature,
    weight: KnowledgeWeight,
    description: String,
    ext_data: serde_json::Value,
) -> KnowledgeNode {
    KnowledgeNode {
        id,
        branch_id: branch_id.clone(),
        nature,
        weight,
        confidence: 1.0,
        adoption_count: 1,
        total_count: 1,
        description,
        ext_data: Some(ext_data),
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    fn branch() -> BranchId {
        BranchId::from("test")
    }

    // -----------------------------------------------------------------------
    // DocType detection
    // -----------------------------------------------------------------------

    #[test]
    fn doc_type_from_extension_markdown() {
        assert_eq!(DocType::from_extension("md"), Some(DocType::Markdown));
    }

    #[test]
    fn doc_type_from_extension_json() {
        assert_eq!(DocType::from_extension("json"), Some(DocType::JsonSchema));
    }

    #[test]
    fn doc_type_from_extension_yaml() {
        assert_eq!(DocType::from_extension("yaml"), Some(DocType::OpenApi));
        assert_eq!(DocType::from_extension("yml"), Some(DocType::OpenApi));
    }

    #[test]
    fn doc_type_from_extension_unknown() {
        assert_eq!(DocType::from_extension("rs"), None);
        assert_eq!(DocType::from_extension("txt"), None);
    }

    #[test]
    fn doc_type_case_insensitive() {
        assert_eq!(DocType::from_extension("MD"), Some(DocType::Markdown));
        assert_eq!(DocType::from_extension("YAML"), Some(DocType::OpenApi));
        assert_eq!(DocType::from_extension("Json"), Some(DocType::JsonSchema));
    }

    // -----------------------------------------------------------------------
    // parse_documentation dispatch
    // -----------------------------------------------------------------------

    #[test]
    fn parse_documentation_unsupported_extension() {
        let result = parse_documentation(Path::new("file.txt"), "content", &branch());
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(matches!(err, ScanError::DocumentationError { .. }));
    }

    #[test]
    fn parse_documentation_routes_to_markdown() {
        // "# Hello\n- item" is one H1 section → one node
        let content = "# Hello\n- item";
        let result = parse_documentation(Path::new("README.md"), content, &branch()).unwrap();
        assert_eq!(result.doc_type, DocType::Markdown);
        assert_eq!(result.nodes.len(), 1);
    }

    #[test]
    fn parse_documentation_routes_to_json_schema() {
        let content = r#"{"$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "title": "Test"}"#;
        let result = parse_documentation(Path::new("schema.json"), content, &branch()).unwrap();
        assert_eq!(result.doc_type, DocType::JsonSchema);
        assert!(!result.nodes.is_empty());
    }

    #[test]
    fn parse_documentation_routes_to_openapi() {
        let content = "openapi: '3.0.0'\ninfo:\n  title: Test\n  version: '1.0'\npaths: {}";
        let result = parse_documentation(Path::new("api.yaml"), content, &branch()).unwrap();
        assert_eq!(result.doc_type, DocType::OpenApi);
        assert!(!result.nodes.is_empty());
    }

    // -----------------------------------------------------------------------
    // Markdown: section-based parsing (H1/H2 = one node, body = content)
    // -----------------------------------------------------------------------

    #[test]
    fn markdown_extracts_h1_h2_as_sections() {
        // H3 (Subsection) must NOT generate its own node — it is body of Section.
        let content = "# Title\n\nSome text\n\n## Section\n\nMore text\n\n### Subsection";
        let nodes = parse_markdown(Path::new("doc.md"), content, &branch());

        assert_eq!(nodes.len(), 2, "only H1 and H2 create nodes");
        assert_eq!(nodes[0].description, "Title");
        assert_eq!(nodes[1].description, "Section");

        // Levels stored in ext_data
        assert_eq!(nodes[0].ext_data.as_ref().unwrap()["level"], 1);
        assert_eq!(nodes[1].ext_data.as_ref().unwrap()["level"], 2);

        // H3 sub-heading is part of Section's content
        let section_content = nodes[1].ext_data.as_ref().unwrap()["content"]
            .as_str()
            .unwrap();
        assert!(
            section_content.contains("### Subsection"),
            "H3 should appear in H2 section content"
        );
    }

    #[test]
    fn markdown_heading_requires_space() {
        let content = "#NoSpace\n# Has Space";
        let nodes = parse_markdown(Path::new("doc.md"), content, &branch());
        assert_eq!(nodes.len(), 1);
        assert_eq!(nodes[0].description, "Has Space");
    }

    #[test]
    fn markdown_heading_max_level() {
        // H6 opens a section; H7 is invalid → treated as body content.
        // But H6 > 2, so it is body too. Only H1/H2 create nodes.
        let content = "# Top\n###### H6 content\n####### H7 content";
        let nodes = parse_markdown(Path::new("doc.md"), content, &branch());
        assert_eq!(nodes.len(), 1);
        assert_eq!(nodes[0].description, "Top");
        let body = nodes[0].ext_data.as_ref().unwrap()["content"]
            .as_str()
            .unwrap();
        assert!(body.contains("H6 content"));
    }

    #[test]
    fn markdown_list_items_are_body_content() {
        // Lists under an H1 must appear in content, not as separate nodes.
        let content = "# Section\n- First item\n- Second item\n* Third item";
        let nodes = parse_markdown(Path::new("doc.md"), content, &branch());

        assert_eq!(nodes.len(), 1, "only one node for the H1 section");
        assert_eq!(nodes[0].description, "Section");

        let body = nodes[0].ext_data.as_ref().unwrap()["content"]
            .as_str()
            .unwrap();
        assert!(body.contains("First item"));
        assert!(body.contains("Second item"));
        assert!(body.contains("Third item"));
    }

    #[test]
    fn markdown_multiple_h2_sections() {
        let content = "# Doc\n\npreamble\n\n## Section A\n- item A\n## Section B\n- item B";
        let nodes = parse_markdown(Path::new("doc.md"), content, &branch());

        // H1 + H2 A + H2 B = 3 nodes
        assert_eq!(nodes.len(), 3);
        assert_eq!(nodes[0].description, "Doc");
        assert_eq!(nodes[1].description, "Section A");
        assert_eq!(nodes[2].description, "Section B");

        let body_a = nodes[1].ext_data.as_ref().unwrap()["content"]
            .as_str()
            .unwrap();
        assert!(body_a.contains("item A"));
        assert!(!body_a.contains("item B"));
    }

    #[test]
    fn markdown_orphan_content_before_first_heading_discarded() {
        // Content before the first H1/H2 produces no node.
        let content = "some preamble\n# First heading\nbody";
        let nodes = parse_markdown(Path::new("doc.md"), content, &branch());
        assert_eq!(nodes.len(), 1);
        assert_eq!(nodes[0].description, "First heading");
    }

    #[test]
    fn markdown_all_nodes_tagged_with_source() {
        let content = "# Heading\n- Item\n## Sub\ntext";
        let nodes = parse_markdown(Path::new("doc.md"), content, &branch());
        for node in &nodes {
            let ext = node.ext_data.as_ref().unwrap();
            assert_eq!(ext["source"], "documentation");
            assert_eq!(ext["doc_type"], "markdown");
            assert_eq!(ext["element"], "section");
        }
    }

    #[test]
    fn markdown_empty_content() {
        let content = "";
        let nodes = parse_markdown(Path::new("empty.md"), content, &branch());
        assert!(nodes.is_empty());
    }

    #[test]
    fn markdown_prose_only_no_structured_content() {
        // No H1/H2 → no nodes.
        let content = "This is just a paragraph.\nWith no headings or lists.";
        let nodes = parse_markdown(Path::new("prose.md"), content, &branch());
        assert!(nodes.is_empty());
    }

    // -----------------------------------------------------------------------
    // JSON Schema: basic
    // -----------------------------------------------------------------------

    #[test]
    fn json_schema_extracts_title_and_properties() {
        let content = r#"{
            "$schema": "http://json-schema.org/draft-07/schema#",
            "title": "User",
            "description": "A user account",
            "type": "object",
            "required": ["id", "email"],
            "properties": {
                "id": {"type": "integer", "description": "Unique identifier"},
                "email": {"type": "string", "description": "Email address"},
                "name": {"type": "string"}
            }
        }"#;

        let nodes = parse_json_schema(Path::new("user.json"), content, &branch()).unwrap();

        // 1 schema node + 3 property nodes
        assert_eq!(nodes.len(), 4);
        assert!(nodes[0].description.contains("User"));
        assert!(nodes[0].description.contains("A user account"));

        // Check properties
        let id_node = nodes.iter().find(|n| n.description.contains("id")).unwrap();
        assert!(id_node.description.contains("integer"));
        assert!(id_node.description.contains("required"));

        let email_node = nodes
            .iter()
            .find(|n| n.description.contains("email"))
            .unwrap();
        assert!(email_node.description.contains("required"));

        let name_node = nodes
            .iter()
            .find(|n| n.description.contains("name") && !n.description.contains("User"))
            .unwrap();
        assert!(!name_node.description.contains("required"));
    }

    #[test]
    fn json_schema_extracts_definitions() {
        let content = r#"{
            "$schema": "http://json-schema.org/draft-07/schema#",
            "title": "API",
            "type": "object",
            "definitions": {
                "Address": {
                    "type": "object",
                    "description": "A postal address"
                },
                "PhoneNumber": {
                    "type": "string"
                }
            }
        }"#;

        let nodes = parse_json_schema(Path::new("api.json"), content, &branch()).unwrap();

        // 1 schema + 2 definitions
        assert_eq!(nodes.len(), 3);

        let addr = nodes
            .iter()
            .find(|n| n.description.contains("Address"))
            .unwrap();
        assert!(addr.description.contains("A postal address"));

        let phone = nodes
            .iter()
            .find(|n| n.description.contains("PhoneNumber"))
            .unwrap();
        assert!(phone.description.contains("string"));
    }

    #[test]
    fn json_schema_extracts_defs_key() {
        let content = r#"{
            "$schema": "https://json-schema.org/draft/2020-12/schema",
            "title": "Modern",
            "type": "object",
            "$defs": {
                "Color": {"type": "string", "description": "A color value"}
            }
        }"#;

        let nodes = parse_json_schema(Path::new("modern.json"), content, &branch()).unwrap();
        assert_eq!(nodes.len(), 2);
        assert!(nodes[1].description.contains("Color"));
    }

    #[test]
    fn json_schema_not_a_schema() {
        let content = r#"{"name": "John", "age": 30}"#;
        let nodes = parse_json_schema(Path::new("data.json"), content, &branch()).unwrap();
        assert!(nodes.is_empty());
    }

    #[test]
    fn json_schema_invalid_json() {
        let result = parse_json_schema(Path::new("bad.json"), "not json", &branch());
        assert!(result.is_err());
    }

    #[test]
    fn json_schema_not_object() {
        let result = parse_json_schema(Path::new("array.json"), "[1,2,3]", &branch());
        assert!(result.is_err());
    }

    #[test]
    fn json_schema_all_nodes_tagged_with_source() {
        let content = r#"{
            "$schema": "http://json-schema.org/draft-07/schema#",
            "title": "T",
            "type": "object",
            "properties": {"x": {"type": "string"}}
        }"#;
        let nodes = parse_json_schema(Path::new("t.json"), content, &branch()).unwrap();
        for node in &nodes {
            let ext = node.ext_data.as_ref().unwrap();
            assert_eq!(ext["source"], "documentation");
            assert_eq!(ext["doc_type"], "json_schema");
        }
    }

    // -----------------------------------------------------------------------
    // OpenAPI: basic
    // -----------------------------------------------------------------------

    #[test]
    fn openapi_extracts_api_info_and_endpoints() {
        let content = r#"
openapi: '3.0.0'
info:
  title: Pet Store
  version: '1.0.0'
paths:
  /pets:
    get:
      summary: List all pets
      operationId: listPets
      tags:
        - pets
      responses:
        '200':
          description: A list of pets
    post:
      summary: Create a pet
      operationId: createPet
      responses:
        '201':
          description: Pet created
  /pets/{petId}:
    get:
      summary: Get a pet by ID
      operationId: showPetById
      responses:
        '200':
          description: A single pet
        '404':
          description: Pet not found
"#;

        let nodes = parse_openapi(Path::new("api.yaml"), content, &branch()).unwrap();

        // 1 API node + 3 endpoint nodes
        assert_eq!(nodes.len(), 4);

        let api_node = &nodes[0];
        assert!(api_node.description.contains("Pet Store"));
        assert!(api_node.description.contains("v1.0.0"));

        // Check endpoints
        let get_pets = nodes
            .iter()
            .find(|n| n.description.contains("GET /pets") && !n.description.contains("{petId}"))
            .unwrap();
        assert!(get_pets.description.contains("List all pets"));

        let post_pets = nodes
            .iter()
            .find(|n| n.description.contains("POST /pets"))
            .unwrap();
        assert!(post_pets.description.contains("Create a pet"));

        let get_pet = nodes
            .iter()
            .find(|n| n.description.contains("GET /pets/{petId}"))
            .unwrap();
        assert!(get_pet.description.contains("Get a pet by ID"));

        // Check ext_data for endpoint
        let ext = get_pets.ext_data.as_ref().unwrap();
        assert_eq!(ext["source"], "documentation");
        assert_eq!(ext["operation_id"], "listPets");
        assert_eq!(ext["tags"], serde_json::json!(["pets"]));
        assert_eq!(ext["response_codes"], serde_json::json!(["200"]));
    }

    #[test]
    fn openapi_extracts_component_schemas() {
        let content = r#"
openapi: '3.0.0'
info:
  title: Test API
  version: '1.0'
paths: {}
components:
  schemas:
    Pet:
      type: object
      description: A pet in the store
    Error:
      type: object
      description: An error response
"#;

        let nodes = parse_openapi(Path::new("api.yml"), content, &branch()).unwrap();

        // 1 API + 2 schemas
        assert_eq!(nodes.len(), 3);

        let pet = nodes
            .iter()
            .find(|n| n.description.contains("Pet"))
            .unwrap();
        assert!(pet.description.contains("A pet in the store"));

        let error = nodes
            .iter()
            .find(|n| n.description.contains("Error"))
            .unwrap();
        assert!(error.description.contains("An error response"));
    }

    #[test]
    fn openapi_swagger_2_definitions() {
        let content = r#"
swagger: '2.0'
info:
  title: Legacy API
  version: '0.1'
paths:
  /users:
    get:
      summary: List users
      responses:
        '200':
          description: OK
definitions:
  User:
    type: object
    description: A user object
"#;

        let nodes = parse_openapi(Path::new("legacy.yaml"), content, &branch()).unwrap();

        // 1 API + 1 endpoint + 1 definition
        assert_eq!(nodes.len(), 3);

        let user = nodes
            .iter()
            .find(|n| n.description.contains("User"))
            .unwrap();
        assert!(user.description.contains("A user object"));
    }

    #[test]
    fn openapi_not_an_api_spec() {
        let content = "name: John\nage: 30";
        let nodes = parse_openapi(Path::new("data.yaml"), content, &branch()).unwrap();
        assert!(nodes.is_empty());
    }

    #[test]
    fn openapi_invalid_yaml() {
        let result = parse_openapi(Path::new("bad.yaml"), "{{invalid yaml", &branch());
        assert!(result.is_err());
    }

    #[test]
    fn openapi_not_mapping() {
        let result = parse_openapi(Path::new("list.yaml"), "- item1\n- item2", &branch());
        assert!(result.is_err());
    }

    #[test]
    fn openapi_all_nodes_tagged_with_source() {
        let content = r#"
openapi: '3.0.0'
info:
  title: T
  version: '1'
paths:
  /x:
    get:
      summary: X
      responses:
        '200':
          description: OK
"#;
        let nodes = parse_openapi(Path::new("api.yaml"), content, &branch()).unwrap();
        for node in &nodes {
            let ext = node.ext_data.as_ref().unwrap();
            assert_eq!(ext["source"], "documentation");
            assert_eq!(ext["doc_type"], "openapi");
        }
    }

    #[test]
    fn openapi_endpoint_without_summary() {
        let content = r#"
openapi: '3.0.0'
info:
  title: Minimal
  version: '1'
paths:
  /health:
    get:
      responses:
        '200':
          description: OK
"#;
        let nodes = parse_openapi(Path::new("api.yaml"), content, &branch()).unwrap();
        let endpoint = nodes
            .iter()
            .find(|n| n.description.contains("GET /health"))
            .unwrap();
        // No summary means just method + path
        assert_eq!(endpoint.description, "Endpoint: GET /health");
    }

    // -----------------------------------------------------------------------
    // Node properties
    // -----------------------------------------------------------------------

    #[test]
    fn all_nodes_are_facts_with_info_weight() {
        let md = "# Title\n- Item";
        let md_nodes = parse_markdown(Path::new("doc.md"), md, &branch());
        for node in &md_nodes {
            assert_eq!(node.nature, KnowledgeNature::Fact);
            assert_eq!(node.weight, KnowledgeWeight::Info);
            assert!((node.confidence - 1.0).abs() < f64::EPSILON);
        }
    }

    #[test]
    fn documentation_result_contains_correct_path() {
        let result = parse_documentation(Path::new("docs/README.md"), "# Hi", &branch()).unwrap();
        assert_eq!(result.path, Path::new("docs/README.md"));
    }
}