Skip to main content

sqry_core/visualization/
unified.rs

1//! Unified graph visualization exporters.
2//!
3//! This module provides visualization exporters that work directly with
4//! [`GraphSnapshot`](crate::graph::unified::concurrent::GraphSnapshot) from the unified graph architecture, replacing the
5//! legacy exporters that operated on the pre-unified graph.
6//!
7//! #
8//!
9//! These exporters are the migration target for the legacy visualization modules.
10//! They provide the same functionality but use the unified graph's efficient
11//! Arena+CSR storage instead of DashMap iteration.
12//!
13//! # Available Exporters
14//!
15//! - [`UnifiedDotExporter`](crate::visualization::unified::UnifiedDotExporter): Graphviz DOT format
16//! - [`UnifiedD2Exporter`](crate::visualization::unified::UnifiedD2Exporter): D2 diagram format
17//! - [`UnifiedJsonExporter`](crate::visualization::unified::UnifiedJsonExporter): JSON format for web visualizations
18//! - [`UnifiedMermaidExporter`](crate::visualization::unified::UnifiedMermaidExporter): Mermaid format for Markdown
19//!
20//! # Example
21//!
22//! ```rust,ignore
23//! use sqry_core::graph::unified::concurrent::GraphSnapshot;
24//! use sqry_core::visualization::unified::{UnifiedDotExporter, DotConfig};
25//!
26//! let snapshot: GraphSnapshot = /* ... */;
27//! let config = DotConfig::default()
28//!     .with_cross_language_highlight(true)
29//!     .with_details(true);
30//! let exporter = UnifiedDotExporter::new(&snapshot, config);
31//! let dot_output = exporter.export();
32//! ```
33
34use std::collections::{HashMap, HashSet, VecDeque};
35use std::fmt::Write;
36
37use crate::graph::node::Language;
38use crate::graph::unified::concurrent::GraphSnapshot;
39use crate::graph::unified::edge::EdgeKind;
40#[cfg(test)]
41use crate::graph::unified::edge::ResolvedVia;
42use crate::graph::unified::node::NodeId;
43use crate::graph::unified::node::kind::NodeKind;
44use crate::graph::unified::storage::arena::NodeEntry;
45
46// ============================================================================
47// Common Types
48// ============================================================================
49
50/// Graph layout direction for visualization.
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
52pub enum Direction {
53    /// Left to right (default)
54    #[default]
55    LeftToRight,
56    /// Top to bottom
57    TopToBottom,
58}
59
60impl Direction {
61    /// Returns the direction as a string for DOT/D2.
62    #[must_use]
63    pub const fn as_str(self) -> &'static str {
64        match self {
65            Self::LeftToRight => "LR",
66            Self::TopToBottom => "TB",
67        }
68    }
69}
70
71/// Edge kind filter for filtering edges by type.
72#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
73pub enum EdgeFilter {
74    /// Call edges
75    Calls,
76    /// Import edges
77    Imports,
78    /// Export edges
79    Exports,
80    /// Reference edges
81    References,
82    /// Inheritance edges
83    Inherits,
84    /// Implementation edges
85    Implements,
86    /// FFI call edges
87    FfiCall,
88    /// HTTP request edges
89    HttpRequest,
90    /// Database query edges
91    DbQuery,
92}
93
94impl EdgeFilter {
95    /// Check if an `EdgeKind` matches this filter.
96    #[must_use]
97    pub fn matches(&self, kind: &EdgeKind) -> bool {
98        matches!(
99            (self, kind),
100            (EdgeFilter::Calls, EdgeKind::Calls { .. })
101                | (EdgeFilter::Imports, EdgeKind::Imports { .. })
102                | (EdgeFilter::Exports, EdgeKind::Exports { .. })
103                | (EdgeFilter::References, EdgeKind::References)
104                | (EdgeFilter::Inherits, EdgeKind::Inherits)
105                | (EdgeFilter::Implements, EdgeKind::Implements)
106                | (EdgeFilter::FfiCall, EdgeKind::FfiCall { .. })
107                | (EdgeFilter::HttpRequest, EdgeKind::HttpRequest { .. })
108                | (EdgeFilter::DbQuery, EdgeKind::DbQuery { .. })
109        )
110    }
111}
112
113// ============================================================================
114// Utility Functions
115// ============================================================================
116
117/// Get color for a language.
118#[must_use]
119pub fn language_color(lang: Language) -> &'static str {
120    match lang {
121        Language::Rust => "#dea584",
122        Language::JavaScript => "#f7df1e",
123        Language::TypeScript => "#3178c6",
124        Language::Python => "#3572A5",
125        Language::Go => "#00ADD8",
126        Language::Java => "#b07219",
127        Language::Ruby => "#701516",
128        Language::Php => "#4F5D95",
129        Language::Cpp => "#f34b7d",
130        Language::C => "#555555",
131        Language::Swift => "#F05138",
132        Language::Kotlin => "#A97BFF",
133        Language::Scala => "#c22d40",
134        Language::Sql | Language::Plsql => "#e38c00",
135        Language::Shell => "#89e051",
136        Language::Lua => "#000080",
137        Language::Perl => "#0298c3",
138        Language::Dart => "#00B4AB",
139        Language::Groovy => "#4298b8",
140        Language::Http => "#005C9C",
141        Language::Css => "#563d7c",
142        Language::Elixir => "#6e4a7e",
143        Language::R => "#198CE7",
144        Language::Haskell => "#5e5086",
145        Language::Html => "#e34c26",
146        Language::Svelte => "#ff3e00",
147        Language::Vue => "#41b883",
148        Language::Zig => "#ec915c",
149        Language::Terraform => "#5c4ee5",
150        Language::Puppet => "#302B6D",
151        Language::Pulumi => "#6d2df5",
152        Language::Apex => "#1797c0",
153        Language::Abap => "#E8274B",
154        Language::ServiceNow => "#62d84e",
155        Language::CSharp => "#178600",
156        Language::Json => "#292929",
157    }
158}
159
160/// Get default color for unknown language.
161#[must_use]
162pub const fn default_language_color() -> &'static str {
163    "#cccccc"
164}
165
166/// Get shape for a node kind.
167#[must_use]
168pub fn node_shape(kind: &NodeKind) -> &'static str {
169    match kind {
170        NodeKind::Class | NodeKind::Struct => "component",
171        NodeKind::Interface | NodeKind::Trait => "ellipse",
172        NodeKind::Module => "folder",
173        NodeKind::Variable | NodeKind::Constant => "note",
174        NodeKind::Enum | NodeKind::EnumVariant => "hexagon",
175        NodeKind::Type => "diamond",
176        NodeKind::Macro => "parallelogram",
177        _ => "box",
178    }
179}
180
181/// Get edge style based on edge kind.
182#[must_use]
183pub fn edge_style(kind: &EdgeKind) -> (&'static str, &'static str) {
184    match kind {
185        EdgeKind::Calls { .. } => ("solid", "#333333"),
186        EdgeKind::Imports { .. } => ("dashed", "#0066cc"),
187        EdgeKind::Exports { .. } => ("dashed", "#00cc66"),
188        EdgeKind::References => ("dotted", "#666666"),
189        EdgeKind::Inherits => ("solid", "#990099"),
190        EdgeKind::Implements => ("dashed", "#990099"),
191        EdgeKind::FfiCall { .. } => ("bold", "#ff6600"),
192        EdgeKind::HttpRequest { .. } => ("bold", "#cc0000"),
193        EdgeKind::DbQuery { .. } => ("bold", "#009900"),
194        _ => ("solid", "#666666"),
195    }
196}
197
198/// Get label for an edge kind.
199#[must_use]
200pub fn edge_label(
201    kind: &EdgeKind,
202    strings: &crate::graph::unified::storage::interner::StringInterner,
203) -> String {
204    match kind {
205        EdgeKind::Calls {
206            argument_count,
207            is_async,
208            ..
209        } => {
210            if *is_async {
211                format!("async call({argument_count})")
212            } else {
213                format!("call({argument_count})")
214            }
215        }
216        EdgeKind::Imports { alias, is_wildcard } => {
217            if *is_wildcard {
218                "import *".to_string()
219            } else if let Some(alias_id) = alias {
220                let alias_str = strings
221                    .resolve(*alias_id)
222                    .map_or_else(|| "?".to_string(), |s| s.to_string());
223                format!("import as {alias_str}")
224            } else {
225                "import".to_string()
226            }
227        }
228        EdgeKind::Exports {
229            kind: export_kind,
230            alias,
231        } => {
232            let kind_str = match export_kind {
233                crate::graph::unified::edge::ExportKind::Direct => "export",
234                crate::graph::unified::edge::ExportKind::Reexport => "re-export",
235                crate::graph::unified::edge::ExportKind::Default => "default export",
236                crate::graph::unified::edge::ExportKind::Namespace => "export *",
237            };
238            if let Some(alias_id) = alias {
239                let alias_str = strings
240                    .resolve(*alias_id)
241                    .map_or_else(|| "?".to_string(), |s| s.to_string());
242                format!("{kind_str} as {alias_str}")
243            } else {
244                kind_str.to_string()
245            }
246        }
247        EdgeKind::References => "ref".to_string(),
248        EdgeKind::Inherits => "extends".to_string(),
249        EdgeKind::Implements => "implements".to_string(),
250        EdgeKind::FfiCall { convention } => format!("ffi:{convention:?}"),
251        EdgeKind::HttpRequest { method, .. } => method.as_str().to_string(),
252        EdgeKind::DbQuery { query_type, .. } => format!("{query_type:?}"),
253        _ => String::new(),
254    }
255}
256
257/// Escape string for DOT format.
258#[must_use]
259pub fn escape_dot(s: &str) -> String {
260    s.replace('\\', "\\\\")
261        .replace('"', "\\\"")
262        .replace('\n', "\\n")
263}
264
265/// Escape string for D2 format.
266#[must_use]
267pub fn escape_d2(s: &str) -> String {
268    s.replace('\\', "\\\\")
269        .replace('"', "\\\"")
270        .replace('\n', " ")
271}
272
273// ============================================================================
274// DOT Exporter
275// ============================================================================
276
277/// Configuration for DOT export.
278#[derive(Debug, Clone)]
279pub struct DotConfig {
280    /// Filter to specific languages (empty = all).
281    pub filter_languages: HashSet<Language>,
282    /// Filter to specific edge kinds (empty = all).
283    pub filter_edges: HashSet<EdgeFilter>,
284    /// Filter to specific files (empty = all).
285    pub filter_files: HashSet<String>,
286    /// Restrict rendering to a specific set of node IDs. When `Some`, only these
287    /// nodes (and edges between them) are included in the output. This is a
288    /// fast-path that skips BFS entirely.
289    pub filter_node_ids: Option<HashSet<NodeId>>,
290    /// Highlight cross-language edges.
291    pub highlight_cross_language: bool,
292    /// Maximum depth from root nodes (None = unlimited).
293    pub max_depth: Option<usize>,
294    /// Root nodes to start from (empty = all nodes).
295    pub root_nodes: HashSet<NodeId>,
296    /// Graph direction.
297    pub direction: Direction,
298    /// Show node details (file, line numbers).
299    pub show_details: bool,
300    /// Show edge labels.
301    pub show_edge_labels: bool,
302}
303
304impl Default for DotConfig {
305    fn default() -> Self {
306        Self {
307            filter_languages: HashSet::new(),
308            filter_edges: HashSet::new(),
309            filter_files: HashSet::new(),
310            filter_node_ids: None,
311            highlight_cross_language: false,
312            max_depth: None,
313            root_nodes: HashSet::new(),
314            direction: Direction::LeftToRight,
315            show_details: true,
316            show_edge_labels: true,
317        }
318    }
319}
320
321impl DotConfig {
322    /// Enable cross-language highlighting.
323    #[must_use]
324    pub fn with_cross_language_highlight(mut self, enabled: bool) -> Self {
325        self.highlight_cross_language = enabled;
326        self
327    }
328
329    /// Show node details.
330    #[must_use]
331    pub fn with_details(mut self, enabled: bool) -> Self {
332        self.show_details = enabled;
333        self
334    }
335
336    /// Show edge labels.
337    #[must_use]
338    pub fn with_edge_labels(mut self, enabled: bool) -> Self {
339        self.show_edge_labels = enabled;
340        self
341    }
342
343    /// Set graph direction.
344    #[must_use]
345    pub fn with_direction(mut self, direction: Direction) -> Self {
346        self.direction = direction;
347        self
348    }
349
350    /// Filter to a specific language.
351    #[must_use]
352    pub fn filter_language(mut self, lang: Language) -> Self {
353        self.filter_languages.insert(lang);
354        self
355    }
356
357    /// Filter to a specific edge kind.
358    #[must_use]
359    pub fn filter_edge(mut self, edge: EdgeFilter) -> Self {
360        self.filter_edges.insert(edge);
361        self
362    }
363
364    /// Set maximum depth.
365    #[must_use]
366    pub fn with_max_depth(mut self, depth: usize) -> Self {
367        self.max_depth = Some(depth);
368        self
369    }
370
371    /// Restrict output to the given set of node IDs. Pass `None` to clear any filter.
372    /// When set, this takes priority over `root_nodes`/`max_depth` BFS traversal.
373    #[must_use]
374    pub fn with_filter_node_ids(mut self, ids: Option<HashSet<NodeId>>) -> Self {
375        self.filter_node_ids = ids;
376        self
377    }
378}
379
380/// DOT format exporter for unified graph.
381pub struct UnifiedDotExporter<'a> {
382    graph: &'a GraphSnapshot,
383    config: DotConfig,
384}
385
386impl<'a> UnifiedDotExporter<'a> {
387    /// Create a new exporter with default configuration.
388    #[must_use]
389    pub fn new(graph: &'a GraphSnapshot) -> Self {
390        Self {
391            graph,
392            config: DotConfig::default(),
393        }
394    }
395
396    /// Create a new exporter with custom configuration.
397    #[must_use]
398    pub fn with_config(graph: &'a GraphSnapshot, config: DotConfig) -> Self {
399        Self { graph, config }
400    }
401
402    /// Export graph to DOT format.
403    #[must_use]
404    pub fn export(&self) -> String {
405        let mut dot = String::from("digraph CodeGraph {\n");
406
407        // Graph attributes
408        let rankdir = self.config.direction.as_str();
409        writeln!(dot, "  rankdir={rankdir};").expect("write to String never fails");
410        dot.push_str("  node [shape=box, style=filled];\n");
411        dot.push_str("  overlap=false;\n");
412        dot.push_str("  splines=true;\n\n");
413
414        // Collect visible nodes
415        let visible_nodes = self.filter_nodes();
416
417        // Export nodes
418        for node_id in &visible_nodes {
419            if let Some(entry) = self.graph.get_node(*node_id) {
420                self.export_node(&mut dot, *node_id, entry);
421            }
422        }
423
424        dot.push('\n');
425
426        // Export edges
427        for (from, to, kind) in self.graph.iter_edges() {
428            if !visible_nodes.contains(&from) || !visible_nodes.contains(&to) {
429                continue;
430            }
431
432            if !self.edge_allowed(&kind) {
433                continue;
434            }
435
436            self.export_edge(&mut dot, from, to, &kind);
437        }
438
439        dot.push_str("}\n");
440        dot
441    }
442
443    /// Filter nodes based on configuration.
444    fn filter_nodes(&self) -> HashSet<NodeId> {
445        // Fastest path: explicit node ID filter from pre-computed BFS
446        if let Some(ref filter_ids) = self.config.filter_node_ids {
447            return filter_ids.clone();
448        }
449
450        // Fast path: no filtering
451        if self.config.root_nodes.is_empty() && self.config.max_depth.is_none() {
452            return self
453                .graph
454                .iter_nodes()
455                .filter(|(id, entry)| self.should_include_node(*id, entry))
456                .map(|(id, _)| id)
457                .collect();
458        }
459
460        // BFS from root nodes with depth limit
461        let adjacency = self.build_adjacency();
462        let depth_limit = self.config.max_depth.unwrap_or(usize::MAX);
463        let mut visible = HashSet::new();
464
465        let starting_nodes: Vec<NodeId> = if self.config.root_nodes.is_empty() {
466            // Gate 0d iter-2 fix: skip unified losers from the
467            // visualization starting set. See
468            // `NodeEntry::is_unified_loser`.
469            self.graph
470                .iter_nodes()
471                .filter(|(_, entry)| !entry.is_unified_loser())
472                .map(|(id, _)| id)
473                .collect()
474        } else {
475            self.config.root_nodes.iter().copied().collect()
476        };
477
478        for node_id in starting_nodes {
479            if visible.contains(&node_id) {
480                continue;
481            }
482            self.collect_nodes(&mut visible, &adjacency, node_id, depth_limit);
483        }
484
485        visible
486    }
487
488    /// Check if a node should be included.
489    fn should_include_node(&self, _node_id: NodeId, entry: &NodeEntry) -> bool {
490        // Gate 0d iter-2 fix: never include unified losers in
491        // visualization output. See `NodeEntry::is_unified_loser`.
492        if entry.is_unified_loser() {
493            return false;
494        }
495        // Language filter
496        if !self.config.filter_languages.is_empty() {
497            if let Some(lang) = self.graph.files().language_for_file(entry.file) {
498                if !self.config.filter_languages.contains(&lang) {
499                    return false;
500                }
501            } else {
502                return false;
503            }
504        }
505
506        // File filter
507        if !self.config.filter_files.is_empty() {
508            if let Some(path) = self.graph.files().resolve(entry.file) {
509                let path_str = path.to_string_lossy();
510                if !self
511                    .config
512                    .filter_files
513                    .iter()
514                    .any(|f| path_str.contains(f))
515                {
516                    return false;
517                }
518            } else {
519                return false;
520            }
521        }
522
523        true
524    }
525
526    /// Check if an edge kind is allowed.
527    fn edge_allowed(&self, kind: &EdgeKind) -> bool {
528        if self.config.filter_edges.is_empty() {
529            return true;
530        }
531        self.config.filter_edges.iter().any(|f| f.matches(kind))
532    }
533
534    /// Build adjacency map for BFS.
535    fn build_adjacency(&self) -> HashMap<NodeId, Vec<NodeId>> {
536        let mut adjacency: HashMap<NodeId, Vec<NodeId>> = HashMap::new();
537        for (from, to, _) in self.graph.iter_edges() {
538            adjacency.entry(from).or_default().push(to);
539            adjacency.entry(to).or_default().push(from);
540        }
541        adjacency
542    }
543
544    /// Collect nodes reachable within depth limit.
545    fn collect_nodes(
546        &self,
547        visible: &mut HashSet<NodeId>,
548        adjacency: &HashMap<NodeId, Vec<NodeId>>,
549        start: NodeId,
550        depth_limit: usize,
551    ) {
552        let mut queue = VecDeque::new();
553        queue.push_back((start, 0usize));
554
555        while let Some((node_id, depth)) = queue.pop_front() {
556            if depth > depth_limit {
557                continue;
558            }
559
560            let Some(entry) = self.graph.get_node(node_id) else {
561                continue;
562            };
563
564            if !self.should_include_node(node_id, entry) {
565                continue;
566            }
567
568            if !visible.insert(node_id) {
569                continue;
570            }
571
572            if depth == depth_limit {
573                continue;
574            }
575
576            if let Some(neighbors) = adjacency.get(&node_id) {
577                for neighbor in neighbors {
578                    queue.push_back((*neighbor, depth + 1));
579                }
580            }
581        }
582    }
583
584    /// Export a single node to DOT.
585    fn export_node(&self, dot: &mut String, node_id: NodeId, entry: &NodeEntry) {
586        let lang = self.graph.files().language_for_file(entry.file);
587        let color = lang.map_or(default_language_color(), language_color);
588        let shape = node_shape(&entry.kind);
589
590        // Get name - resolve to Arc<str> then use as_ref for string operations
591        let name = self
592            .graph
593            .strings()
594            .resolve(entry.name)
595            .unwrap_or_else(|| std::sync::Arc::from("?"));
596        let qualified_name = entry
597            .qualified_name
598            .and_then(|id| self.graph.strings().resolve(id))
599            .unwrap_or_else(|| std::sync::Arc::clone(&name));
600
601        // Build label
602        let label = if self.config.show_details {
603            let file = self
604                .graph
605                .files()
606                .resolve(entry.file)
607                .map_or_else(|| "?".to_string(), |p| p.to_string_lossy().into_owned());
608            format!("{}\\n{}:{}", qualified_name, file, entry.start_line)
609        } else {
610            qualified_name.to_string()
611        };
612
613        let label = escape_dot(&label);
614        let node_key = format!("n{}", node_id.index());
615
616        writeln!(
617            dot,
618            "  \"{node_key}\" [label=\"{label}\", fillcolor=\"{color}\", shape=\"{shape}\"];",
619        )
620        .expect("write to String never fails");
621    }
622
623    /// Export a single edge to DOT.
624    fn export_edge(&self, dot: &mut String, from: NodeId, to: NodeId, kind: &EdgeKind) {
625        let (style, base_color) = edge_style(kind);
626        let color = if self.config.highlight_cross_language
627            && let (Some(from_entry), Some(to_entry)) =
628                (self.graph.get_node(from), self.graph.get_node(to))
629        {
630            let from_lang = self.graph.files().language_for_file(from_entry.file);
631            let to_lang = self.graph.files().language_for_file(to_entry.file);
632            if from_lang == to_lang {
633                base_color
634            } else {
635                "red"
636            }
637        } else {
638            base_color
639        };
640
641        let label = if self.config.show_edge_labels {
642            edge_label(kind, self.graph.strings())
643        } else {
644            String::new()
645        };
646
647        let from_key = format!("n{}", from.index());
648        let to_key = format!("n{}", to.index());
649
650        if label.is_empty() {
651            writeln!(
652                dot,
653                "  \"{from_key}\" -> \"{to_key}\" [style=\"{style}\", color=\"{color}\"];"
654            )
655            .expect("write to String never fails");
656        } else {
657            writeln!(
658                dot,
659                "  \"{from_key}\" -> \"{to_key}\" [style=\"{style}\", color=\"{color}\", label=\"{}\"];",
660                escape_dot(&label)
661            )
662            .expect("write to String never fails");
663        }
664    }
665}
666
667// ============================================================================
668// D2 Exporter
669// ============================================================================
670
671/// Configuration for D2 export.
672#[derive(Debug, Clone)]
673pub struct D2Config {
674    /// Filter to specific languages.
675    pub filter_languages: HashSet<Language>,
676    /// Filter to specific edge kinds.
677    pub filter_edges: HashSet<EdgeFilter>,
678    /// Restrict rendering to a specific set of node IDs. When `Some`, only these
679    /// nodes (and edges between them) are included in the output.
680    pub filter_node_ids: Option<HashSet<NodeId>>,
681    /// Highlight cross-language edges.
682    pub highlight_cross_language: bool,
683    /// Show node details.
684    pub show_details: bool,
685    /// Show edge labels.
686    pub show_edge_labels: bool,
687    /// Graph direction.
688    pub direction: Direction,
689}
690
691impl Default for D2Config {
692    fn default() -> Self {
693        Self {
694            filter_languages: HashSet::new(),
695            filter_edges: HashSet::new(),
696            filter_node_ids: None,
697            highlight_cross_language: false,
698            show_details: true,
699            show_edge_labels: true,
700            direction: Direction::LeftToRight,
701        }
702    }
703}
704
705impl D2Config {
706    /// Enable cross-language highlighting.
707    #[must_use]
708    pub fn with_cross_language_highlight(mut self, enabled: bool) -> Self {
709        self.highlight_cross_language = enabled;
710        self
711    }
712
713    /// Show node details.
714    #[must_use]
715    pub fn with_details(mut self, enabled: bool) -> Self {
716        self.show_details = enabled;
717        self
718    }
719
720    /// Show edge labels.
721    #[must_use]
722    pub fn with_edge_labels(mut self, enabled: bool) -> Self {
723        self.show_edge_labels = enabled;
724        self
725    }
726
727    /// Restrict output to the given set of node IDs. Pass `None` to clear any filter.
728    #[must_use]
729    pub fn with_filter_node_ids(mut self, ids: Option<HashSet<NodeId>>) -> Self {
730        self.filter_node_ids = ids;
731        self
732    }
733}
734
735/// D2 format exporter for unified graph.
736pub struct UnifiedD2Exporter<'a> {
737    graph: &'a GraphSnapshot,
738    config: D2Config,
739}
740
741impl<'a> UnifiedD2Exporter<'a> {
742    /// Create a new exporter with default configuration.
743    #[must_use]
744    pub fn new(graph: &'a GraphSnapshot) -> Self {
745        Self {
746            graph,
747            config: D2Config::default(),
748        }
749    }
750
751    /// Create a new exporter with custom configuration.
752    #[must_use]
753    pub fn with_config(graph: &'a GraphSnapshot, config: D2Config) -> Self {
754        Self { graph, config }
755    }
756
757    /// Export graph to D2 format.
758    #[must_use]
759    pub fn export(&self) -> String {
760        let mut d2 = String::new();
761
762        // Direction
763        writeln!(d2, "direction: {}", self.config.direction.as_str())
764            .expect("write to String never fails");
765        d2.push('\n');
766
767        // Collect visible nodes
768        let visible_nodes: HashSet<NodeId> =
769            if let Some(ref filter_ids) = self.config.filter_node_ids {
770                filter_ids.clone()
771            } else {
772                self.graph
773                    .iter_nodes()
774                    .filter(|(id, entry)| self.should_include_node(*id, entry))
775                    .map(|(id, _)| id)
776                    .collect()
777            };
778
779        // Export nodes
780        for node_id in &visible_nodes {
781            if let Some(entry) = self.graph.get_node(*node_id) {
782                self.export_node(&mut d2, *node_id, entry);
783            }
784        }
785
786        d2.push('\n');
787
788        // Export edges
789        for (from, to, kind) in self.graph.iter_edges() {
790            if !visible_nodes.contains(&from) || !visible_nodes.contains(&to) {
791                continue;
792            }
793
794            if !self.edge_allowed(&kind) {
795                continue;
796            }
797
798            self.export_edge(&mut d2, from, to, &kind);
799        }
800
801        d2
802    }
803
804    /// Check if a node should be included.
805    fn should_include_node(&self, _node_id: NodeId, entry: &NodeEntry) -> bool {
806        // Gate 0d iter-2 fix: never include unified losers in D2
807        // visualization. See `NodeEntry::is_unified_loser`.
808        if entry.is_unified_loser() {
809            return false;
810        }
811        if !self.config.filter_languages.is_empty() {
812            if let Some(lang) = self.graph.files().language_for_file(entry.file) {
813                if !self.config.filter_languages.contains(&lang) {
814                    return false;
815                }
816            } else {
817                return false;
818            }
819        }
820        true
821    }
822
823    /// Check if an edge kind is allowed.
824    fn edge_allowed(&self, kind: &EdgeKind) -> bool {
825        if self.config.filter_edges.is_empty() {
826            return true;
827        }
828        self.config.filter_edges.iter().any(|f| f.matches(kind))
829    }
830
831    /// Export a single node to D2.
832    fn export_node(&self, d2: &mut String, node_id: NodeId, entry: &NodeEntry) {
833        let lang = self.graph.files().language_for_file(entry.file);
834        let color = lang.map_or(default_language_color(), language_color);
835        let shape = match entry.kind {
836            NodeKind::Class | NodeKind::Struct => "class",
837            NodeKind::Interface | NodeKind::Trait => "oval",
838            NodeKind::Module => "package",
839            _ => "rectangle",
840        };
841
842        let name = self
843            .graph
844            .strings()
845            .resolve(entry.name)
846            .unwrap_or_else(|| std::sync::Arc::from("?"));
847        let qualified_name = entry
848            .qualified_name
849            .and_then(|id| self.graph.strings().resolve(id))
850            .unwrap_or_else(|| std::sync::Arc::clone(&name));
851
852        let label = if self.config.show_details {
853            let file = self
854                .graph
855                .files()
856                .resolve(entry.file)
857                .map_or_else(|| "?".to_string(), |p| p.to_string_lossy().into_owned());
858            format!("{} ({file}:{})", qualified_name.as_ref(), entry.start_line)
859        } else {
860            qualified_name.to_string()
861        };
862
863        let node_key = format!("n{}", node_id.index());
864        let label = escape_d2(&label);
865
866        writeln!(d2, "{node_key}: \"{label}\" {{").expect("write to String never fails");
867        writeln!(d2, "  shape: {shape}").expect("write to String never fails");
868        writeln!(d2, "  style.fill: \"{color}\"").expect("write to String never fails");
869        writeln!(d2, "}}").expect("write to String never fails");
870    }
871
872    /// Export a single edge to D2.
873    fn export_edge(&self, d2: &mut String, from: NodeId, to: NodeId, kind: &EdgeKind) {
874        let (style, base_color) = edge_style(kind);
875        let color = if self.config.highlight_cross_language
876            && let (Some(from_entry), Some(to_entry)) =
877                (self.graph.get_node(from), self.graph.get_node(to))
878        {
879            let from_lang = self.graph.files().language_for_file(from_entry.file);
880            let to_lang = self.graph.files().language_for_file(to_entry.file);
881            if from_lang == to_lang {
882                base_color
883            } else {
884                "#ff0000"
885            }
886        } else {
887            base_color
888        };
889
890        let from_key = format!("n{}", from.index());
891        let to_key = format!("n{}", to.index());
892
893        let arrow = match kind {
894            EdgeKind::Inherits | EdgeKind::Implements => "<->",
895            _ => "->",
896        };
897
898        if self.config.show_edge_labels {
899            let label = edge_label(kind, self.graph.strings());
900            if label.is_empty() {
901                writeln!(d2, "{from_key} {arrow} {to_key}: {{")
902                    .expect("write to String never fails");
903            } else {
904                writeln!(d2, "{from_key} {arrow} {to_key}: \"{label}\" {{")
905                    .expect("write to String never fails");
906            }
907        } else {
908            writeln!(d2, "{from_key} {arrow} {to_key}: {{").expect("write to String never fails");
909        }
910
911        let d2_style = match style {
912            "dashed" => "stroke-dash: 3",
913            "dotted" => "stroke-dash: 1",
914            "bold" => "stroke-width: 3",
915            _ => "",
916        };
917
918        if !d2_style.is_empty() {
919            writeln!(d2, "  style.{d2_style}").expect("write to String never fails");
920        }
921        writeln!(d2, "  style.stroke: \"{color}\"").expect("write to String never fails");
922        writeln!(d2, "}}").expect("write to String never fails");
923    }
924}
925
926// ============================================================================
927// Mermaid Exporter
928// ============================================================================
929
930/// Configuration for Mermaid export.
931#[derive(Debug, Clone)]
932pub struct MermaidConfig {
933    /// Filter to specific languages.
934    pub filter_languages: HashSet<Language>,
935    /// Filter to specific edge kinds.
936    pub filter_edges: HashSet<EdgeFilter>,
937    /// Highlight cross-language edges.
938    pub highlight_cross_language: bool,
939    /// Show edge labels.
940    pub show_edge_labels: bool,
941    /// Graph direction.
942    pub direction: Direction,
943    /// Restrict rendering to a specific set of node IDs. When `Some`, only these
944    /// nodes (and edges between them) are included in the output.
945    pub filter_node_ids: Option<HashSet<NodeId>>,
946}
947
948impl Default for MermaidConfig {
949    fn default() -> Self {
950        Self {
951            filter_languages: HashSet::new(),
952            filter_edges: HashSet::new(),
953            highlight_cross_language: false,
954            show_edge_labels: true,
955            direction: Direction::LeftToRight,
956            filter_node_ids: None,
957        }
958    }
959}
960
961impl MermaidConfig {
962    /// Enable cross-language highlighting.
963    #[must_use]
964    pub fn with_cross_language_highlight(mut self, enabled: bool) -> Self {
965        self.highlight_cross_language = enabled;
966        self
967    }
968
969    /// Show edge labels.
970    #[must_use]
971    pub fn with_edge_labels(mut self, enabled: bool) -> Self {
972        self.show_edge_labels = enabled;
973        self
974    }
975
976    /// Restrict output to the given set of node IDs. Pass `None` to clear any filter.
977    #[must_use]
978    pub fn with_filter_node_ids(mut self, ids: Option<HashSet<NodeId>>) -> Self {
979        self.filter_node_ids = ids;
980        self
981    }
982}
983
984/// Mermaid format exporter for unified graph.
985pub struct UnifiedMermaidExporter<'a> {
986    graph: &'a GraphSnapshot,
987    config: MermaidConfig,
988}
989
990impl<'a> UnifiedMermaidExporter<'a> {
991    /// Create a new exporter with default configuration.
992    #[must_use]
993    pub fn new(graph: &'a GraphSnapshot) -> Self {
994        Self {
995            graph,
996            config: MermaidConfig::default(),
997        }
998    }
999
1000    /// Create a new exporter with custom configuration.
1001    #[must_use]
1002    pub fn with_config(graph: &'a GraphSnapshot, config: MermaidConfig) -> Self {
1003        Self { graph, config }
1004    }
1005
1006    /// Export graph to Mermaid format.
1007    #[must_use]
1008    pub fn export(&self) -> String {
1009        let mut mermaid = String::new();
1010
1011        // Header
1012        writeln!(mermaid, "graph {}", self.config.direction.as_str())
1013            .expect("write to String never fails");
1014
1015        // Collect visible nodes
1016        let visible_nodes: HashSet<NodeId> =
1017            if let Some(ref filter_ids) = self.config.filter_node_ids {
1018                filter_ids.clone()
1019            } else {
1020                self.graph
1021                    .iter_nodes()
1022                    .filter(|(id, entry)| self.should_include_node(*id, entry))
1023                    .map(|(id, _)| id)
1024                    .collect()
1025            };
1026
1027        // Export nodes
1028        for node_id in &visible_nodes {
1029            if let Some(entry) = self.graph.get_node(*node_id) {
1030                self.export_node(&mut mermaid, *node_id, entry);
1031            }
1032        }
1033
1034        // Export edges
1035        for (from, to, kind) in self.graph.iter_edges() {
1036            if !visible_nodes.contains(&from) || !visible_nodes.contains(&to) {
1037                continue;
1038            }
1039
1040            if !self.edge_allowed(&kind) {
1041                continue;
1042            }
1043
1044            self.export_edge(&mut mermaid, from, to, &kind);
1045        }
1046
1047        mermaid
1048    }
1049
1050    /// Check if a node should be included.
1051    fn should_include_node(&self, _node_id: NodeId, entry: &NodeEntry) -> bool {
1052        // Gate 0d iter-2 fix: never include unified losers in
1053        // Mermaid visualization. See `NodeEntry::is_unified_loser`.
1054        if entry.is_unified_loser() {
1055            return false;
1056        }
1057        if !self.config.filter_languages.is_empty() {
1058            if let Some(lang) = self.graph.files().language_for_file(entry.file) {
1059                if !self.config.filter_languages.contains(&lang) {
1060                    return false;
1061                }
1062            } else {
1063                return false;
1064            }
1065        }
1066        true
1067    }
1068
1069    /// Check if an edge kind is allowed.
1070    fn edge_allowed(&self, kind: &EdgeKind) -> bool {
1071        if self.config.filter_edges.is_empty() {
1072            return true;
1073        }
1074        self.config.filter_edges.iter().any(|f| f.matches(kind))
1075    }
1076
1077    /// Export a single node to Mermaid.
1078    fn export_node(&self, mermaid: &mut String, node_id: NodeId, entry: &NodeEntry) {
1079        let name = self
1080            .graph
1081            .strings()
1082            .resolve(entry.name)
1083            .unwrap_or_else(|| std::sync::Arc::from("?"));
1084        let qualified_name = entry
1085            .qualified_name
1086            .and_then(|id| self.graph.strings().resolve(id))
1087            .unwrap_or_else(|| std::sync::Arc::clone(&name));
1088
1089        let node_key = format!("n{}", node_id.index());
1090        let label = Self::escape_mermaid(&qualified_name);
1091
1092        // Node shapes in Mermaid
1093        let (open, close) = match entry.kind {
1094            NodeKind::Class | NodeKind::Struct => ("[[", "]]"),
1095            NodeKind::Interface | NodeKind::Trait => ("([", "])"),
1096            NodeKind::Module => ("{{", "}}"),
1097            _ => ("[", "]"),
1098        };
1099
1100        writeln!(mermaid, "    {node_key}{open}\"{label}\"{close}")
1101            .expect("write to String never fails");
1102    }
1103
1104    /// Export a single edge to Mermaid.
1105    fn export_edge(&self, mermaid: &mut String, from: NodeId, to: NodeId, kind: &EdgeKind) {
1106        let from_key = format!("n{}", from.index());
1107        let to_key = format!("n{}", to.index());
1108
1109        let arrow = match kind {
1110            EdgeKind::Imports { .. } | EdgeKind::Exports { .. } => "-.->",
1111            EdgeKind::Calls { is_async: true, .. } => "==>",
1112            _ => "-->",
1113        };
1114
1115        if self.config.show_edge_labels {
1116            let label = edge_label(kind, self.graph.strings());
1117            if label.is_empty() {
1118                writeln!(mermaid, "    {from_key} {arrow} {to_key}")
1119                    .expect("write to String never fails");
1120            } else {
1121                let label = Self::escape_mermaid(&label);
1122                writeln!(mermaid, "    {from_key} {arrow}|\"{label}\"| {to_key}")
1123                    .expect("write to String never fails");
1124            }
1125        } else {
1126            writeln!(mermaid, "    {from_key} {arrow} {to_key}")
1127                .expect("write to String never fails");
1128        }
1129    }
1130
1131    /// Escape string for Mermaid.
1132    fn escape_mermaid(s: &str) -> String {
1133        s.replace('"', "#quot;")
1134            .replace('<', "&lt;")
1135            .replace('>', "&gt;")
1136    }
1137}
1138
1139// ============================================================================
1140// JSON Exporter
1141// ============================================================================
1142
1143/// Configuration for JSON export.
1144#[derive(Debug, Clone, Default)]
1145pub struct JsonConfig {
1146    /// Include node details (signature, doc).
1147    pub include_details: bool,
1148    /// Include edge metadata.
1149    pub include_edge_metadata: bool,
1150}
1151
1152impl JsonConfig {
1153    /// Include node details.
1154    #[must_use]
1155    pub fn with_details(mut self, enabled: bool) -> Self {
1156        self.include_details = enabled;
1157        self
1158    }
1159
1160    /// Include edge metadata.
1161    #[must_use]
1162    pub fn with_edge_metadata(mut self, enabled: bool) -> Self {
1163        self.include_edge_metadata = enabled;
1164        self
1165    }
1166}
1167
1168/// JSON format exporter for unified graph.
1169pub struct UnifiedJsonExporter<'a> {
1170    graph: &'a GraphSnapshot,
1171    config: JsonConfig,
1172}
1173
1174impl<'a> UnifiedJsonExporter<'a> {
1175    /// Create a new exporter with default configuration.
1176    #[must_use]
1177    pub fn new(graph: &'a GraphSnapshot) -> Self {
1178        Self {
1179            graph,
1180            config: JsonConfig::default(),
1181        }
1182    }
1183
1184    /// Create a new exporter with custom configuration.
1185    #[must_use]
1186    pub fn with_config(graph: &'a GraphSnapshot, config: JsonConfig) -> Self {
1187        Self { graph, config }
1188    }
1189
1190    /// Export graph to JSON.
1191    #[must_use]
1192    pub fn export(&self) -> serde_json::Value {
1193        let nodes = self.export_nodes();
1194        let edges = self.export_edges();
1195
1196        serde_json::json!({
1197            "nodes": nodes,
1198            "edges": edges,
1199            "metadata": {
1200                "node_count": nodes.len(),
1201                "edge_count": edges.len(),
1202            }
1203        })
1204    }
1205
1206    fn export_nodes(&self) -> Vec<serde_json::Value> {
1207        // Gate 0d iter-2 fix: skip unified losers from JSON
1208        // visualization export. See `NodeEntry::is_unified_loser`.
1209        self.graph
1210            .iter_nodes()
1211            .filter(|(_, entry)| !entry.is_unified_loser())
1212            .map(|(node_id, entry)| self.export_node(node_id, entry))
1213            .collect()
1214    }
1215
1216    fn export_node(&self, node_id: NodeId, entry: &NodeEntry) -> serde_json::Value {
1217        let name = self
1218            .graph
1219            .strings()
1220            .resolve(entry.name)
1221            .map_or_else(|| "?".to_string(), |s| s.to_string());
1222        let qualified_name = entry
1223            .qualified_name
1224            .and_then(|id| self.graph.strings().resolve(id))
1225            .map_or_else(|| name.clone(), |s| s.to_string());
1226        let file = self
1227            .graph
1228            .files()
1229            .resolve(entry.file)
1230            .map_or_else(|| "?".to_string(), |p| p.to_string_lossy().into_owned());
1231        let lang = self
1232            .graph
1233            .files()
1234            .language_for_file(entry.file)
1235            .map_or_else(|| "Unknown".to_string(), |l| format!("{l:?}"));
1236
1237        let mut node = serde_json::json!({
1238            "id": format!("n{}", node_id.index()),
1239            "name": name,
1240            "qualified_name": qualified_name,
1241            "kind": format!("{:?}", entry.kind),
1242            "file": file,
1243            "language": lang,
1244            "line": entry.start_line,
1245        });
1246
1247        if self.config.include_details {
1248            self.append_node_details(entry, &mut node);
1249        }
1250
1251        node
1252    }
1253
1254    fn append_node_details(&self, entry: &NodeEntry, node: &mut serde_json::Value) {
1255        if let Some(sig_id) = entry.signature
1256            && let Some(sig) = self.graph.strings().resolve(sig_id)
1257        {
1258            node["signature"] = serde_json::Value::String(sig.to_string());
1259        }
1260        if let Some(doc_id) = entry.doc
1261            && let Some(doc) = self.graph.strings().resolve(doc_id)
1262        {
1263            node["doc"] = serde_json::Value::String(doc.to_string());
1264        }
1265        if let Some(vis_id) = entry.visibility
1266            && let Some(vis) = self.graph.strings().resolve(vis_id)
1267        {
1268            node["visibility"] = serde_json::Value::String(vis.to_string());
1269        }
1270        node["is_async"] = serde_json::Value::Bool(entry.is_async);
1271        node["is_static"] = serde_json::Value::Bool(entry.is_static);
1272    }
1273
1274    fn export_edges(&self) -> Vec<serde_json::Value> {
1275        self.graph
1276            .iter_edges()
1277            .map(|(from, to, kind)| self.export_edge(from, to, &kind))
1278            .collect()
1279    }
1280
1281    fn export_edge(&self, from: NodeId, to: NodeId, kind: &EdgeKind) -> serde_json::Value {
1282        let from_key = format!("n{}", from.index());
1283        let to_key = format!("n{}", to.index());
1284
1285        let mut edge = serde_json::json!({
1286            "from": from_key,
1287            "to": to_key,
1288            "kind": Self::edge_kind_name(kind),
1289        });
1290
1291        if self.config.include_edge_metadata {
1292            self.append_edge_metadata(kind, &mut edge);
1293        }
1294
1295        edge
1296    }
1297
1298    fn append_edge_metadata(&self, kind: &EdgeKind, edge: &mut serde_json::Value) {
1299        match kind {
1300            EdgeKind::Calls {
1301                argument_count,
1302                is_async,
1303                ..
1304            } => {
1305                edge["argument_count"] = serde_json::Value::Number((*argument_count).into());
1306                edge["is_async"] = serde_json::Value::Bool(*is_async);
1307            }
1308            EdgeKind::Imports { alias, is_wildcard } => {
1309                edge["is_wildcard"] = serde_json::Value::Bool(*is_wildcard);
1310                if let Some(alias_id) = alias
1311                    && let Some(alias_str) = self.graph.strings().resolve(*alias_id)
1312                {
1313                    edge["alias"] = serde_json::Value::String(alias_str.to_string());
1314                }
1315            }
1316            EdgeKind::Exports {
1317                kind: export_kind,
1318                alias,
1319            } => {
1320                edge["export_kind"] = serde_json::Value::String(format!("{export_kind:?}"));
1321                if let Some(alias_id) = alias
1322                    && let Some(alias_str) = self.graph.strings().resolve(*alias_id)
1323                {
1324                    edge["alias"] = serde_json::Value::String(alias_str.to_string());
1325                }
1326            }
1327            EdgeKind::HttpRequest { method, url } => {
1328                edge["method"] = serde_json::Value::String(method.as_str().to_string());
1329                if let Some(url_id) = url
1330                    && let Some(url_str) = self.graph.strings().resolve(*url_id)
1331                {
1332                    edge["url"] = serde_json::Value::String(url_str.to_string());
1333                }
1334            }
1335            _ => {}
1336        }
1337    }
1338
1339    /// Get edge kind name as string.
1340    fn edge_kind_name(kind: &EdgeKind) -> &'static str {
1341        match kind {
1342            EdgeKind::Defines => "defines",
1343            EdgeKind::Contains => "contains",
1344            EdgeKind::Calls { .. } => "calls",
1345            EdgeKind::References => "references",
1346            EdgeKind::Imports { .. } => "imports",
1347            EdgeKind::Exports { .. } => "exports",
1348            EdgeKind::TypeOf { .. } => "type_of",
1349            EdgeKind::Inherits => "inherits",
1350            EdgeKind::Implements => "implements",
1351            EdgeKind::FfiCall { .. } => "ffi_call",
1352            EdgeKind::HttpRequest { .. } => "http_request",
1353            EdgeKind::GrpcCall { .. } => "grpc_call",
1354            EdgeKind::WebAssemblyCall => "wasm_call",
1355            EdgeKind::DbQuery { .. } => "db_query",
1356            EdgeKind::TableRead { .. } => "table_read",
1357            EdgeKind::TableWrite { .. } => "table_write",
1358            EdgeKind::TriggeredBy { .. } => "triggered_by",
1359            EdgeKind::MessageQueue { .. } => "message_queue",
1360            EdgeKind::WebSocket { .. } => "websocket",
1361            EdgeKind::GraphQLOperation { .. } => "graphql_operation",
1362            EdgeKind::ProcessExec { .. } => "process_exec",
1363            EdgeKind::FileIpc { .. } => "file_ipc",
1364            EdgeKind::ProtocolCall { .. } => "protocol_call",
1365            // Rust-specific edge kinds
1366            EdgeKind::LifetimeConstraint { .. } => "lifetime_constraint",
1367            EdgeKind::TraitMethodBinding { .. } => "trait_method_binding",
1368            EdgeKind::MacroExpansion { .. } => "macro_expansion",
1369            // JVM Classpath (Track C)
1370            EdgeKind::GenericBound => "generic_bound",
1371            EdgeKind::AnnotatedWith => "annotated_with",
1372            EdgeKind::AnnotationParam => "annotation_param",
1373            EdgeKind::LambdaCaptures => "lambda_captures",
1374            EdgeKind::ModuleExports => "module_exports",
1375            EdgeKind::ModuleRequires => "module_requires",
1376            EdgeKind::ModuleOpens => "module_opens",
1377            EdgeKind::ModuleProvides => "module_provides",
1378            EdgeKind::TypeArgument => "type_argument",
1379            EdgeKind::ExtensionReceiver => "extension_receiver",
1380            EdgeKind::CompanionOf => "companion_of",
1381            EdgeKind::SealedPermit => "sealed_permit",
1382        }
1383    }
1384}
1385
1386#[cfg(test)]
1387mod tests {
1388    use super::*;
1389
1390    // ===== Direction tests =====
1391
1392    #[test]
1393    fn test_direction_as_str() {
1394        assert_eq!(Direction::LeftToRight.as_str(), "LR");
1395        assert_eq!(Direction::TopToBottom.as_str(), "TB");
1396    }
1397
1398    #[test]
1399    fn test_direction_default() {
1400        assert_eq!(Direction::default(), Direction::LeftToRight);
1401    }
1402
1403    // ===== EdgeFilter tests =====
1404
1405    #[test]
1406    fn test_edge_filter_matches_calls() {
1407        assert!(EdgeFilter::Calls.matches(&EdgeKind::Calls {
1408            argument_count: 0,
1409            is_async: false,
1410            resolved_via: ResolvedVia::Direct,
1411        }));
1412        assert!(EdgeFilter::Calls.matches(&EdgeKind::Calls {
1413            argument_count: 5,
1414            is_async: true,
1415            resolved_via: ResolvedVia::Direct,
1416        }));
1417        assert!(!EdgeFilter::Calls.matches(&EdgeKind::References));
1418    }
1419
1420    #[test]
1421    fn test_edge_filter_matches_imports() {
1422        assert!(EdgeFilter::Imports.matches(&EdgeKind::Imports {
1423            alias: None,
1424            is_wildcard: false
1425        }));
1426        assert!(EdgeFilter::Imports.matches(&EdgeKind::Imports {
1427            alias: None,
1428            is_wildcard: true
1429        }));
1430        assert!(!EdgeFilter::Imports.matches(&EdgeKind::Exports {
1431            kind: crate::graph::unified::edge::ExportKind::Direct,
1432            alias: None
1433        }));
1434    }
1435
1436    #[test]
1437    fn test_edge_filter_matches_exports() {
1438        assert!(EdgeFilter::Exports.matches(&EdgeKind::Exports {
1439            kind: crate::graph::unified::edge::ExportKind::Direct,
1440            alias: None
1441        }));
1442        assert!(!EdgeFilter::Exports.matches(&EdgeKind::Imports {
1443            alias: None,
1444            is_wildcard: false
1445        }));
1446    }
1447
1448    #[test]
1449    fn test_edge_filter_matches_references() {
1450        assert!(EdgeFilter::References.matches(&EdgeKind::References));
1451        assert!(!EdgeFilter::References.matches(&EdgeKind::Calls {
1452            argument_count: 0,
1453            is_async: false,
1454            resolved_via: ResolvedVia::Direct,
1455        }));
1456    }
1457
1458    #[test]
1459    fn test_edge_filter_matches_inheritance() {
1460        assert!(EdgeFilter::Inherits.matches(&EdgeKind::Inherits));
1461        assert!(EdgeFilter::Implements.matches(&EdgeKind::Implements));
1462        assert!(!EdgeFilter::Inherits.matches(&EdgeKind::Implements));
1463        assert!(!EdgeFilter::Implements.matches(&EdgeKind::Inherits));
1464    }
1465
1466    #[test]
1467    fn test_edge_filter_matches_cross_language() {
1468        assert!(EdgeFilter::FfiCall.matches(&EdgeKind::FfiCall {
1469            convention: crate::graph::unified::edge::FfiConvention::C
1470        }));
1471        assert!(EdgeFilter::HttpRequest.matches(&EdgeKind::HttpRequest {
1472            method: crate::graph::unified::edge::HttpMethod::Get,
1473            url: None
1474        }));
1475        assert!(EdgeFilter::DbQuery.matches(&EdgeKind::DbQuery {
1476            query_type: crate::graph::unified::edge::DbQueryType::Select,
1477            table: None
1478        }));
1479    }
1480
1481    // ===== Language color tests =====
1482
1483    #[test]
1484    fn test_language_color_common_languages() {
1485        assert_eq!(language_color(Language::Rust), "#dea584");
1486        assert_eq!(language_color(Language::JavaScript), "#f7df1e");
1487        assert_eq!(language_color(Language::TypeScript), "#3178c6");
1488        assert_eq!(language_color(Language::Python), "#3572A5");
1489        assert_eq!(language_color(Language::Go), "#00ADD8");
1490        assert_eq!(language_color(Language::Java), "#b07219");
1491    }
1492
1493    #[test]
1494    fn test_language_color_all_languages() {
1495        // Ensure all languages have colors (no panic)
1496        let languages = [
1497            Language::Rust,
1498            Language::JavaScript,
1499            Language::TypeScript,
1500            Language::Python,
1501            Language::Go,
1502            Language::Java,
1503            Language::Ruby,
1504            Language::Php,
1505            Language::Cpp,
1506            Language::C,
1507            Language::Swift,
1508            Language::Kotlin,
1509            Language::Scala,
1510            Language::Sql,
1511            Language::Plsql,
1512            Language::Shell,
1513            Language::Lua,
1514            Language::Perl,
1515            Language::Dart,
1516            Language::Groovy,
1517            Language::Http,
1518            Language::Css,
1519            Language::Elixir,
1520            Language::R,
1521            Language::Haskell,
1522            Language::Html,
1523            Language::Svelte,
1524            Language::Vue,
1525            Language::Zig,
1526            Language::Terraform,
1527            Language::Puppet,
1528            Language::Apex,
1529            Language::Abap,
1530            Language::ServiceNow,
1531            Language::CSharp,
1532        ];
1533        for lang in languages {
1534            let color = language_color(lang);
1535            assert!(color.starts_with('#'), "Color for {lang:?} should be hex");
1536        }
1537    }
1538
1539    #[test]
1540    fn test_default_language_color() {
1541        assert_eq!(default_language_color(), "#cccccc");
1542    }
1543
1544    // ===== Node shape tests =====
1545
1546    #[test]
1547    fn test_node_shape_class_types() {
1548        assert_eq!(node_shape(&NodeKind::Class), "component");
1549        assert_eq!(node_shape(&NodeKind::Struct), "component");
1550    }
1551
1552    #[test]
1553    fn test_node_shape_interface_types() {
1554        assert_eq!(node_shape(&NodeKind::Interface), "ellipse");
1555        assert_eq!(node_shape(&NodeKind::Trait), "ellipse");
1556    }
1557
1558    #[test]
1559    fn test_node_shape_module() {
1560        assert_eq!(node_shape(&NodeKind::Module), "folder");
1561    }
1562
1563    #[test]
1564    fn test_node_shape_variables() {
1565        assert_eq!(node_shape(&NodeKind::Variable), "note");
1566        assert_eq!(node_shape(&NodeKind::Constant), "note");
1567    }
1568
1569    #[test]
1570    fn test_node_shape_enums() {
1571        assert_eq!(node_shape(&NodeKind::Enum), "hexagon");
1572        assert_eq!(node_shape(&NodeKind::EnumVariant), "hexagon");
1573    }
1574
1575    #[test]
1576    fn test_node_shape_special() {
1577        assert_eq!(node_shape(&NodeKind::Type), "diamond");
1578        assert_eq!(node_shape(&NodeKind::Macro), "parallelogram");
1579    }
1580
1581    #[test]
1582    fn test_node_shape_default() {
1583        assert_eq!(node_shape(&NodeKind::Function), "box");
1584        assert_eq!(node_shape(&NodeKind::Method), "box");
1585    }
1586
1587    // ===== Edge style tests =====
1588
1589    #[test]
1590    fn test_edge_style_calls() {
1591        let (style, color) = edge_style(&EdgeKind::Calls {
1592            argument_count: 0,
1593            is_async: false,
1594            resolved_via: ResolvedVia::Direct,
1595        });
1596        assert_eq!(style, "solid");
1597        assert_eq!(color, "#333333");
1598    }
1599
1600    #[test]
1601    fn test_edge_style_imports_exports() {
1602        let (style, color) = edge_style(&EdgeKind::Imports {
1603            alias: None,
1604            is_wildcard: false,
1605        });
1606        assert_eq!(style, "dashed");
1607        assert_eq!(color, "#0066cc");
1608
1609        let (style, color) = edge_style(&EdgeKind::Exports {
1610            kind: crate::graph::unified::edge::ExportKind::Direct,
1611            alias: None,
1612        });
1613        assert_eq!(style, "dashed");
1614        assert_eq!(color, "#00cc66");
1615    }
1616
1617    #[test]
1618    fn test_edge_style_references() {
1619        let (style, color) = edge_style(&EdgeKind::References);
1620        assert_eq!(style, "dotted");
1621        assert_eq!(color, "#666666");
1622    }
1623
1624    #[test]
1625    fn test_edge_style_inheritance() {
1626        let (style, color) = edge_style(&EdgeKind::Inherits);
1627        assert_eq!(style, "solid");
1628        assert_eq!(color, "#990099");
1629
1630        let (style, color) = edge_style(&EdgeKind::Implements);
1631        assert_eq!(style, "dashed");
1632        assert_eq!(color, "#990099");
1633    }
1634
1635    #[test]
1636    fn test_edge_style_cross_language() {
1637        let (style, color) = edge_style(&EdgeKind::FfiCall {
1638            convention: crate::graph::unified::edge::FfiConvention::C,
1639        });
1640        assert_eq!(style, "bold");
1641        assert_eq!(color, "#ff6600");
1642
1643        let (style, color) = edge_style(&EdgeKind::HttpRequest {
1644            method: crate::graph::unified::edge::HttpMethod::Get,
1645            url: None,
1646        });
1647        assert_eq!(style, "bold");
1648        assert_eq!(color, "#cc0000");
1649
1650        let (style, color) = edge_style(&EdgeKind::DbQuery {
1651            query_type: crate::graph::unified::edge::DbQueryType::Select,
1652            table: None,
1653        });
1654        assert_eq!(style, "bold");
1655        assert_eq!(color, "#009900");
1656    }
1657
1658    // ===== Escape function tests =====
1659
1660    #[test]
1661    fn test_escape_dot_basic() {
1662        assert_eq!(escape_dot("hello"), "hello");
1663        assert_eq!(escape_dot("hello world"), "hello world");
1664    }
1665
1666    #[test]
1667    fn test_escape_dot_quotes() {
1668        assert_eq!(escape_dot("say \"hi\""), "say \\\"hi\\\"");
1669        assert_eq!(escape_dot("\"quoted\""), "\\\"quoted\\\"");
1670    }
1671
1672    #[test]
1673    fn test_escape_dot_newlines() {
1674        assert_eq!(escape_dot("line1\nline2"), "line1\\nline2");
1675        assert_eq!(escape_dot("a\nb\nc"), "a\\nb\\nc");
1676    }
1677
1678    #[test]
1679    fn test_escape_dot_backslashes() {
1680        assert_eq!(escape_dot("path\\to\\file"), "path\\\\to\\\\file");
1681    }
1682
1683    #[test]
1684    fn test_escape_d2_basic() {
1685        assert_eq!(escape_d2("hello"), "hello");
1686        assert_eq!(escape_d2("hello world"), "hello world");
1687    }
1688
1689    #[test]
1690    fn test_escape_d2_quotes_and_newlines() {
1691        // D2 escape only handles \, ", and newlines
1692        assert_eq!(escape_d2("say \"hi\""), "say \\\"hi\\\"");
1693        assert_eq!(escape_d2("line1\nline2"), "line1 line2");
1694        assert_eq!(escape_d2("path\\to\\file"), "path\\\\to\\\\file");
1695    }
1696
1697    // ===== Config builder tests =====
1698
1699    #[test]
1700    fn test_dot_config_default() {
1701        let config = DotConfig::default();
1702        assert_eq!(config.direction, Direction::LeftToRight);
1703        assert!(!config.highlight_cross_language);
1704        assert!(config.show_details); // Default is true
1705        assert!(config.show_edge_labels); // Default is true
1706        assert!(config.filter_node_ids.is_none());
1707        assert!(config.filter_languages.is_empty());
1708        assert!(config.filter_edges.is_empty());
1709        assert!(config.filter_files.is_empty());
1710    }
1711
1712    #[test]
1713    fn test_dot_config_builder() {
1714        let config = DotConfig::default()
1715            .with_direction(Direction::TopToBottom)
1716            .with_cross_language_highlight(true)
1717            .with_details(true);
1718        assert_eq!(config.direction, Direction::TopToBottom);
1719        assert!(config.highlight_cross_language);
1720        assert!(config.show_details);
1721
1722        // Verify with_filter_node_ids sets the field correctly
1723        let mut ids = HashSet::new();
1724        ids.insert(NodeId::new(0, 0));
1725        let config_with_filter = DotConfig::default().with_filter_node_ids(Some(ids.clone()));
1726        assert!(config_with_filter.filter_node_ids.is_some());
1727        assert_eq!(config_with_filter.filter_node_ids.as_ref().unwrap(), &ids);
1728
1729        let config_cleared = config_with_filter.with_filter_node_ids(None);
1730        assert!(config_cleared.filter_node_ids.is_none());
1731    }
1732
1733    #[test]
1734    fn test_d2_config_default() {
1735        let config = D2Config::default();
1736        assert_eq!(config.direction, Direction::LeftToRight);
1737        assert!(!config.highlight_cross_language);
1738        assert!(config.show_details); // Default is true
1739        assert!(config.show_edge_labels); // Default is true
1740        assert!(config.filter_node_ids.is_none());
1741        assert!(config.filter_languages.is_empty());
1742        assert!(config.filter_edges.is_empty());
1743    }
1744
1745    #[test]
1746    fn test_d2_config_builder() {
1747        let config = D2Config::default()
1748            .with_cross_language_highlight(true)
1749            .with_details(true)
1750            .with_edge_labels(true);
1751        assert!(config.highlight_cross_language);
1752        assert!(config.show_details);
1753        assert!(config.show_edge_labels);
1754
1755        // Verify with_filter_node_ids sets the field correctly
1756        let mut ids = HashSet::new();
1757        ids.insert(NodeId::new(0, 0));
1758        let config_with_filter = D2Config::default().with_filter_node_ids(Some(ids.clone()));
1759        assert!(config_with_filter.filter_node_ids.is_some());
1760        assert_eq!(config_with_filter.filter_node_ids.as_ref().unwrap(), &ids);
1761
1762        let config_cleared = config_with_filter.with_filter_node_ids(None);
1763        assert!(config_cleared.filter_node_ids.is_none());
1764    }
1765
1766    #[test]
1767    fn test_mermaid_config_default() {
1768        let config = MermaidConfig::default();
1769        assert_eq!(config.direction, Direction::LeftToRight);
1770        assert!(!config.highlight_cross_language);
1771        assert!(config.show_edge_labels); // Default is true
1772        assert!(config.filter_node_ids.is_none());
1773        assert!(config.filter_languages.is_empty());
1774        assert!(config.filter_edges.is_empty());
1775    }
1776
1777    #[test]
1778    fn test_mermaid_config_builder() {
1779        let config = MermaidConfig::default()
1780            .with_cross_language_highlight(true)
1781            .with_edge_labels(false);
1782        assert!(config.highlight_cross_language);
1783        assert!(!config.show_edge_labels);
1784
1785        // Verify with_filter_node_ids sets the field correctly
1786        let mut ids = HashSet::new();
1787        ids.insert(NodeId::new(0, 0));
1788        let config_with_filter = MermaidConfig::default().with_filter_node_ids(Some(ids.clone()));
1789        assert!(config_with_filter.filter_node_ids.is_some());
1790        assert_eq!(config_with_filter.filter_node_ids.as_ref().unwrap(), &ids);
1791
1792        let config_cleared = config_with_filter.with_filter_node_ids(None);
1793        assert!(config_cleared.filter_node_ids.is_none());
1794    }
1795
1796    #[test]
1797    fn test_json_config_builder() {
1798        let config = JsonConfig::default()
1799            .with_details(true)
1800            .with_edge_metadata(true);
1801        assert!(config.include_details);
1802        assert!(config.include_edge_metadata);
1803    }
1804
1805    // ============================================================================
1806    // Exporter tests with test graph
1807    // ============================================================================
1808
1809    use crate::graph::unified::concurrent::CodeGraph;
1810    use crate::graph::unified::edge::BidirectionalEdgeStore;
1811    use crate::graph::unified::storage::NodeEntry;
1812    use crate::graph::unified::storage::arena::NodeArena;
1813    use crate::graph::unified::storage::indices::AuxiliaryIndices;
1814    use crate::graph::unified::storage::interner::StringInterner;
1815    use crate::graph::unified::storage::registry::FileRegistry;
1816    use std::path::Path;
1817
1818    /// Create a minimal test graph with nodes and edges for exporter testing.
1819    fn create_test_graph_for_export() -> CodeGraph {
1820        let mut nodes = NodeArena::new();
1821        let mut strings = StringInterner::new();
1822        let mut files = FileRegistry::new();
1823        let edges = BidirectionalEdgeStore::new();
1824        let indices = AuxiliaryIndices::new();
1825
1826        // Register file with language
1827        let file_id = files
1828            .register_with_language(Path::new("src/main.rs"), Some(Language::Rust))
1829            .unwrap();
1830
1831        // Intern strings
1832        let name_main = strings.intern("main").unwrap();
1833        let name_helper = strings.intern("helper").unwrap();
1834        let qname_main = strings.intern("app::main").unwrap();
1835        let qname_helper = strings.intern("app::helper").unwrap();
1836        let sig = strings.intern("fn main()").unwrap();
1837
1838        // Add nodes
1839        let main_entry = NodeEntry {
1840            kind: NodeKind::Function,
1841            name: name_main,
1842            file: file_id,
1843            start_byte: 0,
1844            end_byte: 100,
1845            start_line: 1,
1846            start_column: 0,
1847            end_line: 10,
1848            end_column: 1,
1849            signature: Some(sig),
1850            doc: None,
1851            qualified_name: Some(qname_main),
1852            visibility: None,
1853            is_async: false,
1854            is_static: false,
1855            is_unsafe: false,
1856            body_hash: None,
1857        };
1858        let main_id = nodes.alloc(main_entry).unwrap();
1859
1860        let helper_entry = NodeEntry {
1861            kind: NodeKind::Function,
1862            name: name_helper,
1863            file: file_id,
1864            start_byte: 100,
1865            end_byte: 200,
1866            start_line: 11,
1867            start_column: 0,
1868            end_line: 20,
1869            end_column: 1,
1870            signature: None,
1871            doc: None,
1872            qualified_name: Some(qname_helper),
1873            visibility: None,
1874            is_async: true,
1875            is_static: false,
1876            is_unsafe: false,
1877            body_hash: None,
1878        };
1879        let helper_id = nodes.alloc(helper_entry).unwrap();
1880
1881        // Add call edge: main -> helper
1882        edges.add_edge(
1883            main_id,
1884            helper_id,
1885            EdgeKind::Calls {
1886                argument_count: 2,
1887                is_async: false,
1888                resolved_via: ResolvedVia::Direct,
1889            },
1890            file_id,
1891        );
1892
1893        CodeGraph::from_components(
1894            nodes,
1895            edges,
1896            strings,
1897            files,
1898            indices,
1899            crate::graph::unified::NodeMetadataStore::new(),
1900        )
1901    }
1902
1903    // ===== DOT Exporter tests =====
1904
1905    #[test]
1906    fn test_unified_dot_exporter_basic() {
1907        let graph = create_test_graph_for_export();
1908        let snapshot = graph.snapshot();
1909        let exporter = UnifiedDotExporter::new(&snapshot);
1910        let output = exporter.export();
1911
1912        // Verify DOT structure
1913        assert!(output.starts_with("digraph CodeGraph {"));
1914        assert!(output.ends_with("}\n"));
1915        assert!(output.contains("rankdir=LR"));
1916    }
1917
1918    #[test]
1919    fn test_unified_dot_exporter_with_config() {
1920        let graph = create_test_graph_for_export();
1921        let snapshot = graph.snapshot();
1922        let config = DotConfig::default()
1923            .with_direction(Direction::TopToBottom)
1924            .with_cross_language_highlight(true)
1925            .with_details(true);
1926        let exporter = UnifiedDotExporter::with_config(&snapshot, config);
1927        let output = exporter.export();
1928
1929        assert!(output.contains("rankdir=TB"));
1930    }
1931
1932    #[test]
1933    fn test_unified_dot_exporter_contains_nodes() {
1934        let graph = create_test_graph_for_export();
1935        let snapshot = graph.snapshot();
1936        let exporter = UnifiedDotExporter::new(&snapshot);
1937        let output = exporter.export();
1938
1939        // Should contain node definitions
1940        assert!(output.contains("n0"), "Should contain first node");
1941        assert!(output.contains("n1"), "Should contain second node");
1942        // Should contain node labels
1943        assert!(
1944            output.contains("main") || output.contains("app::main"),
1945            "Should contain main function name"
1946        );
1947    }
1948
1949    #[test]
1950    fn test_unified_dot_exporter_contains_edges() {
1951        let graph = create_test_graph_for_export();
1952        let snapshot = graph.snapshot();
1953        let exporter = UnifiedDotExporter::new(&snapshot);
1954        let output = exporter.export();
1955
1956        // Should contain edge definitions (n0 -> n1 format)
1957        assert!(output.contains("->"), "Should contain edge arrow");
1958    }
1959
1960    #[test]
1961    fn test_unified_dot_exporter_empty_graph() {
1962        let graph = CodeGraph::new();
1963        let snapshot = graph.snapshot();
1964        let exporter = UnifiedDotExporter::new(&snapshot);
1965        let output = exporter.export();
1966
1967        assert!(output.starts_with("digraph CodeGraph {"));
1968        assert!(output.ends_with("}\n"));
1969        // Empty graph should have no node definitions
1970        assert!(!output.contains("n0"));
1971    }
1972
1973    // ===== D2 Exporter tests =====
1974
1975    #[test]
1976    fn test_unified_d2_exporter_basic() {
1977        let graph = create_test_graph_for_export();
1978        let snapshot = graph.snapshot();
1979        let exporter = UnifiedD2Exporter::new(&snapshot);
1980        let output = exporter.export();
1981
1982        // Verify D2 structure
1983        assert!(output.contains("direction: LR"));
1984    }
1985
1986    #[test]
1987    fn test_unified_d2_exporter_with_config() {
1988        let graph = create_test_graph_for_export();
1989        let snapshot = graph.snapshot();
1990        let config = D2Config::default().with_cross_language_highlight(true);
1991        let exporter = UnifiedD2Exporter::with_config(&snapshot, config);
1992        let output = exporter.export();
1993
1994        assert!(output.contains("direction:"));
1995    }
1996
1997    #[test]
1998    fn test_unified_d2_exporter_contains_nodes() {
1999        let graph = create_test_graph_for_export();
2000        let snapshot = graph.snapshot();
2001        let exporter = UnifiedD2Exporter::new(&snapshot);
2002        let output = exporter.export();
2003
2004        // D2 nodes are defined with key: "label" { style }
2005        assert!(
2006            output.contains("n0:"),
2007            "Should contain first node definition"
2008        );
2009        assert!(
2010            output.contains("n1:"),
2011            "Should contain second node definition"
2012        );
2013    }
2014
2015    #[test]
2016    fn test_unified_d2_exporter_contains_edges() {
2017        let graph = create_test_graph_for_export();
2018        let snapshot = graph.snapshot();
2019        let exporter = UnifiedD2Exporter::new(&snapshot);
2020        let output = exporter.export();
2021
2022        // D2 edges use -> or <-> format
2023        assert!(
2024            output.contains("->") || output.contains("<->"),
2025            "Should contain edge"
2026        );
2027    }
2028
2029    // ===== Mermaid Exporter tests =====
2030
2031    #[test]
2032    fn test_unified_mermaid_exporter_basic() {
2033        let graph = create_test_graph_for_export();
2034        let snapshot = graph.snapshot();
2035        let exporter = UnifiedMermaidExporter::new(&snapshot);
2036        let output = exporter.export();
2037
2038        // Verify Mermaid structure
2039        assert!(output.starts_with("graph LR"));
2040    }
2041
2042    #[test]
2043    fn test_unified_mermaid_exporter_with_config() {
2044        let graph = create_test_graph_for_export();
2045        let snapshot = graph.snapshot();
2046        let config = MermaidConfig::default()
2047            .with_cross_language_highlight(true)
2048            .with_edge_labels(false);
2049        let exporter = UnifiedMermaidExporter::with_config(&snapshot, config);
2050        let output = exporter.export();
2051
2052        assert!(output.starts_with("graph LR"));
2053    }
2054
2055    #[test]
2056    fn test_unified_mermaid_exporter_contains_nodes() {
2057        let graph = create_test_graph_for_export();
2058        let snapshot = graph.snapshot();
2059        let exporter = UnifiedMermaidExporter::new(&snapshot);
2060        let output = exporter.export();
2061
2062        // Mermaid nodes use node[label] or node["label"] format
2063        assert!(output.contains("n0"), "Should contain first node");
2064        assert!(output.contains("n1"), "Should contain second node");
2065    }
2066
2067    #[test]
2068    fn test_unified_mermaid_exporter_contains_edges() {
2069        let graph = create_test_graph_for_export();
2070        let snapshot = graph.snapshot();
2071        let exporter = UnifiedMermaidExporter::new(&snapshot);
2072        let output = exporter.export();
2073
2074        // Mermaid edges use -->, ==>, or -.->
2075        assert!(
2076            output.contains("-->") || output.contains("==>") || output.contains("-.->"),
2077            "Should contain edge"
2078        );
2079    }
2080
2081    // ===== JSON Exporter tests =====
2082
2083    #[test]
2084    fn test_unified_json_exporter_basic() {
2085        let graph = create_test_graph_for_export();
2086        let snapshot = graph.snapshot();
2087        let exporter = UnifiedJsonExporter::new(&snapshot);
2088        let output = exporter.export();
2089
2090        // Verify JSON structure
2091        assert!(output.is_object());
2092        assert!(output.get("nodes").is_some());
2093        assert!(output.get("edges").is_some());
2094        assert!(output.get("metadata").is_some());
2095    }
2096
2097    #[test]
2098    fn test_unified_json_exporter_node_count() {
2099        let graph = create_test_graph_for_export();
2100        let snapshot = graph.snapshot();
2101        let exporter = UnifiedJsonExporter::new(&snapshot);
2102        let output = exporter.export();
2103
2104        let nodes = output.get("nodes").unwrap().as_array().unwrap();
2105        assert_eq!(nodes.len(), 2, "Should have 2 nodes");
2106    }
2107
2108    #[test]
2109    fn test_unified_json_exporter_edge_count() {
2110        let graph = create_test_graph_for_export();
2111        let snapshot = graph.snapshot();
2112        let exporter = UnifiedJsonExporter::new(&snapshot);
2113        let output = exporter.export();
2114
2115        let edges = output.get("edges").unwrap().as_array().unwrap();
2116        assert_eq!(edges.len(), 1, "Should have 1 edge");
2117    }
2118
2119    #[test]
2120    fn test_unified_json_exporter_metadata() {
2121        let graph = create_test_graph_for_export();
2122        let snapshot = graph.snapshot();
2123        let exporter = UnifiedJsonExporter::new(&snapshot);
2124        let output = exporter.export();
2125
2126        let metadata = output.get("metadata").unwrap();
2127        assert_eq!(
2128            metadata.get("node_count").unwrap().as_u64().unwrap(),
2129            2,
2130            "Metadata should report 2 nodes"
2131        );
2132        assert_eq!(
2133            metadata.get("edge_count").unwrap().as_u64().unwrap(),
2134            1,
2135            "Metadata should report 1 edge"
2136        );
2137    }
2138
2139    #[test]
2140    fn test_unified_json_exporter_with_details() {
2141        let graph = create_test_graph_for_export();
2142        let snapshot = graph.snapshot();
2143        let config = JsonConfig::default().with_details(true);
2144        let exporter = UnifiedJsonExporter::with_config(&snapshot, config);
2145        let output = exporter.export();
2146
2147        let nodes = output.get("nodes").unwrap().as_array().unwrap();
2148        // First node (main) has a signature
2149        let main_node = &nodes[0];
2150        assert!(
2151            main_node.get("signature").is_some(),
2152            "Node should have signature when details enabled"
2153        );
2154    }
2155
2156    #[test]
2157    fn test_unified_json_exporter_with_edge_metadata() {
2158        let graph = create_test_graph_for_export();
2159        let snapshot = graph.snapshot();
2160        let config = JsonConfig::default().with_edge_metadata(true);
2161        let exporter = UnifiedJsonExporter::with_config(&snapshot, config);
2162        let output = exporter.export();
2163
2164        let edges = output.get("edges").unwrap().as_array().unwrap();
2165        let edge = &edges[0];
2166        // Call edge should have argument_count when metadata enabled
2167        assert!(
2168            edge.get("argument_count").is_some(),
2169            "Edge should have argument_count metadata"
2170        );
2171    }
2172
2173    #[test]
2174    fn test_unified_json_exporter_empty_graph() {
2175        let graph = CodeGraph::new();
2176        let snapshot = graph.snapshot();
2177        let exporter = UnifiedJsonExporter::new(&snapshot);
2178        let output = exporter.export();
2179
2180        let nodes = output.get("nodes").unwrap().as_array().unwrap();
2181        let edges = output.get("edges").unwrap().as_array().unwrap();
2182        assert!(nodes.is_empty(), "Empty graph should have no nodes");
2183        assert!(edges.is_empty(), "Empty graph should have no edges");
2184    }
2185
2186    // ===== edge_label function tests =====
2187
2188    #[test]
2189    fn test_edge_label_calls() {
2190        let strings = StringInterner::new();
2191        let label = edge_label(
2192            &EdgeKind::Calls {
2193                argument_count: 3,
2194                is_async: false,
2195                resolved_via: ResolvedVia::Direct,
2196            },
2197            &strings,
2198        );
2199        assert_eq!(label, "call(3)");
2200    }
2201
2202    #[test]
2203    fn test_edge_label_async_calls() {
2204        let strings = StringInterner::new();
2205        let label = edge_label(
2206            &EdgeKind::Calls {
2207                argument_count: 2,
2208                is_async: true,
2209                resolved_via: ResolvedVia::Direct,
2210            },
2211            &strings,
2212        );
2213        assert_eq!(label, "async call(2)");
2214    }
2215
2216    #[test]
2217    fn test_edge_label_imports_simple() {
2218        let strings = StringInterner::new();
2219        let label = edge_label(
2220            &EdgeKind::Imports {
2221                alias: None,
2222                is_wildcard: false,
2223            },
2224            &strings,
2225        );
2226        assert_eq!(label, "import");
2227    }
2228
2229    #[test]
2230    fn test_edge_label_imports_wildcard() {
2231        let strings = StringInterner::new();
2232        let label = edge_label(
2233            &EdgeKind::Imports {
2234                alias: None,
2235                is_wildcard: true,
2236            },
2237            &strings,
2238        );
2239        assert_eq!(label, "import *");
2240    }
2241
2242    #[test]
2243    fn test_edge_label_references() {
2244        let strings = StringInterner::new();
2245        let label = edge_label(&EdgeKind::References, &strings);
2246        assert_eq!(label, "ref");
2247    }
2248
2249    #[test]
2250    fn test_edge_label_inherits() {
2251        let strings = StringInterner::new();
2252        let label = edge_label(&EdgeKind::Inherits, &strings);
2253        assert_eq!(label, "extends");
2254    }
2255
2256    #[test]
2257    fn test_edge_label_implements() {
2258        let strings = StringInterner::new();
2259        let label = edge_label(&EdgeKind::Implements, &strings);
2260        assert_eq!(label, "implements");
2261    }
2262
2263    // ===== MermaidConfig filter_node_ids tests =====
2264
2265    #[test]
2266    fn test_mermaid_filter_node_ids_restricts_output() {
2267        let graph = create_test_graph_for_export();
2268        let snapshot = graph.snapshot();
2269
2270        // Collect nodes in iteration order so we can pick a specific one.
2271        let all_nodes: Vec<NodeId> = snapshot.iter_nodes().map(|(id, _)| id).collect();
2272        assert!(
2273            all_nodes.len() >= 2,
2274            "test graph must have at least 2 nodes"
2275        );
2276
2277        // Filter to contain only the first node in iteration order.
2278        let kept_id = all_nodes[0];
2279        let expected_key = format!("n{}", kept_id.index());
2280        // The excluded node key must NOT appear in the output.
2281        let excluded_key = format!("n{}", all_nodes[1].index());
2282
2283        let mut filter = HashSet::new();
2284        filter.insert(kept_id);
2285
2286        let config = MermaidConfig::default().with_filter_node_ids(Some(filter));
2287        let exporter = UnifiedMermaidExporter::with_config(&snapshot, config);
2288        let output = exporter.export();
2289
2290        // Collect all node-definition lines (lines that start with `nN[`).
2291        let node_defs: Vec<&str> = output
2292            .lines()
2293            .filter(|l| l.trim_start().starts_with('n') && l.contains('['))
2294            .collect();
2295
2296        assert_eq!(
2297            node_defs.len(),
2298            1,
2299            "filtered export should have exactly 1 node, got: {node_defs:?}"
2300        );
2301
2302        // The single emitted node must be the one we kept.
2303        assert!(
2304            node_defs[0].trim_start().starts_with(&expected_key),
2305            "expected node key '{expected_key}' but got: {}",
2306            node_defs[0]
2307        );
2308
2309        // The excluded node must not appear anywhere in the output.
2310        let excluded_present = output
2311            .lines()
2312            .any(|l| l.trim_start().starts_with(&excluded_key));
2313        assert!(
2314            !excluded_present,
2315            "excluded node key '{excluded_key}' must not appear in filtered output"
2316        );
2317
2318        // With only one visible node, no edges can exist between visible nodes.
2319        let edge_lines: Vec<&str> = output
2320            .lines()
2321            .filter(|l| l.contains("-->") || l.contains("---"))
2322            .collect();
2323        assert!(
2324            edge_lines.is_empty(),
2325            "no edges should appear when only one node is visible, got: {edge_lines:?}"
2326        );
2327    }
2328
2329    // ===== D2Config filter_node_ids tests =====
2330
2331    #[test]
2332    fn test_d2_filter_node_ids_restricts_output() {
2333        let graph = create_test_graph_for_export();
2334        let snapshot = graph.snapshot();
2335
2336        // Collect nodes in iteration order so we can pick a specific one.
2337        let all_nodes: Vec<NodeId> = snapshot.iter_nodes().map(|(id, _)| id).collect();
2338        assert!(
2339            all_nodes.len() >= 2,
2340            "test graph must have at least 2 nodes"
2341        );
2342
2343        // Filter to contain only the first node in iteration order.
2344        let kept_id = all_nodes[0];
2345        let expected_key = format!("n{}:", kept_id.index());
2346        // The excluded node key must NOT appear in the output.
2347        let excluded_key = format!("n{}:", all_nodes[1].index());
2348
2349        let mut filter = HashSet::new();
2350        filter.insert(kept_id);
2351
2352        let config = D2Config::default().with_filter_node_ids(Some(filter));
2353        let exporter = UnifiedD2Exporter::with_config(&snapshot, config);
2354        let output = exporter.export();
2355
2356        // D2 node definitions look like `nN: "label" {`
2357        let node_defs: Vec<&str> = output
2358            .lines()
2359            .filter(|l| {
2360                let trimmed = l.trim_start();
2361                (trimmed.starts_with('n') && trimmed.contains(": {"))
2362                    || (trimmed.starts_with('n') && trimmed.contains(": \""))
2363            })
2364            .collect();
2365
2366        assert_eq!(
2367            node_defs.len(),
2368            1,
2369            "filtered export should have exactly 1 node, got: {node_defs:?}"
2370        );
2371
2372        // The single emitted node must be the one we kept.
2373        assert!(
2374            node_defs[0].trim_start().starts_with(&expected_key),
2375            "expected node key '{expected_key}' but got: {}",
2376            node_defs[0]
2377        );
2378
2379        // The excluded node must not appear as a node definition in the output.
2380        let excluded_present = output
2381            .lines()
2382            .any(|l| l.trim_start().starts_with(&excluded_key));
2383        assert!(
2384            !excluded_present,
2385            "excluded node key '{excluded_key}' must not appear in filtered output"
2386        );
2387
2388        // With only one visible node, no edges can exist between visible nodes.
2389        let edge_lines: Vec<&str> = output
2390            .lines()
2391            .filter(|l| l.contains("->") || l.contains("<->"))
2392            .collect();
2393        assert!(
2394            edge_lines.is_empty(),
2395            "no edges should appear when only one node is visible, got: {edge_lines:?}"
2396        );
2397    }
2398
2399    // ===== DotConfig filter_node_ids tests =====
2400
2401    #[test]
2402    fn test_dot_filter_node_ids_restricts_output() {
2403        let graph = create_test_graph_for_export();
2404        let snapshot = graph.snapshot();
2405
2406        // Collect nodes in iteration order so we can pick a specific one.
2407        let all_nodes: Vec<NodeId> = snapshot.iter_nodes().map(|(id, _)| id).collect();
2408        assert!(
2409            all_nodes.len() >= 2,
2410            "test graph must have at least 2 nodes"
2411        );
2412
2413        // Filter to contain only the first node in iteration order.
2414        let kept_id = all_nodes[0];
2415        let expected_key = format!("\"n{}\"", kept_id.index());
2416        // The excluded node key must NOT appear in the output.
2417        let excluded_key = format!("\"n{}\"", all_nodes[1].index());
2418
2419        let mut filter = HashSet::new();
2420        filter.insert(kept_id);
2421
2422        let config = DotConfig::default().with_filter_node_ids(Some(filter));
2423        let exporter = UnifiedDotExporter::with_config(&snapshot, config);
2424        let output = exporter.export();
2425
2426        // DOT node definitions look like `  "nN" [label=...`
2427        let node_defs: Vec<&str> = output
2428            .lines()
2429            .filter(|l| {
2430                let trimmed = l.trim_start();
2431                trimmed.starts_with('"') && trimmed.contains("[label=")
2432            })
2433            .collect();
2434
2435        assert_eq!(
2436            node_defs.len(),
2437            1,
2438            "filtered export should have exactly 1 node, got: {node_defs:?}"
2439        );
2440
2441        // The single emitted node must be the one we kept.
2442        assert!(
2443            node_defs[0].trim_start().starts_with(&expected_key),
2444            "expected node key '{expected_key}' but got: {}",
2445            node_defs[0]
2446        );
2447
2448        // The excluded node must not appear as a definition in the output.
2449        let excluded_present = output
2450            .lines()
2451            .any(|l| l.trim_start().starts_with(&excluded_key) && l.contains("[label="));
2452        assert!(
2453            !excluded_present,
2454            "excluded node key '{excluded_key}' must not appear in filtered output"
2455        );
2456
2457        // With only one visible node, no edges can exist between visible nodes.
2458        let edge_lines: Vec<&str> = output.lines().filter(|l| l.contains("->")).collect();
2459        assert!(
2460            edge_lines.is_empty(),
2461            "no edges should appear when only one node is visible, got: {edge_lines:?}"
2462        );
2463    }
2464
2465    // ===== DotConfig filter tests =====
2466
2467    #[test]
2468    fn test_dot_config_filter_language() {
2469        let config = DotConfig::default().filter_language(Language::Rust);
2470        assert!(config.filter_languages.contains(&Language::Rust));
2471    }
2472
2473    #[test]
2474    fn test_dot_config_filter_edge() {
2475        let config = DotConfig::default().filter_edge(EdgeFilter::Calls);
2476        assert!(config.filter_edges.contains(&EdgeFilter::Calls));
2477    }
2478
2479    #[test]
2480    fn test_dot_config_with_max_depth() {
2481        let config = DotConfig::default().with_max_depth(5);
2482        assert_eq!(config.max_depth, Some(5));
2483    }
2484}