dotspace 0.3.0

Explore your Graphviz dot files in interactive 3D space
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
#![allow(clippy::cast_precision_loss)] // We accept precision loss for f32 conversions
#![allow(clippy::needless_pass_by_value)] // Bevy systems require owned Res parameters
#![allow(clippy::multiple_crate_versions)] // Bevy dependencies have multiple versions

use bevy::prelude::*;
use clap::Parser;
use petgraph::graph::DiGraph;
use std::collections::HashMap;
use std::io::{self, IsTerminal, Read};

#[derive(Parser, Debug)]
#[command(author, version, about = "Explore your Graphviz dot files in interactive 3D space", long_about = None)]
struct Args {
    /// Optional dot file path. If not provided, reads from stdin.
    file: Option<String>,

    /// Initial camera distance from center
    #[arg(short, long, default_value = "25.0")]
    distance: f32,

    /// Camera movement speed
    #[arg(short, long, default_value = "5.0")]
    speed: f32,
}

fn main() {
    let args = Args::parse();

    // Read dot content from file or stdin
    let dot_content = args.file.map_or_else(
        || {
            if io::stdin().is_terminal() {
                eprintln!("Error: No input provided. Either specify a file or pipe data to stdin.");
                eprintln!("Usage: dotspace [FILE] or command | dotspace");
                std::process::exit(1);
            } else {
                // Read from stdin if it's piped
                let mut buffer = String::new();
                io::stdin().read_to_string(&mut buffer).unwrap_or_else(|e| {
                    eprintln!("Error reading from stdin: {e}");
                    std::process::exit(1);
                });
                buffer
            }
        },
        |filename| {
            std::fs::read_to_string(&filename).unwrap_or_else(|e| {
                eprintln!("Error reading file '{filename}': {e}");
                std::process::exit(1);
            })
        },
    );

    App::new()
        .add_plugins(DefaultPlugins)
        .insert_resource(DotContent(dot_content))
        .insert_resource(CameraConfig {
            initial_distance: args.distance,
            speed: args.speed,
        })
        .add_systems(Startup, setup)
        .add_systems(Update, (camera_controls, update_node_labels, exit_on_key))
        .run();
}

#[derive(Resource)]
struct DotContent(String);

#[derive(Resource)]
struct CameraConfig {
    initial_distance: f32,
    speed: f32,
}

#[derive(Clone, Debug)]
struct NodeInfo {
    label: String,
    node_type: NodeType,
    level: u32,
}

#[derive(Clone, Debug, PartialEq)]
enum NodeType {
    Organization,
    LineOfBusiness,
    Site,
    Team,
    User,
    Default,
}

#[derive(Resource)]
struct GraphData {
    graph: DiGraph<NodeInfo, ()>,
    //node_map: HashMap<String, NodeIndex>,
}

fn spawn_edge(
    commands: &mut Commands,
    meshes: &mut ResMut<Assets<Mesh>>,
    material: Handle<StandardMaterial>,
    from: Vec3,
    to: Vec3,
) {
    let direction = to - from;
    let distance = direction.length();
    let midpoint = from + direction * 0.5;

    // Calculate rotation to align cylinder with edge direction
    let up = Vec3::Y;
    let rotation = Quat::from_rotation_arc(up, direction.normalize());

    // Create a cylinder to represent the edge
    commands.spawn((
        Mesh3d(meshes.add(Cylinder::new(0.02, distance))),
        MeshMaterial3d(material),
        Transform::from_translation(midpoint).with_rotation(rotation),
    ));
}

fn parse_dot_file(content: &str) -> GraphData {
    // For now, let's use a simple parser that extracts basic info
    let mut graph = DiGraph::new();
    let mut node_map = HashMap::new();
    let mut node_attributes = HashMap::new();

    // Parse nodes with attributes
    let lines: Vec<&str> = content.lines().collect();
    for line in &lines {
        let trimmed = line.trim();

        // Parse node definitions with attributes
        if trimmed.contains('[') && trimmed.contains(']') && !trimmed.contains("->") {
            if let Some(node_end) = trimmed.find('[') {
                let node_id = trimmed[..node_end].trim().trim_matches('"');

                // Extract attributes
                let attrs_str = &trimmed[node_end + 1..trimmed.rfind(']').unwrap_or(trimmed.len())];
                let mut node_type = NodeType::Default;
                let mut level = 0u32;

                // Parse attributes
                for attr in attrs_str.split(',') {
                    let parts: Vec<&str> = attr.split('=').collect();
                    if parts.len() == 2 {
                        let key = parts[0].trim();
                        let value = parts[1].trim().trim_matches('"');

                        match key {
                            "type" => {
                                node_type = match value {
                                    "organization" => NodeType::Organization,
                                    "lob" => NodeType::LineOfBusiness,
                                    "site" => NodeType::Site,
                                    "team" => NodeType::Team,
                                    "user" => NodeType::User,
                                    _ => NodeType::Default,
                                };
                            }
                            "level" => {
                                level = value.parse().unwrap_or(0);
                            }
                            _ => {}
                        }
                    }
                }

                node_attributes.insert(node_id.to_string(), (node_type, level));
            }
        }
    }

    // Parse edges and create nodes
    for line in &lines {
        let trimmed = line.trim();
        if trimmed.contains("->") {
            // Remove comments
            let edge_line = trimmed
                .find("//")
                .map_or(trimmed, |comment_pos| &trimmed[..comment_pos]);

            let parts: Vec<&str> = edge_line.split("->").collect();
            if parts.len() >= 2 {
                let from = parts[0].trim().trim_matches('"');
                let to_part = parts[1].trim();
                let to = to_part.find('[').map_or_else(
                    || to_part.trim_end_matches(';').trim().trim_matches('"'),
                    |bracket_pos| {
                        to_part[..bracket_pos]
                            .trim()
                            .trim_matches('"')
                            .trim_end_matches(';')
                    },
                );

                // Ensure nodes exist
                let from_idx = *node_map.entry(from.to_string()).or_insert_with(|| {
                    let (node_type, level) = node_attributes
                        .get(from)
                        .cloned()
                        .unwrap_or((NodeType::Default, 0));
                    graph.add_node(NodeInfo {
                        label: from.to_string(),
                        node_type,
                        level,
                    })
                });

                let to_idx = *node_map.entry(to.to_string()).or_insert_with(|| {
                    let (node_type, level) = node_attributes
                        .get(to)
                        .cloned()
                        .unwrap_or((NodeType::Default, 0));
                    graph.add_node(NodeInfo {
                        label: to.to_string(),
                        node_type,
                        level,
                    })
                });

                graph.add_edge(from_idx, to_idx, ());
            }
        }
    }

    //GraphData { graph, node_map }
    GraphData { graph }
}

fn get_node_appearance(node_type: &NodeType) -> (Color, f32) {
    // Returns (color, size_multiplier)
    match node_type {
        NodeType::Organization => (Color::srgb(0.8, 0.2, 0.2), 1.5), // Red, large
        NodeType::LineOfBusiness => (Color::srgb(0.8, 0.5, 0.2), 1.2), // Orange
        NodeType::Site => (Color::srgb(0.2, 0.6, 0.8), 1.0),         // Blue
        NodeType::Team => (Color::srgb(0.2, 0.8, 0.5), 0.8),         // Green
        NodeType::User => (Color::srgb(0.6, 0.4, 0.8), 0.6),         // Purple, small
        NodeType::Default => (Color::srgb(0.5, 0.5, 0.5), 0.7),      // Gray
    }
}

fn setup_camera(commands: &mut Commands, camera_config: &Res<CameraConfig>) {
    let controller = CameraController {
        distance: camera_config.initial_distance,
        speed: camera_config.speed,
        ..Default::default()
    };

    // Calculate initial position based on orbit angles and distance
    let horizontal_distance = controller.distance * controller.pitch_angle.cos();
    let x = horizontal_distance * controller.orbit_angle.cos();
    let y = controller
        .distance
        .mul_add(controller.pitch_angle.sin(), controller.look_at.y);
    let z = horizontal_distance * controller.orbit_angle.sin();

    commands.spawn((
        Camera3d::default(),
        Transform::from_xyz(x, y, z).looking_at(controller.look_at, Vec3::Y),
        controller,
    ));
}

fn setup(
    mut commands: Commands,
    mut meshes: ResMut<Assets<Mesh>>,
    mut materials: ResMut<Assets<StandardMaterial>>,
    dot_content: Res<DotContent>,
    camera_config: Res<CameraConfig>,
) {
    // Parse the dot content
    let graph_data = parse_dot_file(&dot_content.0);

    // Setup camera
    setup_camera(&mut commands, &camera_config);

    // Light
    commands.spawn((
        DirectionalLight {
            illuminance: 10000.0,
            ..default()
        },
        Transform::from_rotation(Quat::from_euler(EulerRot::XYZ, -0.5, -0.5, 0.0)),
    ));

    // Ground plane for reference
    commands.spawn((
        Mesh3d(meshes.add(Plane3d::default().mesh().size(20.0, 20.0))),
        MeshMaterial3d(materials.add(StandardMaterial {
            base_color: Color::srgb(0.3, 0.2, 0.2),
            ..default()
        })),
    ));

    // Create nodes and edges
    create_graph_visualization(&mut commands, &mut meshes, &mut materials, &graph_data);

    // Store graph data as a resource for later use
    commands.insert_resource(graph_data);

    // Add control instructions
    commands.spawn((
        Text::new("Controls:\nArrows: Move\nShift+Arrows: Rotate\n+/- : Zoom\nESC/Q: Exit"),
        TextFont {
            font_size: 16.0,
            ..default()
        },
        TextColor(Color::WHITE),
        Node {
            position_type: PositionType::Absolute,
            top: Val::Px(10.0),
            left: Val::Px(10.0),
            ..default()
        },
    ));
}

fn create_graph_visualization(
    commands: &mut Commands,
    meshes: &mut ResMut<Assets<Mesh>>,
    materials: &mut ResMut<Assets<StandardMaterial>>,
    graph_data: &GraphData,
) {
    // Create 3D nodes from the graph with hierarchical layout
    let mut level_counts = HashMap::new();
    let mut level_indices = HashMap::new();

    // Count nodes at each level
    for node_idx in graph_data.graph.node_indices() {
        let node_info = &graph_data.graph[node_idx];
        *level_counts.entry(node_info.level).or_insert(0) += 1;
    }

    // Create nodes with proper positioning
    for node_idx in graph_data.graph.node_indices() {
        let node_info = &graph_data.graph[node_idx];
        let (color, size_mult) = get_node_appearance(&node_info.node_type);

        // Get current index at this level
        let level_idx = level_indices.entry(node_info.level).or_insert(0);
        let count_at_level = level_counts[&node_info.level];

        // Calculate position with hierarchical layout
        let level_radius = (node_info.level as f32).mul_add(2.0, 5.0);
        let angle = 2.0 * std::f32::consts::PI * (*level_idx as f32) / count_at_level as f32;
        let x = level_radius * angle.cos();
        let z = level_radius * angle.sin();
        let y = node_info.level as f32 * 2.0; // Vertical spacing by level

        *level_idx += 1;

        // Create material for this node type
        let node_material = materials.add(StandardMaterial {
            base_color: color,
            ..default()
        });

        // Create mesh based on node type
        let mesh = match node_info.node_type {
            NodeType::Organization => meshes.add(Cuboid::new(1.0, 1.0, 1.0)), // Cube
            NodeType::LineOfBusiness => meshes.add(Cylinder::new(0.5, 1.0)),  // Cylinder
            NodeType::Site => meshes.add(Torus::new(0.3, 0.5)),               // Torus
            NodeType::Team | NodeType::Default => meshes.add(Sphere::new(0.5)), // Sphere
            NodeType::User => meshes.add(Capsule3d::new(0.3, 0.4)),           // Capsule
        };

        // Spawn node with appropriate shape
        let node_entity = commands
            .spawn((
                Mesh3d(mesh),
                MeshMaterial3d(node_material),
                Transform::from_xyz(x, y, z).with_scale(Vec3::splat(size_mult)),
                GraphNode,
            ))
            .id();

        // Store the label in the Name component
        commands
            .entity(node_entity)
            .insert(Name::new(node_info.label.clone()));

        // Create a UI text element for this node
        let label_entity = commands
            .spawn((
                Text::new(node_info.label.clone()),
                TextFont {
                    font_size: 20.0,
                    ..default()
                },
                TextColor(Color::WHITE),
                Node {
                    position_type: PositionType::Absolute,
                    ..default()
                },
                NodeLabel {
                    offset: Vec3::new(0.0, 1.0, 0.0),
                },
            ))
            .id();

        // Link the label to the node
        commands
            .entity(node_entity)
            .insert(LabelEntity(label_entity));
    }

    // Create edges between nodes
    let edge_material = materials.add(StandardMaterial {
        base_color: Color::srgb(0.7, 0.7, 0.7),
        unlit: true,
        ..default()
    });

    // Reset level indices for edge position calculation
    level_indices.clear();

    // Get node positions for edge creation
    let mut node_positions = HashMap::new();
    for node_idx in graph_data.graph.node_indices() {
        let node_info = &graph_data.graph[node_idx];
        let level_idx = level_indices.entry(node_info.level).or_insert(0);
        let count_at_level = level_counts[&node_info.level];

        let level_radius = (node_info.level as f32).mul_add(2.0, 5.0);
        let angle = 2.0 * std::f32::consts::PI * (*level_idx as f32) / count_at_level as f32;
        let x = level_radius * angle.cos();
        let z = level_radius * angle.sin();
        let y = node_info.level as f32 * 2.0;

        *level_idx += 1;
        node_positions.insert(node_idx, Vec3::new(x, y, z));
    }

    // Create edges
    for edge in graph_data.graph.edge_indices() {
        if let Some((from_idx, to_idx)) = graph_data.graph.edge_endpoints(edge) {
            if let (Some(&from_pos), Some(&to_pos)) =
                (node_positions.get(&from_idx), node_positions.get(&to_idx))
            {
                spawn_edge(commands, meshes, edge_material.clone(), from_pos, to_pos);
            }
        }
    }
}

#[derive(Component)]
struct CameraController {
    speed: f32,
    rotation_speed: f32,
    look_at: Vec3,
    distance: f32,
    orbit_angle: f32,
    pitch_angle: f32,
}

#[derive(Component)]
struct GraphNode;

#[derive(Component)]
struct NodeLabel {
    offset: Vec3,
}

#[derive(Component)]
struct LabelEntity(Entity);

impl Default for CameraController {
    fn default() -> Self {
        Self {
            speed: 5.0,
            rotation_speed: 1.0,
            look_at: Vec3::new(0.0, 4.0, 0.0), // Center of hierarchy
            distance: 25.0,
            orbit_angle: std::f32::consts::PI / 4.0, // 45 degrees
            pitch_angle: std::f32::consts::PI / 6.0, // 30 degrees
        }
    }
}

fn camera_controls(
    keyboard_input: Res<ButtonInput<KeyCode>>,
    time: Res<Time>,
    mut query: Query<(&mut Transform, &mut CameraController)>,
) {
    for (mut transform, mut controller) in &mut query {
        let shift = keyboard_input.pressed(KeyCode::ShiftLeft)
            || keyboard_input.pressed(KeyCode::ShiftRight);

        // Zoom controls - multiple options for Mac compatibility
        if keyboard_input.pressed(KeyCode::PageUp)
            || keyboard_input.pressed(KeyCode::Equal)  // Plus key
            || keyboard_input.pressed(KeyCode::NumpadAdd)
        {
            controller.distance = controller
                .speed
                .mul_add(-time.delta_secs(), controller.distance)
                .max(5.0);
        }
        if keyboard_input.pressed(KeyCode::PageDown)
            || keyboard_input.pressed(KeyCode::Minus)
            || keyboard_input.pressed(KeyCode::NumpadSubtract)
        {
            controller.distance = controller
                .speed
                .mul_add(time.delta_secs(), controller.distance)
                .min(50.0);
        }

        if shift {
            // Rotation mode - orbit around the look_at point
            if keyboard_input.pressed(KeyCode::ArrowLeft) {
                controller.orbit_angle += controller.rotation_speed * time.delta_secs();
            }
            if keyboard_input.pressed(KeyCode::ArrowRight) {
                controller.orbit_angle -= controller.rotation_speed * time.delta_secs();
            }
            if keyboard_input.pressed(KeyCode::ArrowUp) {
                controller.pitch_angle = controller
                    .rotation_speed
                    .mul_add(-time.delta_secs(), controller.pitch_angle)
                    .clamp(-std::f32::consts::PI / 3.0, std::f32::consts::PI / 3.0);
                // Limit to +/- 60 degrees
            }
            if keyboard_input.pressed(KeyCode::ArrowDown) {
                controller.pitch_angle = controller
                    .rotation_speed
                    .mul_add(time.delta_secs(), controller.pitch_angle)
                    .clamp(-std::f32::consts::PI / 3.0, std::f32::consts::PI / 3.0);
            }

            // Update camera position based on orbit angles
            let horizontal_distance = controller.distance * controller.pitch_angle.cos();
            let x = horizontal_distance * controller.orbit_angle.cos();
            let y = controller
                .distance
                .mul_add(controller.pitch_angle.sin(), controller.look_at.y);
            let z = horizontal_distance * controller.orbit_angle.sin();

            transform.translation = controller.look_at + Vec3::new(x, y, z);
            transform.look_at(controller.look_at, Vec3::Y);
        } else {
            // Movement mode - move the look_at point
            let mut movement = Vec3::ZERO;
            let forward = transform.forward();
            let right = transform.right();

            if keyboard_input.pressed(KeyCode::ArrowUp) {
                movement += Vec3::new(forward.x, 0.0, forward.z).normalize();
            }
            if keyboard_input.pressed(KeyCode::ArrowDown) {
                movement -= Vec3::new(forward.x, 0.0, forward.z).normalize();
            }
            if keyboard_input.pressed(KeyCode::ArrowLeft) {
                movement -= Vec3::new(right.x, 0.0, right.z).normalize();
            }
            if keyboard_input.pressed(KeyCode::ArrowRight) {
                movement += Vec3::new(right.x, 0.0, right.z).normalize();
            }

            if movement.length() > 0.0 {
                movement = movement.normalize() * controller.speed * time.delta_secs();
                controller.look_at += movement;
                transform.translation += movement;
            }
        }

        // Always update camera position after zoom changes
        if keyboard_input.pressed(KeyCode::PageUp)
            || keyboard_input.pressed(KeyCode::PageDown)
            || keyboard_input.pressed(KeyCode::Equal)
            || keyboard_input.pressed(KeyCode::Minus)
            || keyboard_input.pressed(KeyCode::NumpadAdd)
            || keyboard_input.pressed(KeyCode::NumpadSubtract)
        {
            let horizontal_distance = controller.distance * controller.pitch_angle.cos();
            let x = horizontal_distance * controller.orbit_angle.cos();
            let y = controller
                .distance
                .mul_add(controller.pitch_angle.sin(), controller.look_at.y);
            let z = horizontal_distance * controller.orbit_angle.sin();

            transform.translation = controller.look_at + Vec3::new(x, y, z);
            transform.look_at(controller.look_at, Vec3::Y);
        }
    }
}

fn update_node_labels(
    nodes: Query<(&GlobalTransform, &LabelEntity), With<GraphNode>>,
    mut labels: Query<(&mut Node, &NodeLabel)>,
    camera_query: Query<(&Camera, &GlobalTransform), With<Camera3d>>,
) {
    if let Ok((camera, camera_transform)) = camera_query.single() {
        for (node_transform, label_entity) in &nodes {
            if let Ok((mut style, label)) = labels.get_mut(label_entity.0) {
                // Project 3D position to screen space
                let world_position = node_transform.translation() + label.offset;

                if let Ok(screen_pos) = camera.world_to_viewport(camera_transform, world_position) {
                    style.left = Val::Px(screen_pos.x);
                    style.top = Val::Px(screen_pos.y);
                }
            }
        }
    }
}

fn exit_on_key(keyboard_input: Res<ButtonInput<KeyCode>>, mut exit: EventWriter<AppExit>) {
    if keyboard_input.just_pressed(KeyCode::Escape) || keyboard_input.just_pressed(KeyCode::KeyQ) {
        exit.write(AppExit::Success);
    }
}

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

    #[test]
    fn test_parse_simple_graph() {
        let dot_content = r"
            digraph G {
                A -> B;
                B -> C;
            }
        ";

        let graph_data = parse_dot_file(dot_content);

        // Should have 3 nodes
        assert_eq!(graph_data.graph.node_count(), 3);
        // Should have 2 edges
        assert_eq!(graph_data.graph.edge_count(), 2);
    }

    #[test]
    fn test_parse_node_with_attributes() {
        let dot_content = r#"
            digraph G {
                "CEO" [type="organization", level="3"];
                "Manager" [type="team", level="1"];
                "CEO" -> "Manager";
            }
        "#;

        let graph_data = parse_dot_file(dot_content);

        // Check nodes were created with correct attributes
        let ceo_node = graph_data
            .graph
            .node_indices()
            .find(|&idx| graph_data.graph[idx].label == "CEO")
            .expect("CEO node not found");

        assert_eq!(graph_data.graph[ceo_node].node_type, NodeType::Organization);
        assert_eq!(graph_data.graph[ceo_node].level, 3);

        let manager_node = graph_data
            .graph
            .node_indices()
            .find(|&idx| graph_data.graph[idx].label == "Manager")
            .expect("Manager node not found");

        assert_eq!(graph_data.graph[manager_node].node_type, NodeType::Team);
        assert_eq!(graph_data.graph[manager_node].level, 1);
    }

    #[test]
    fn test_parse_nodes_without_attributes() {
        let dot_content = r#"
            digraph G {
                "NodeA";
                "NodeB";
                "NodeA" -> "NodeB";
            }
        "#;

        let graph_data = parse_dot_file(dot_content);

        // Nodes without attributes should have defaults
        for node_idx in graph_data.graph.node_indices() {
            let node = &graph_data.graph[node_idx];
            assert_eq!(node.node_type, NodeType::Default);
            assert_eq!(node.level, 0);
        }
    }

    #[test]
    fn test_parse_edge_with_style() {
        let dot_content = r#"
            digraph G {
                A -> B [style="dashed"];
                B -> C;
            }
        "#;

        let graph_data = parse_dot_file(dot_content);

        // Should parse edges even with style attributes
        assert_eq!(graph_data.graph.edge_count(), 2);
    }

    #[test]
    fn test_node_type_parsing() {
        let test_cases = vec![
            ("organization", NodeType::Organization),
            ("lob", NodeType::LineOfBusiness),
            ("site", NodeType::Site),
            ("team", NodeType::Team),
            ("user", NodeType::User),
            ("unknown", NodeType::Default),
        ];

        for (type_str, expected_type) in test_cases {
            let dot_content = format!(
                "digraph G {{\n  \"TestNode\" [type=\"{type_str}\"];\n  \"TestNode\" -> \"Dummy\";\n}}"
            );

            let graph_data = parse_dot_file(&dot_content);

            let test_node = graph_data
                .graph
                .node_indices()
                .find(|&idx| graph_data.graph[idx].label == "TestNode")
                .expect("TestNode not found");
            assert_eq!(graph_data.graph[test_node].node_type, expected_type);
        }
    }

    #[test]
    fn test_quoted_node_names() {
        let dot_content = r#"
            digraph G {
                "Node with spaces" [type="team"];
                "Another Node" [type="user"];
                "Node with spaces" -> "Another Node";
            }
        "#;

        let graph_data = parse_dot_file(dot_content);

        // Should handle quoted node names properly
        assert_eq!(graph_data.graph.node_count(), 2);
        assert_eq!(graph_data.graph.edge_count(), 1);

        // Check that quotes were removed from labels
        let labels: Vec<String> = graph_data
            .graph
            .node_indices()
            .map(|idx| graph_data.graph[idx].label.clone())
            .collect();

        assert!(labels.contains(&"Node with spaces".to_string()));
        assert!(labels.contains(&"Another Node".to_string()));
    }

    #[test]
    fn test_get_node_appearance() {
        // Test color and size for each node type
        let test_cases = vec![
            (NodeType::Organization, 1.5),
            (NodeType::LineOfBusiness, 1.2),
            (NodeType::Site, 1.0),
            (NodeType::Team, 0.8),
            (NodeType::User, 0.6),
            (NodeType::Default, 0.7),
        ];

        for (node_type, expected_size) in test_cases {
            let (color, size) = get_node_appearance(&node_type);
            assert!((size - expected_size).abs() < f32::EPSILON);
            // Just verify we got a color (specific values might change)
            assert!(color.to_srgba().red >= 0.0);
        }
    }

    #[test]
    fn test_complex_graph_parsing() {
        let dot_content = r#"
            digraph ComplexGraph {
                // Comments should be ignored
                "Root" [type="organization", level="2"];
                "Child1" [type="team", level="1"];
                "Child2" [type="team", level="1"];
                "Leaf1" [type="user", level="0"];

                "Root" -> "Child1";
                "Root" -> "Child2";
                "Child1" -> "Leaf1";
                "Child2" -> "Leaf1"; // Multiple parents
            }
        "#;

        let graph_data = parse_dot_file(dot_content);

        assert_eq!(graph_data.graph.node_count(), 4);
        assert_eq!(graph_data.graph.edge_count(), 4);

        // Verify node attributes were parsed correctly
        let root = graph_data
            .graph
            .node_indices()
            .find(|&idx| graph_data.graph[idx].label == "Root")
            .unwrap();
        assert_eq!(graph_data.graph[root].level, 2);
    }
}