ucm-engine 0.1.18

Transformation engine for the Unified Content Model
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
//! Graph traversal operations for UCM documents.
//!
//! This module provides various traversal algorithms and utilities for
//! navigating the document's block structure, including BFS, DFS,
//! and semantic traversal.

use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet, VecDeque};
use ucm_core::{Block, BlockId, Content, Document, EdgeType};

use crate::error::Result;

/// Direction for navigation operations
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum NavigateDirection {
    /// Navigate to children only
    Down,
    /// Navigate to parent only
    Up,
    /// Navigate both up and down
    Both,
    /// Navigate to siblings
    Siblings,
    /// Breadth-first traversal
    BreadthFirst,
    /// Depth-first traversal
    DepthFirst,
}

/// Output format for traversal results
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum TraversalOutput {
    /// Only return structure (block IDs and relationships)
    StructureOnly,
    /// Return structure and full block content
    #[default]
    StructureAndBlocks,
    /// Return structure with content previews
    StructureWithPreviews,
}

/// Filter criteria for traversal
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct TraversalFilter {
    /// Only include blocks with these semantic roles
    pub include_roles: Vec<String>,
    /// Exclude blocks with these semantic roles
    pub exclude_roles: Vec<String>,
    /// Only include blocks with these tags
    pub include_tags: Vec<String>,
    /// Exclude blocks with these tags
    pub exclude_tags: Vec<String>,
    /// Only include blocks matching content pattern
    pub content_pattern: Option<String>,
    /// Follow edge types (for edge-based traversal)
    pub edge_types: Vec<EdgeType>,
}

/// A node in the traversal result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TraversalNode {
    pub id: BlockId,
    pub depth: usize,
    pub parent_id: Option<BlockId>,
    pub content_preview: Option<String>,
    pub semantic_role: Option<String>,
    pub child_count: usize,
    pub edge_count: usize,
}

/// An edge in the traversal result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TraversalEdge {
    pub source: BlockId,
    pub target: BlockId,
    pub edge_type: EdgeType,
}

/// Summary statistics for a traversal
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct TraversalSummary {
    pub total_nodes: usize,
    pub total_edges: usize,
    pub max_depth: usize,
    pub nodes_by_role: HashMap<String, usize>,
    pub truncated: bool,
    pub truncation_reason: Option<String>,
}

/// Metadata about the traversal operation
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct TraversalMetadata {
    pub start_id: Option<BlockId>,
    pub direction: Option<NavigateDirection>,
    pub max_depth: Option<usize>,
    pub execution_time_ms: Option<u64>,
}

/// Complete traversal result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TraversalResult {
    pub nodes: Vec<TraversalNode>,
    pub edges: Vec<TraversalEdge>,
    pub paths: Vec<Vec<BlockId>>,
    pub summary: TraversalSummary,
    pub metadata: TraversalMetadata,
}

impl TraversalResult {
    pub fn empty() -> Self {
        Self {
            nodes: Vec::new(),
            edges: Vec::new(),
            paths: Vec::new(),
            summary: TraversalSummary::default(),
            metadata: TraversalMetadata::default(),
        }
    }
}

/// Configuration for the traversal engine
#[derive(Debug, Clone)]
pub struct TraversalConfig {
    pub max_depth: usize,
    pub max_nodes: usize,
    pub default_preview_length: usize,
    pub include_orphans: bool,
    pub cache_enabled: bool,
}

impl Default for TraversalConfig {
    fn default() -> Self {
        Self {
            max_depth: 100,
            max_nodes: 10000,
            default_preview_length: 100,
            include_orphans: false,
            cache_enabled: true,
        }
    }
}

/// Graph traversal engine for UCM documents
pub struct TraversalEngine {
    config: TraversalConfig,
}

impl TraversalEngine {
    /// Create a new traversal engine with default configuration
    pub fn new() -> Self {
        Self {
            config: TraversalConfig::default(),
        }
    }

    /// Create a traversal engine with custom configuration
    pub fn with_config(config: TraversalConfig) -> Self {
        Self { config }
    }

    /// Navigate from a starting point in a specific direction
    pub fn navigate(
        &self,
        doc: &Document,
        start_id: Option<BlockId>,
        direction: NavigateDirection,
        depth: Option<usize>,
        filter: Option<TraversalFilter>,
        output: TraversalOutput,
    ) -> Result<TraversalResult> {
        let start = start_id.unwrap_or(doc.root);
        let max_depth = depth
            .unwrap_or(self.config.max_depth)
            .min(self.config.max_depth);
        let filter = filter.unwrap_or_default();

        #[cfg(not(target_arch = "wasm32"))]
        let start_time = std::time::Instant::now();

        let result = match direction {
            NavigateDirection::Down => self.traverse_down(doc, start, max_depth, &filter, output),
            NavigateDirection::Up => self.traverse_up(doc, start, max_depth, &filter, output),
            NavigateDirection::Both => self.traverse_both(doc, start, max_depth, &filter, output),
            NavigateDirection::Siblings => self.traverse_siblings(doc, start, &filter, output),
            NavigateDirection::BreadthFirst => {
                self.traverse_bfs(doc, start, max_depth, &filter, output)
            }
            NavigateDirection::DepthFirst => {
                self.traverse_dfs(doc, start, max_depth, &filter, output)
            }
        }?;

        let mut result = result;
        result.metadata.start_id = Some(start);
        result.metadata.direction = Some(direction);
        result.metadata.max_depth = Some(max_depth);

        #[cfg(not(target_arch = "wasm32"))]
        {
            result.metadata.execution_time_ms = Some(start_time.elapsed().as_millis() as u64);
        }

        Ok(result)
    }

    /// Expand a node to get its immediate children
    pub fn expand(
        &self,
        doc: &Document,
        node_id: &BlockId,
        output: TraversalOutput,
    ) -> Result<TraversalResult> {
        self.navigate(
            doc,
            Some(*node_id),
            NavigateDirection::Down,
            Some(1),
            None,
            output,
        )
    }

    /// Get the path from a node to the root
    pub fn path_to_root(&self, doc: &Document, node_id: &BlockId) -> Result<Vec<BlockId>> {
        let mut path = vec![*node_id];
        let mut current = *node_id;

        while let Some(parent) = doc.parent(&current) {
            path.push(*parent);
            if *parent == doc.root {
                break;
            }
            current = *parent;
        }

        path.reverse();
        Ok(path)
    }

    /// Find all paths between two nodes
    pub fn find_paths(
        &self,
        doc: &Document,
        from: &BlockId,
        to: &BlockId,
        max_paths: usize,
    ) -> Result<Vec<Vec<BlockId>>> {
        let mut paths = Vec::new();
        let mut visited = HashSet::new();
        let mut current_path = vec![*from];

        self.find_paths_recursive(
            doc,
            from,
            to,
            &mut visited,
            &mut current_path,
            &mut paths,
            max_paths,
        )?;

        Ok(paths)
    }

    #[allow(clippy::too_many_arguments)]
    fn find_paths_recursive(
        &self,
        doc: &Document,
        current: &BlockId,
        target: &BlockId,
        visited: &mut HashSet<BlockId>,
        current_path: &mut Vec<BlockId>,
        paths: &mut Vec<Vec<BlockId>>,
        max_paths: usize,
    ) -> Result<()> {
        if paths.len() >= max_paths {
            return Ok(());
        }

        if current == target {
            paths.push(current_path.clone());
            return Ok(());
        }

        visited.insert(*current);

        // Check children
        for child in doc.children(current) {
            if !visited.contains(child) {
                current_path.push(*child);
                self.find_paths_recursive(
                    doc,
                    child,
                    target,
                    visited,
                    current_path,
                    paths,
                    max_paths,
                )?;
                current_path.pop();
            }
        }

        // Check edges
        if let Some(block) = doc.get_block(current) {
            for edge in &block.edges {
                if !visited.contains(&edge.target) {
                    current_path.push(edge.target);
                    self.find_paths_recursive(
                        doc,
                        &edge.target,
                        target,
                        visited,
                        current_path,
                        paths,
                        max_paths,
                    )?;
                    current_path.pop();
                }
            }
        }

        visited.remove(current);
        Ok(())
    }

    /// Traverse downward from a starting node
    fn traverse_down(
        &self,
        doc: &Document,
        start: BlockId,
        max_depth: usize,
        filter: &TraversalFilter,
        output: TraversalOutput,
    ) -> Result<TraversalResult> {
        self.traverse_bfs(doc, start, max_depth, filter, output)
    }

    /// Traverse upward from a starting node
    fn traverse_up(
        &self,
        doc: &Document,
        start: BlockId,
        max_depth: usize,
        filter: &TraversalFilter,
        output: TraversalOutput,
    ) -> Result<TraversalResult> {
        let mut nodes = Vec::new();
        let mut current = start;
        let mut depth = 0;

        while depth <= max_depth {
            if let Some(block) = doc.get_block(&current) {
                if self.matches_filter(block, filter) {
                    nodes.push(self.create_traversal_node(doc, &current, depth, None, output));
                }
            }

            if let Some(parent) = doc.parent(&current) {
                current = *parent;
                depth += 1;
            } else {
                break;
            }
        }

        let summary = TraversalSummary {
            total_nodes: nodes.len(),
            max_depth: depth,
            ..Default::default()
        };

        Ok(TraversalResult {
            nodes,
            edges: Vec::new(),
            paths: Vec::new(),
            summary,
            metadata: TraversalMetadata::default(),
        })
    }

    /// Traverse both up and down from a starting node
    fn traverse_both(
        &self,
        doc: &Document,
        start: BlockId,
        max_depth: usize,
        filter: &TraversalFilter,
        output: TraversalOutput,
    ) -> Result<TraversalResult> {
        let up_result = self.traverse_up(doc, start, max_depth, filter, output)?;
        let down_result = self.traverse_down(doc, start, max_depth, filter, output)?;

        // Merge results, avoiding duplicates
        let mut seen = HashSet::new();
        let mut nodes = Vec::new();

        for node in up_result
            .nodes
            .into_iter()
            .chain(down_result.nodes.into_iter())
        {
            if seen.insert(node.id) {
                nodes.push(node);
            }
        }

        let max_depth = nodes.iter().map(|n| n.depth).max().unwrap_or(0);
        let summary = TraversalSummary {
            total_nodes: nodes.len(),
            max_depth,
            ..Default::default()
        };

        Ok(TraversalResult {
            nodes,
            edges: Vec::new(),
            paths: Vec::new(),
            summary,
            metadata: TraversalMetadata::default(),
        })
    }

    /// Traverse siblings of a node
    fn traverse_siblings(
        &self,
        doc: &Document,
        start: BlockId,
        filter: &TraversalFilter,
        output: TraversalOutput,
    ) -> Result<TraversalResult> {
        let mut nodes = Vec::new();

        if let Some(parent) = doc.parent(&start) {
            for sibling in doc.children(parent) {
                if let Some(block) = doc.get_block(sibling) {
                    if self.matches_filter(block, filter) {
                        nodes.push(self.create_traversal_node(
                            doc,
                            sibling,
                            0,
                            Some(*parent),
                            output,
                        ));
                    }
                }
            }
        }

        let summary = TraversalSummary {
            total_nodes: nodes.len(),
            max_depth: 0,
            ..Default::default()
        };

        Ok(TraversalResult {
            nodes,
            edges: Vec::new(),
            paths: Vec::new(),
            summary,
            metadata: TraversalMetadata::default(),
        })
    }

    /// Breadth-first traversal
    fn traverse_bfs(
        &self,
        doc: &Document,
        start: BlockId,
        max_depth: usize,
        filter: &TraversalFilter,
        output: TraversalOutput,
    ) -> Result<TraversalResult> {
        let mut nodes = Vec::new();
        let mut edges = Vec::new();
        let mut visited = HashSet::new();
        let mut queue = VecDeque::new();
        let mut nodes_by_role: HashMap<String, usize> = HashMap::new();

        queue.push_back((start, None::<BlockId>, 0usize));

        while let Some((node_id, parent_id, depth)) = queue.pop_front() {
            if depth > max_depth || nodes.len() >= self.config.max_nodes {
                break;
            }

            if visited.contains(&node_id) {
                continue;
            }
            visited.insert(node_id);

            if let Some(block) = doc.get_block(&node_id) {
                if self.matches_filter(block, filter) {
                    let node = self.create_traversal_node(doc, &node_id, depth, parent_id, output);

                    if let Some(role) = &node.semantic_role {
                        *nodes_by_role.entry(role.clone()).or_insert(0) += 1;
                    }

                    nodes.push(node);

                    // Collect edges
                    for edge in &block.edges {
                        if filter.edge_types.is_empty()
                            || filter.edge_types.contains(&edge.edge_type)
                        {
                            edges.push(TraversalEdge {
                                source: node_id,
                                target: edge.target,
                                edge_type: edge.edge_type.clone(),
                            });
                        }
                    }
                }

                // Add children to queue
                for child in doc.children(&node_id) {
                    if !visited.contains(child) {
                        queue.push_back((*child, Some(node_id), depth + 1));
                    }
                }
            }
        }

        let max_depth_found = nodes.iter().map(|n| n.depth).max().unwrap_or(0);
        let truncated = nodes.len() >= self.config.max_nodes;

        let summary = TraversalSummary {
            total_nodes: nodes.len(),
            total_edges: edges.len(),
            max_depth: max_depth_found,
            nodes_by_role,
            truncated,
            truncation_reason: if truncated {
                Some(format!(
                    "Max nodes limit ({}) reached",
                    self.config.max_nodes
                ))
            } else {
                None
            },
        };

        Ok(TraversalResult {
            nodes,
            edges,
            paths: Vec::new(),
            summary,
            metadata: TraversalMetadata::default(),
        })
    }

    /// Depth-first traversal
    fn traverse_dfs(
        &self,
        doc: &Document,
        start: BlockId,
        max_depth: usize,
        filter: &TraversalFilter,
        output: TraversalOutput,
    ) -> Result<TraversalResult> {
        let mut nodes = Vec::new();
        let mut edges = Vec::new();
        let mut visited = HashSet::new();
        let mut nodes_by_role: HashMap<String, usize> = HashMap::new();

        self.dfs_recursive(
            doc,
            start,
            None,
            0,
            max_depth,
            filter,
            output,
            &mut visited,
            &mut nodes,
            &mut edges,
            &mut nodes_by_role,
        )?;

        let max_depth_found = nodes.iter().map(|n| n.depth).max().unwrap_or(0);
        let truncated = nodes.len() >= self.config.max_nodes;

        let summary = TraversalSummary {
            total_nodes: nodes.len(),
            total_edges: edges.len(),
            max_depth: max_depth_found,
            nodes_by_role,
            truncated,
            truncation_reason: if truncated {
                Some(format!(
                    "Max nodes limit ({}) reached",
                    self.config.max_nodes
                ))
            } else {
                None
            },
        };

        Ok(TraversalResult {
            nodes,
            edges,
            paths: Vec::new(),
            summary,
            metadata: TraversalMetadata::default(),
        })
    }

    #[allow(clippy::too_many_arguments)]
    fn dfs_recursive(
        &self,
        doc: &Document,
        node_id: BlockId,
        parent_id: Option<BlockId>,
        depth: usize,
        max_depth: usize,
        filter: &TraversalFilter,
        output: TraversalOutput,
        visited: &mut HashSet<BlockId>,
        nodes: &mut Vec<TraversalNode>,
        edges: &mut Vec<TraversalEdge>,
        nodes_by_role: &mut HashMap<String, usize>,
    ) -> Result<()> {
        if depth > max_depth || nodes.len() >= self.config.max_nodes {
            return Ok(());
        }

        if visited.contains(&node_id) {
            return Ok(());
        }
        visited.insert(node_id);

        if let Some(block) = doc.get_block(&node_id) {
            if self.matches_filter(block, filter) {
                let node = self.create_traversal_node(doc, &node_id, depth, parent_id, output);

                if let Some(role) = &node.semantic_role {
                    *nodes_by_role.entry(role.clone()).or_insert(0) += 1;
                }

                nodes.push(node);

                // Collect edges
                for edge in &block.edges {
                    if filter.edge_types.is_empty() || filter.edge_types.contains(&edge.edge_type) {
                        edges.push(TraversalEdge {
                            source: node_id,
                            target: edge.target,
                            edge_type: edge.edge_type.clone(),
                        });
                    }
                }
            }

            // Recurse to children
            for child in doc.children(&node_id) {
                self.dfs_recursive(
                    doc,
                    *child,
                    Some(node_id),
                    depth + 1,
                    max_depth,
                    filter,
                    output,
                    visited,
                    nodes,
                    edges,
                    nodes_by_role,
                )?;
            }
        }

        Ok(())
    }

    /// Check if a block matches the filter criteria
    fn matches_filter(&self, block: &Block, filter: &TraversalFilter) -> bool {
        // Check role inclusion
        if !filter.include_roles.is_empty() {
            let role = block
                .metadata
                .semantic_role
                .as_ref()
                .map(|r| r.category.as_str().to_string())
                .unwrap_or_default();
            if !filter.include_roles.contains(&role) {
                return false;
            }
        }

        // Check role exclusion
        if !filter.exclude_roles.is_empty() {
            let role = block
                .metadata
                .semantic_role
                .as_ref()
                .map(|r| r.category.as_str().to_string())
                .unwrap_or_default();
            if filter.exclude_roles.contains(&role) {
                return false;
            }
        }

        // Check tag inclusion
        if !filter.include_tags.is_empty() {
            let has_tag = filter
                .include_tags
                .iter()
                .any(|t| block.metadata.tags.contains(t));
            if !has_tag {
                return false;
            }
        }

        // Check tag exclusion
        if !filter.exclude_tags.is_empty() {
            let has_excluded = filter
                .exclude_tags
                .iter()
                .any(|t| block.metadata.tags.contains(t));
            if has_excluded {
                return false;
            }
        }

        // Check content pattern
        if let Some(ref pattern) = filter.content_pattern {
            let content_text = self.extract_content_text(&block.content);
            if !content_text
                .to_lowercase()
                .contains(&pattern.to_lowercase())
            {
                return false;
            }
        }

        true
    }

    /// Create a traversal node from a block
    fn create_traversal_node(
        &self,
        doc: &Document,
        block_id: &BlockId,
        depth: usize,
        parent_id: Option<BlockId>,
        output: TraversalOutput,
    ) -> TraversalNode {
        let block = doc.get_block(block_id);
        let children = doc.children(block_id);

        let content_preview = match output {
            TraversalOutput::StructureOnly => None,
            TraversalOutput::StructureWithPreviews | TraversalOutput::StructureAndBlocks => block
                .map(|b| {
                    let text = self.extract_content_text(&b.content);
                    if text.len() > self.config.default_preview_length {
                        format!("{}...", &text[..self.config.default_preview_length])
                    } else {
                        text
                    }
                }),
        };

        let semantic_role = block
            .and_then(|b| b.metadata.semantic_role.as_ref())
            .map(|r| r.category.as_str().to_string());

        let edge_count = block.map(|b| b.edges.len()).unwrap_or(0);

        TraversalNode {
            id: *block_id,
            depth,
            parent_id,
            content_preview,
            semantic_role,
            child_count: children.len(),
            edge_count,
        }
    }

    /// Extract text content from a Content enum
    fn extract_content_text(&self, content: &Content) -> String {
        match content {
            Content::Text(t) => t.text.clone(),
            Content::Code(c) => c.source.clone(),
            Content::Table(t) => format!("Table: {} rows", t.rows.len()),
            Content::Math(m) => m.expression.clone(),
            Content::Media(m) => m.alt_text.clone().unwrap_or_else(|| "Media".to_string()),
            Content::Json { .. } => "JSON data".to_string(),
            Content::Binary { .. } => "Binary data".to_string(),
            Content::Composite { children, .. } => {
                format!("Composite: {} children", children.len())
            }
        }
    }
}

impl Default for TraversalEngine {
    fn default() -> Self {
        Self::new()
    }
}

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

    fn create_test_document() -> Document {
        let mut doc = Document::new(DocumentId::new("test"));
        let root = doc.root;

        // Create a simple hierarchy
        let h1 = Block::new(Content::text("Chapter 1"), Some("heading1"));
        let h1_id = doc.add_block(h1, &root).unwrap();

        let p1 = Block::new(Content::text("Introduction paragraph"), Some("paragraph"));
        doc.add_block(p1, &h1_id).unwrap();

        let h2 = Block::new(Content::text("Section 1.1"), Some("heading2"));
        let h2_id = doc.add_block(h2, &h1_id).unwrap();

        let p2 = Block::new(Content::text("Section content"), Some("paragraph"));
        doc.add_block(p2, &h2_id).unwrap();

        doc
    }

    #[test]
    fn test_bfs_traversal() {
        let doc = create_test_document();
        let engine = TraversalEngine::new();

        let result = engine
            .navigate(
                &doc,
                None,
                NavigateDirection::BreadthFirst,
                Some(10),
                None,
                TraversalOutput::StructureAndBlocks,
            )
            .unwrap();

        assert!(!result.nodes.is_empty());
        assert!(result.summary.total_nodes >= 4);
    }

    #[test]
    fn test_dfs_traversal() {
        let doc = create_test_document();
        let engine = TraversalEngine::new();

        let result = engine
            .navigate(
                &doc,
                None,
                NavigateDirection::DepthFirst,
                Some(10),
                None,
                TraversalOutput::StructureAndBlocks,
            )
            .unwrap();

        assert!(!result.nodes.is_empty());
    }

    #[test]
    fn test_path_to_root() {
        let doc = create_test_document();
        let engine = TraversalEngine::new();

        // Find a leaf node
        let root_children = doc.children(&doc.root);
        if let Some(h1_id) = root_children.first() {
            let h1_children = doc.children(h1_id);
            if let Some(h2_id) = h1_children.iter().find(|id| {
                doc.get_block(id)
                    .and_then(|b| b.metadata.semantic_role.as_ref())
                    .map(|r| r.category.as_str() == "heading2")
                    .unwrap_or(false)
            }) {
                let path = engine.path_to_root(&doc, h2_id).unwrap();
                assert!(path.len() >= 2);
                assert_eq!(path[0], doc.root);
            }
        }
    }

    #[test]
    fn test_filter_by_role() {
        let doc = create_test_document();
        let engine = TraversalEngine::new();

        let filter = TraversalFilter {
            include_roles: vec!["heading1".to_string(), "heading2".to_string()],
            ..Default::default()
        };

        let result = engine
            .navigate(
                &doc,
                None,
                NavigateDirection::BreadthFirst,
                Some(10),
                Some(filter),
                TraversalOutput::StructureAndBlocks,
            )
            .unwrap();

        // Should only include headings
        for node in &result.nodes {
            if let Some(role) = &node.semantic_role {
                assert!(role.starts_with("heading"));
            }
        }
    }

    #[test]
    fn test_expand_node() {
        let doc = create_test_document();
        let engine = TraversalEngine::new();

        let result = engine
            .expand(&doc, &doc.root, TraversalOutput::StructureAndBlocks)
            .unwrap();

        // Should include root and immediate children
        assert!(!result.nodes.is_empty());
    }

    #[test]
    fn test_max_depth_limit() {
        let doc = create_test_document();
        let config = TraversalConfig {
            max_depth: 1,
            ..Default::default()
        };
        let engine = TraversalEngine::with_config(config);

        let result = engine
            .navigate(
                &doc,
                None,
                NavigateDirection::BreadthFirst,
                Some(1),
                None,
                TraversalOutput::StructureAndBlocks,
            )
            .unwrap();

        // All nodes should have depth <= 1
        for node in &result.nodes {
            assert!(node.depth <= 1);
        }
    }
}