oximedia-aaf 0.1.2

Advanced Authoring Format (AAF) support for OxiMedia - SMPTE ST 377-1 compliant
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
//! AAF mob graph traversal utilities
//!
//! Provides a directed-graph model of the AAF mob reference network, with
//! DFS / BFS traversal, cycle detection, depth computation, and statistical
//! summaries.
//!
//! The graph is built from `MobNode` descriptors and explicit edge pairs
//! `(from_mob_id, to_mob_id)`.

use std::collections::{HashMap, HashSet, VecDeque};

// ─── MobType ─────────────────────────────────────────────────────────────────

/// The semantic type of a mob in the AAF reference graph.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum MobType {
    /// Composition mob — top-level editorial sequence.
    Composition,
    /// Master mob — intermediate link between composition and source.
    Master,
    /// Source mob — references essence.
    Source,
    /// File source mob — directly references a file.
    FileSrc,
}

impl MobType {
    /// Human-readable label.
    #[must_use]
    pub const fn label(&self) -> &'static str {
        match self {
            Self::Composition => "Composition",
            Self::Master => "Master",
            Self::Source => "Source",
            Self::FileSrc => "FileSrc",
        }
    }

    /// Returns `true` for leaf (source) mob types.
    #[must_use]
    pub fn is_source(&self) -> bool {
        matches!(self, Self::Source | Self::FileSrc)
    }
}

// ─── MobNode ─────────────────────────────────────────────────────────────────

/// A node in the mob reference graph.
#[derive(Debug, Clone)]
pub struct MobNode {
    /// Unique mob identifier.
    pub mob_id: u64,
    /// Mob type.
    pub mob_type: MobType,
    /// Human-readable mob name.
    pub name: String,
    /// Slot IDs contained by this mob.
    pub slots: Vec<u64>,
}

impl MobNode {
    /// Create a new mob node.
    #[must_use]
    pub fn new(mob_id: u64, mob_type: MobType, name: impl Into<String>) -> Self {
        Self {
            mob_id,
            mob_type,
            name: name.into(),
            slots: Vec::new(),
        }
    }

    /// Add a slot ID to this node.
    pub fn add_slot(&mut self, slot_id: u64) {
        self.slots.push(slot_id);
    }
}

// ─── MobGraph ────────────────────────────────────────────────────────────────

/// Directed graph of mob references.
///
/// - `mobs`: all nodes, indexed by `mob_id`
/// - `edges`: directed edges `from → Vec<to>`
#[derive(Debug)]
pub struct MobGraph {
    /// All mob nodes indexed by `mob_id`.
    pub mobs: HashMap<u64, MobNode>,
    /// Directed edges: `mob_id → [referenced_mob_ids]`.
    pub edges: HashMap<u64, Vec<u64>>,
}

impl MobGraph {
    /// Build a `MobGraph` from a slice of nodes and a slice of directed edges.
    ///
    /// Edges are `(from_mob_id, to_mob_id)` pairs.
    #[must_use]
    pub fn build(mobs: &[MobNode], references: &[(u64, u64)]) -> Self {
        let mob_map: HashMap<u64, MobNode> = mobs.iter().map(|n| (n.mob_id, n.clone())).collect();

        let mut edge_map: HashMap<u64, Vec<u64>> = HashMap::new();
        for (from, to) in references {
            edge_map.entry(*from).or_default().push(*to);
        }

        Self {
            mobs: mob_map,
            edges: edge_map,
        }
    }

    /// Iterator over direct successors of `mob_id`.
    #[must_use]
    pub fn successors(&self, mob_id: u64) -> &[u64] {
        self.edges.get(&mob_id).map(Vec::as_slice).unwrap_or(&[])
    }

    /// Number of nodes in the graph.
    #[must_use]
    pub fn node_count(&self) -> usize {
        self.mobs.len()
    }
}

// ─── Traversal ────────────────────────────────────────────────────────────────

/// Depth-first search traversal starting from `start_id`.
///
/// Returns mob IDs in DFS visit order (pre-order).  Each node is visited at
/// most once, so cycles do not cause infinite loops.
#[must_use]
pub fn traverse_dfs(graph: &MobGraph, start_id: u64) -> Vec<u64> {
    let mut visited: HashSet<u64> = HashSet::new();
    let mut order: Vec<u64> = Vec::new();
    dfs_recursive(graph, start_id, &mut visited, &mut order);
    order
}

fn dfs_recursive(graph: &MobGraph, node_id: u64, visited: &mut HashSet<u64>, order: &mut Vec<u64>) {
    if visited.contains(&node_id) {
        return;
    }
    visited.insert(node_id);
    if graph.mobs.contains_key(&node_id) {
        order.push(node_id);
    }
    for &next in graph.successors(node_id) {
        dfs_recursive(graph, next, visited, order);
    }
}

/// Follow the reference chain from a composition mob and return all reachable
/// leaf (source) mob IDs.
///
/// A mob is considered a source leaf if its `mob_type` is `Source` or `FileSrc`.
#[must_use]
pub fn find_source_clips(graph: &MobGraph, composition_id: u64) -> Vec<u64> {
    let reachable = traverse_dfs(graph, composition_id);
    reachable
        .into_iter()
        .filter(|&id| {
            graph
                .mobs
                .get(&id)
                .map(|n| n.mob_type.is_source())
                .unwrap_or(false)
        })
        .collect()
}

/// Compute the transitive closure of all mobs reachable from `mob_id` via BFS.
///
/// Returns mob IDs in BFS order (level-by-level), excluding the start node.
#[must_use]
pub fn find_all_references(graph: &MobGraph, mob_id: u64) -> Vec<u64> {
    let mut visited: HashSet<u64> = HashSet::new();
    let mut queue = VecDeque::new();
    let mut order: Vec<u64> = Vec::new();

    visited.insert(mob_id);
    queue.push_back(mob_id);

    while let Some(current) = queue.pop_front() {
        for &next in graph.successors(current) {
            if visited.insert(next) {
                order.push(next);
                queue.push_back(next);
            }
        }
    }

    order
}

// ─── Cycle detection ─────────────────────────────────────────────────────────

/// Colour used during DFS cycle detection.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Color {
    /// Node not yet visited.
    White,
    /// Node is on the current DFS stack (in-progress).
    Gray,
    /// Node fully processed.
    Black,
}

/// Detect all simple cycles in the graph using DFS with gray/white/black colouring.
///
/// Returns a list of cycles; each cycle is a `Vec<u64>` of mob IDs forming
/// a closed path (the first element equals the last for readability, but the
/// implementation returns the cycle path without repeating the start node).
#[must_use]
pub fn detect_cycles(graph: &MobGraph) -> Vec<Vec<u64>> {
    let mut color: HashMap<u64, Color> = HashMap::new();
    let mut cycles: Vec<Vec<u64>> = Vec::new();
    let mut stack: Vec<u64> = Vec::new();

    for &start in graph.mobs.keys() {
        if *color.get(&start).unwrap_or(&Color::White) == Color::White {
            dfs_color(graph, start, &mut color, &mut stack, &mut cycles);
        }
    }

    cycles
}

fn dfs_color(
    graph: &MobGraph,
    node: u64,
    color: &mut HashMap<u64, Color>,
    stack: &mut Vec<u64>,
    cycles: &mut Vec<Vec<u64>>,
) {
    color.insert(node, Color::Gray);
    stack.push(node);

    for &next in graph.successors(node) {
        match color.get(&next).copied().unwrap_or(Color::White) {
            Color::White => {
                dfs_color(graph, next, color, stack, cycles);
            }
            Color::Gray => {
                // Back-edge found — extract the cycle
                if let Some(pos) = stack.iter().position(|&id| id == next) {
                    let cycle: Vec<u64> = stack[pos..].to_vec();
                    cycles.push(cycle);
                }
            }
            Color::Black => {}
        }
    }

    stack.pop();
    color.insert(node, Color::Black);
}

// ─── Depth computation ────────────────────────────────────────────────────────

/// Compute BFS-level depth of every reachable node from `root_id`.
///
/// The root node has depth 0.  Returns a map of `mob_id → depth`.
/// Unreachable nodes are not included.
#[must_use]
pub fn compute_mob_depth(graph: &MobGraph, root_id: u64) -> HashMap<u64, usize> {
    let mut depths: HashMap<u64, usize> = HashMap::new();
    let mut queue: VecDeque<(u64, usize)> = VecDeque::new();

    depths.insert(root_id, 0);
    queue.push_back((root_id, 0));

    while let Some((current, depth)) = queue.pop_front() {
        for &next in graph.successors(current) {
            if let std::collections::hash_map::Entry::Vacant(e) = depths.entry(next) {
                e.insert(depth + 1);
                queue.push_back((next, depth + 1));
            }
        }
    }

    depths
}

// ─── Statistics ───────────────────────────────────────────────────────────────

// ─── Topological Sort ─────────────────────────────────────────────────────────

/// Compute a topological ordering of the mob graph.
///
/// Returns `None` if the graph contains a cycle (topological sort is undefined
/// for cyclic graphs).
#[must_use]
pub fn topological_sort(graph: &MobGraph) -> Option<Vec<u64>> {
    let mut in_degree: HashMap<u64, usize> = HashMap::new();
    for &id in graph.mobs.keys() {
        in_degree.entry(id).or_insert(0);
    }
    for successors in graph.edges.values() {
        for &succ in successors {
            *in_degree.entry(succ).or_insert(0) += 1;
        }
    }

    let mut queue: VecDeque<u64> = in_degree
        .iter()
        .filter(|(_, &deg)| deg == 0)
        .map(|(&id, _)| id)
        .collect();

    let mut order = Vec::with_capacity(graph.mobs.len());

    while let Some(node) = queue.pop_front() {
        order.push(node);
        for &succ in graph.successors(node) {
            if let Some(deg) = in_degree.get_mut(&succ) {
                *deg = deg.saturating_sub(1);
                if *deg == 0 {
                    queue.push_back(succ);
                }
            }
        }
    }

    if order.len() == graph.mobs.len() {
        Some(order)
    } else {
        None // cycle detected
    }
}

// ─── Reverse Edges ────────────────────────────────────────────────────────────

/// Compute the reverse edge map: for each mob, which mobs reference it.
#[must_use]
pub fn reverse_edges(graph: &MobGraph) -> HashMap<u64, Vec<u64>> {
    let mut rev: HashMap<u64, Vec<u64>> = HashMap::new();
    for (&from, tos) in &graph.edges {
        for &to in tos {
            rev.entry(to).or_default().push(from);
        }
    }
    rev
}

/// Find all mobs that have no incoming edges (root mobs).
#[must_use]
pub fn find_roots(graph: &MobGraph) -> Vec<u64> {
    let rev = reverse_edges(graph);
    graph
        .mobs
        .keys()
        .filter(|id| {
            rev.get(id)
                .map(|parents| parents.is_empty())
                .unwrap_or(true)
        })
        .copied()
        .collect()
}

/// Find all mobs that have no outgoing edges (leaf mobs).
#[must_use]
pub fn find_leaves(graph: &MobGraph) -> Vec<u64> {
    graph
        .mobs
        .keys()
        .filter(|&id| graph.successors(*id).is_empty())
        .copied()
        .collect()
}

/// Count total edges in the graph.
#[must_use]
pub fn edge_count(graph: &MobGraph) -> usize {
    graph.edges.values().map(|v| v.len()).sum()
}

// ─── Path Finding ─────────────────────────────────────────────────────────────

/// Find a path from `start_id` to `end_id` via DFS.
///
/// Returns `None` if no path exists.
#[must_use]
pub fn find_path(graph: &MobGraph, start_id: u64, end_id: u64) -> Option<Vec<u64>> {
    if start_id == end_id {
        return Some(vec![start_id]);
    }

    let mut visited: HashSet<u64> = HashSet::new();
    let mut path: Vec<u64> = Vec::new();

    if dfs_find_path(graph, start_id, end_id, &mut visited, &mut path) {
        Some(path)
    } else {
        None
    }
}

fn dfs_find_path(
    graph: &MobGraph,
    current: u64,
    target: u64,
    visited: &mut HashSet<u64>,
    path: &mut Vec<u64>,
) -> bool {
    if !visited.insert(current) {
        return false;
    }
    path.push(current);

    if current == target {
        return true;
    }

    for &next in graph.successors(current) {
        if dfs_find_path(graph, next, target, visited, path) {
            return true;
        }
    }

    path.pop();
    false
}

// ─── Statistics ───────────────────────────────────────────────────────────────

/// Aggregate statistics about a mob graph.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MobStatistics {
    /// Total number of mobs in the graph.
    pub total_mobs: usize,
    /// Number of leaf source / file-source mobs.
    pub source_clip_count: usize,
    /// Maximum DFS depth from any composition mob (0 for empty graphs).
    pub max_depth: usize,
    /// Whether the graph contains at least one cycle.
    pub has_cycles: bool,
    /// Number of composition mobs.
    pub composition_count: usize,
    /// Number of master mobs.
    pub master_count: usize,
    /// Total number of directed edges.
    pub total_edges: usize,
    /// Number of root nodes (no incoming edges).
    pub root_count: usize,
    /// Number of leaf nodes (no outgoing edges).
    pub leaf_count: usize,
}

/// Compute aggregate statistics for the entire mob graph.
#[must_use]
pub fn compute_statistics(graph: &MobGraph) -> MobStatistics {
    let total_mobs = graph.mobs.len();

    let source_clip_count = graph
        .mobs
        .values()
        .filter(|n| n.mob_type.is_source())
        .count();

    // Max depth: take the maximum over all composition mob roots
    let max_depth = graph
        .mobs
        .values()
        .filter(|n| n.mob_type == MobType::Composition)
        .map(|n| {
            let depths = compute_mob_depth(graph, n.mob_id);
            depths.values().copied().max().unwrap_or(0)
        })
        .max()
        .unwrap_or(0);

    let has_cycles = !detect_cycles(graph).is_empty();

    let composition_count = graph
        .mobs
        .values()
        .filter(|n| n.mob_type == MobType::Composition)
        .count();

    let master_count = graph
        .mobs
        .values()
        .filter(|n| n.mob_type == MobType::Master)
        .count();

    let total_edges = edge_count(graph);
    let root_count = find_roots(graph).len();
    let leaf_count = find_leaves(graph).len();

    MobStatistics {
        total_mobs,
        source_clip_count,
        max_depth,
        has_cycles,
        composition_count,
        master_count,
        total_edges,
        root_count,
        leaf_count,
    }
}

// ─── Tests ────────────────────────────────────────────────────────────────────

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

    // ── Helper builders ────────────────────────────────────────────────────

    fn comp(id: u64, name: &str) -> MobNode {
        MobNode::new(id, MobType::Composition, name)
    }
    fn master(id: u64, name: &str) -> MobNode {
        MobNode::new(id, MobType::Master, name)
    }
    fn source(id: u64, name: &str) -> MobNode {
        MobNode::new(id, MobType::Source, name)
    }
    fn filesrc(id: u64, name: &str) -> MobNode {
        MobNode::new(id, MobType::FileSrc, name)
    }

    /// Simple 3-level chain: Composition → Master → Source
    fn three_level_graph() -> MobGraph {
        let nodes = vec![comp(1, "C1"), master(2, "M1"), source(3, "S1")];
        let edges = vec![(1, 2), (2, 3)];
        MobGraph::build(&nodes, &edges)
    }

    // ── MobNode tests ─────────────────────────────────────────────────────

    #[test]
    fn test_mob_node_creation() {
        let node = MobNode::new(42, MobType::Composition, "MyComp");
        assert_eq!(node.mob_id, 42);
        assert_eq!(node.mob_type, MobType::Composition);
        assert_eq!(node.name, "MyComp");
        assert!(node.slots.is_empty());
    }

    #[test]
    fn test_mob_node_add_slot() {
        let mut node = MobNode::new(1, MobType::Master, "M");
        node.add_slot(10);
        node.add_slot(20);
        assert_eq!(node.slots, vec![10, 20]);
    }

    #[test]
    fn test_mob_type_label() {
        assert_eq!(MobType::Composition.label(), "Composition");
        assert_eq!(MobType::FileSrc.label(), "FileSrc");
    }

    #[test]
    fn test_mob_type_is_source() {
        assert!(MobType::Source.is_source());
        assert!(MobType::FileSrc.is_source());
        assert!(!MobType::Master.is_source());
        assert!(!MobType::Composition.is_source());
    }

    // ── MobGraph tests ────────────────────────────────────────────────────

    #[test]
    fn test_graph_build_node_count() {
        let g = three_level_graph();
        assert_eq!(g.node_count(), 3);
    }

    #[test]
    fn test_graph_successors() {
        let g = three_level_graph();
        assert_eq!(g.successors(1), &[2]);
        assert_eq!(g.successors(2), &[3]);
        assert!(g.successors(3).is_empty());
    }

    #[test]
    fn test_graph_unknown_node_has_no_successors() {
        let g = three_level_graph();
        assert!(g.successors(999).is_empty());
    }

    // ── DFS traversal ─────────────────────────────────────────────────────

    #[test]
    fn test_dfs_linear_chain() {
        let g = three_level_graph();
        let order = traverse_dfs(&g, 1);
        assert_eq!(order, vec![1, 2, 3]);
    }

    #[test]
    fn test_dfs_from_leaf() {
        let g = three_level_graph();
        let order = traverse_dfs(&g, 3);
        assert_eq!(order, vec![3]);
    }

    #[test]
    fn test_dfs_unknown_start() {
        let g = three_level_graph();
        let order = traverse_dfs(&g, 999);
        assert!(order.is_empty());
    }

    #[test]
    fn test_dfs_branching_graph() {
        let nodes = vec![
            comp(1, "C"),
            master(2, "M"),
            source(3, "S1"),
            source(4, "S2"),
        ];
        let edges = vec![(1, 2), (2, 3), (2, 4)];
        let g = MobGraph::build(&nodes, &edges);
        let order = traverse_dfs(&g, 1);
        assert!(order.contains(&1));
        assert!(order.contains(&3));
        assert!(order.contains(&4));
        assert_eq!(order.len(), 4);
    }

    #[test]
    fn test_dfs_no_revisit_with_shared_target() {
        let nodes = vec![comp(1, "C1"), comp(2, "C2"), master(3, "M")];
        let edges = vec![(1, 3), (2, 3)];
        let g = MobGraph::build(&nodes, &edges);
        let order = traverse_dfs(&g, 1);
        // Node 3 should appear exactly once
        assert_eq!(order.iter().filter(|&&id| id == 3).count(), 1);
    }

    // ── find_source_clips ─────────────────────────────────────────────────

    #[test]
    fn test_find_source_clips_basic() {
        let g = three_level_graph();
        let sources = find_source_clips(&g, 1);
        assert_eq!(sources, vec![3]);
    }

    #[test]
    fn test_find_source_clips_multiple() {
        let nodes = vec![
            comp(1, "C"),
            master(2, "M1"),
            master(3, "M2"),
            filesrc(4, "F1"),
            source(5, "S1"),
        ];
        let edges = vec![(1, 2), (1, 3), (2, 4), (3, 5)];
        let g = MobGraph::build(&nodes, &edges);
        let mut sources = find_source_clips(&g, 1);
        sources.sort_unstable();
        assert_eq!(sources, vec![4, 5]);
    }

    #[test]
    fn test_find_source_clips_none_for_master_root() {
        let nodes = vec![master(1, "M"), master(2, "M2")];
        let edges = vec![(1, 2)];
        let g = MobGraph::build(&nodes, &edges);
        let sources = find_source_clips(&g, 1);
        assert!(sources.is_empty());
    }

    // ── find_all_references ───────────────────────────────────────────────

    #[test]
    fn test_find_all_references_linear() {
        let g = three_level_graph();
        let refs = find_all_references(&g, 1);
        assert_eq!(refs, vec![2, 3]);
    }

    #[test]
    fn test_find_all_references_no_children() {
        let g = three_level_graph();
        let refs = find_all_references(&g, 3);
        assert!(refs.is_empty());
    }

    #[test]
    fn test_find_all_references_excludes_start() {
        let g = three_level_graph();
        let refs = find_all_references(&g, 1);
        assert!(!refs.contains(&1));
    }

    // ── Cycle detection ───────────────────────────────────────────────────

    #[test]
    fn test_no_cycles_in_acyclic_graph() {
        let g = three_level_graph();
        let cycles = detect_cycles(&g);
        assert!(cycles.is_empty(), "Expected no cycles, got: {cycles:?}");
    }

    #[test]
    fn test_detects_simple_cycle() {
        let nodes = vec![comp(1, "A"), master(2, "B")];
        let edges = vec![(1, 2), (2, 1)];
        let g = MobGraph::build(&nodes, &edges);
        let cycles = detect_cycles(&g);
        assert!(!cycles.is_empty(), "Should detect cycle A→B→A");
    }

    #[test]
    fn test_detects_self_loop() {
        let nodes = vec![comp(1, "Self")];
        let edges = vec![(1, 1)];
        let g = MobGraph::build(&nodes, &edges);
        let cycles = detect_cycles(&g);
        assert!(!cycles.is_empty(), "Self-loop should be a cycle");
    }

    #[test]
    fn test_no_cycle_detected_for_shared_child() {
        // Diamond: C→M1, C→M2, M1→S, M2→S (no cycle)
        let nodes = vec![
            comp(1, "C"),
            master(2, "M1"),
            master(3, "M2"),
            source(4, "S"),
        ];
        let edges = vec![(1, 2), (1, 3), (2, 4), (3, 4)];
        let g = MobGraph::build(&nodes, &edges);
        let cycles = detect_cycles(&g);
        assert!(cycles.is_empty(), "Diamond graph has no cycles");
    }

    // ── compute_mob_depth ─────────────────────────────────────────────────

    #[test]
    fn test_depth_linear_chain() {
        let g = three_level_graph();
        let depths = compute_mob_depth(&g, 1);
        assert_eq!(depths[&1], 0);
        assert_eq!(depths[&2], 1);
        assert_eq!(depths[&3], 2);
    }

    #[test]
    fn test_depth_root_only() {
        let g = three_level_graph();
        let depths = compute_mob_depth(&g, 3);
        assert_eq!(depths[&3], 0);
        assert_eq!(depths.len(), 1);
    }

    #[test]
    fn test_depth_branching() {
        let nodes = vec![
            comp(1, "C"),
            master(2, "M"),
            source(3, "S1"),
            source(4, "S2"),
        ];
        let edges = vec![(1, 2), (2, 3), (2, 4)];
        let g = MobGraph::build(&nodes, &edges);
        let depths = compute_mob_depth(&g, 1);
        assert_eq!(depths[&1], 0);
        assert_eq!(depths[&2], 1);
        assert_eq!(depths[&3], 2);
        assert_eq!(depths[&4], 2);
    }

    #[test]
    fn test_depth_unreachable_nodes_excluded() {
        let nodes = vec![comp(1, "C"), master(2, "M"), source(99, "Isolated")];
        let edges = vec![(1, 2)];
        let g = MobGraph::build(&nodes, &edges);
        let depths = compute_mob_depth(&g, 1);
        assert!(
            !depths.contains_key(&99),
            "Unreachable node should not appear"
        );
    }

    // ── compute_statistics ────────────────────────────────────────────────

    #[test]
    fn test_statistics_basic() {
        let g = three_level_graph();
        let stats = compute_statistics(&g);
        assert_eq!(stats.total_mobs, 3);
        assert_eq!(stats.source_clip_count, 1);
        assert_eq!(stats.max_depth, 2);
        assert!(!stats.has_cycles);
    }

    #[test]
    fn test_statistics_empty_graph() {
        let g = MobGraph::build(&[], &[]);
        let stats = compute_statistics(&g);
        assert_eq!(stats.total_mobs, 0);
        assert_eq!(stats.source_clip_count, 0);
        assert_eq!(stats.max_depth, 0);
        assert!(!stats.has_cycles);
    }

    #[test]
    fn test_statistics_with_cycle() {
        let nodes = vec![comp(1, "A"), master(2, "B")];
        let edges = vec![(1, 2), (2, 1)];
        let g = MobGraph::build(&nodes, &edges);
        let stats = compute_statistics(&g);
        assert!(stats.has_cycles);
    }

    #[test]
    fn test_statistics_multiple_sources() {
        let nodes = vec![
            comp(1, "C"),
            master(2, "M"),
            source(3, "S1"),
            filesrc(4, "F1"),
            filesrc(5, "F2"),
        ];
        let edges = vec![(1, 2), (2, 3), (2, 4), (2, 5)];
        let g = MobGraph::build(&nodes, &edges);
        let stats = compute_statistics(&g);
        assert_eq!(stats.source_clip_count, 3);
        assert_eq!(stats.max_depth, 2);
        assert!(!stats.has_cycles);
        assert_eq!(stats.composition_count, 1);
        assert_eq!(stats.master_count, 1);
        assert_eq!(stats.total_edges, 4);
    }

    // ── Topological sort ────────────────────────────────────────────────

    #[test]
    fn test_topological_sort_linear() {
        let g = three_level_graph();
        let order = topological_sort(&g);
        assert!(order.is_some());
        let order = order.expect("topo sort");
        // Node 1 must appear before 2, and 2 before 3
        let pos1 = order.iter().position(|&x| x == 1).expect("1");
        let pos2 = order.iter().position(|&x| x == 2).expect("2");
        let pos3 = order.iter().position(|&x| x == 3).expect("3");
        assert!(pos1 < pos2);
        assert!(pos2 < pos3);
    }

    #[test]
    fn test_topological_sort_with_cycle() {
        let nodes = vec![comp(1, "A"), master(2, "B")];
        let edges = vec![(1, 2), (2, 1)];
        let g = MobGraph::build(&nodes, &edges);
        assert!(topological_sort(&g).is_none());
    }

    #[test]
    fn test_topological_sort_empty() {
        let g = MobGraph::build(&[], &[]);
        let order = topological_sort(&g);
        assert!(order.is_some());
        assert!(order.expect("empty").is_empty());
    }

    // ── Reverse edges / roots / leaves ──────────────────────────────────

    #[test]
    fn test_reverse_edges() {
        let g = three_level_graph();
        let rev = reverse_edges(&g);
        assert!(rev.get(&2).map(|v| v.contains(&1)).unwrap_or(false));
        assert!(rev.get(&3).map(|v| v.contains(&2)).unwrap_or(false));
    }

    #[test]
    fn test_find_roots() {
        let g = three_level_graph();
        let roots = find_roots(&g);
        assert_eq!(roots, vec![1]);
    }

    #[test]
    fn test_find_leaves() {
        let g = three_level_graph();
        let mut leaves = find_leaves(&g);
        leaves.sort_unstable();
        assert_eq!(leaves, vec![3]);
    }

    #[test]
    fn test_find_roots_multiple() {
        let nodes = vec![comp(1, "C1"), comp(2, "C2"), source(3, "S")];
        let edges = vec![(1, 3), (2, 3)];
        let g = MobGraph::build(&nodes, &edges);
        let mut roots = find_roots(&g);
        roots.sort_unstable();
        assert_eq!(roots, vec![1, 2]);
    }

    #[test]
    fn test_find_leaves_multiple() {
        let nodes = vec![comp(1, "C"), source(2, "S1"), source(3, "S2")];
        let edges = vec![(1, 2), (1, 3)];
        let g = MobGraph::build(&nodes, &edges);
        let mut leaves = find_leaves(&g);
        leaves.sort_unstable();
        assert_eq!(leaves, vec![2, 3]);
    }

    #[test]
    fn test_edge_count() {
        let g = three_level_graph();
        assert_eq!(edge_count(&g), 2);
    }

    // ── Path finding ────────────────────────────────────────────────────

    #[test]
    fn test_find_path_exists() {
        let g = three_level_graph();
        let path = find_path(&g, 1, 3);
        assert!(path.is_some());
        let path = path.expect("path");
        assert_eq!(path.first(), Some(&1));
        assert_eq!(path.last(), Some(&3));
    }

    #[test]
    fn test_find_path_self() {
        let g = three_level_graph();
        let path = find_path(&g, 2, 2);
        assert_eq!(path, Some(vec![2]));
    }

    #[test]
    fn test_find_path_no_path() {
        let g = three_level_graph();
        let path = find_path(&g, 3, 1); // reverse direction
        assert!(path.is_none());
    }

    #[test]
    fn test_find_path_branching() {
        let nodes = vec![
            comp(1, "C"),
            master(2, "M1"),
            master(3, "M2"),
            source(4, "S"),
        ];
        let edges = vec![(1, 2), (1, 3), (3, 4)];
        let g = MobGraph::build(&nodes, &edges);
        let path = find_path(&g, 1, 4);
        assert!(path.is_some());
        let path = path.expect("path to 4");
        assert_eq!(path.first(), Some(&1));
        assert_eq!(path.last(), Some(&4));
    }

    // ── Statistics extended ─────────────────────────────────────────────

    #[test]
    fn test_statistics_root_and_leaf_counts() {
        let g = three_level_graph();
        let stats = compute_statistics(&g);
        assert_eq!(stats.root_count, 1);
        assert_eq!(stats.leaf_count, 1);
    }

    #[test]
    fn test_statistics_composition_and_master_counts() {
        let nodes = vec![
            comp(1, "C1"),
            comp(2, "C2"),
            master(3, "M1"),
            master(4, "M2"),
            source(5, "S"),
        ];
        let edges = vec![(1, 3), (2, 4), (3, 5), (4, 5)];
        let g = MobGraph::build(&nodes, &edges);
        let stats = compute_statistics(&g);
        assert_eq!(stats.composition_count, 2);
        assert_eq!(stats.master_count, 2);
        assert_eq!(stats.total_edges, 4);
        assert_eq!(stats.root_count, 2);
        assert_eq!(stats.leaf_count, 1);
    }
}