denet 0.7.0

a simple process monitor
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
use clap::{Parser, Subcommand};
use colored::Colorize;
#[cfg(feature = "ebpf")]
use denet::ebpf::debug;
use denet::error::Result;
use denet::monitor::{tagged_json, AggregatedMetrics, Metrics, Summary, SummaryGenerator};
use denet::ProcessMonitor;
use std::fs::File;
use std::io::{self, Write};
use std::path::PathBuf;
use std::process::exit;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::Duration;
use std::time::Instant;
use tabled::{builder::Builder, settings::Style};

/// Dynamic Explorer of Nested Executions Tool (DENET)
#[derive(Parser, Debug)]
#[clap(author, version, about, long_about = None)]
struct Args {
    /// Output in JSON format
    #[clap(short, long)]
    json: bool,

    /// Write output to file
    #[clap(short, long, value_name = "FILE")]
    out: Option<PathBuf>,

    /// Base sampling interval in milliseconds (default: 100)
    #[clap(short, long, default_value = "100")]
    interval: u64,

    /// Maximum sampling interval in milliseconds (default: 1000)
    #[clap(short, long, default_value = "1000")]
    max_interval: u64,

    /// Print new lines instead of updating in place
    #[clap(short, long)]
    no_update: bool,

    /// Maximum duration to monitor in seconds (0 = unlimited)
    #[clap(short, long, default_value = "0")]
    duration: u64,

    /// Show I/O since process start instead of since monitoring start
    #[clap(long)]
    since_process_start: bool,

    /// Exclude child processes from monitoring (monitor only the main process)
    #[clap(long)]
    exclude_children: bool,

    /// Quiet mode: no output to stdout (except with --json)
    #[clap(short, long)]
    quiet: bool,

    /// Enable eBPF profiling (requires root privileges or CAP_BPF capability)
    #[clap(long)]
    enable_ebpf: bool,

    /// Enable debug mode with verbose output (especially for eBPF diagnostics)
    #[clap(long)]
    debug: bool,

    /// Disable polling - wait until process completion for pure event-driven collection
    #[clap(long)]
    no_polling: bool,

    /// Write a host/NUMA/affinity `env` record before metadata (for reproducibility)
    #[clap(long)]
    write_env: bool,

    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand, Debug)]
enum Commands {
    /// Run and monitor a new process
    Run {
        /// Command to run and monitor
        #[clap(required = true)]
        command: Vec<String>,
    },

    /// Monitor an existing process by PID
    Attach {
        /// Process ID (PID) to monitor
        #[clap(required = true)]
        pid: usize,
    },

    /// Generate statistics from a previously saved metrics file
    Stats {
        /// Path to the metrics file
        #[clap(required = true)]
        file: PathBuf,
    },
}

fn main() -> Result<()> {
    let args = Args::parse();

    if let Commands::Stats { file } = &args.command {
        return handle_stats_command(file, &args);
    }

    // Handle monitoring commands
    handle_monitoring_commands(&args)
}

fn handle_stats_command(file: &PathBuf, args: &Args) -> Result<()> {
    generate_summary_from_file(file, args.json, args.out.as_ref())
}

/// Handle monitoring commands (run and attach)
fn handle_monitoring_commands(args: &Args) -> Result<()> {
    let file_handles = setup_output_files(args)?;
    let monitor = create_monitor_from_args(args)?;
    execute_monitoring_with_output(monitor, file_handles, args)
}

/// Output file handles for monitoring
struct OutputHandles {
    out_file: Option<File>,
}

/// Set up output files based on command line arguments
fn setup_output_files(args: &Args) -> Result<OutputHandles> {
    let out_file = args.out.as_ref().map(|path| {
        File::create(path).unwrap_or_else(|err| {
            eprintln!("Error creating output file: {err}");
            exit(1);
        })
    });

    Ok(OutputHandles { out_file })
}

/// Create a ProcessMonitor based on command line arguments
fn create_monitor_from_args(args: &Args) -> Result<ProcessMonitor> {
    match &args.command {
        Commands::Run { command } => create_monitor_for_command(command, args),
        Commands::Attach { pid } => create_monitor_for_pid(*pid, args),
        Commands::Stats { .. } => unreachable!(),
    }
}

/// Create monitor for a new command
fn create_monitor_for_command(command: &[String], args: &Args) -> Result<ProcessMonitor> {
    if command.is_empty() {
        eprintln!("Error: Empty command");
        exit(1);
    }

    match ProcessMonitor::new_with_options(
        command.to_vec(),
        Duration::from_millis(args.interval),
        Duration::from_millis(args.max_interval),
        args.since_process_start,
    ) {
        Ok(monitor) => {
            if args.debug && !args.quiet && !args.json {
                println!("Monitoring process: {}", command.join(" ").cyan());
            }
            Ok(monitor)
        }
        Err(err) => {
            eprintln!("Error starting command: {err}");
            exit(1);
        }
    }
}

/// Create monitor for existing process by PID
fn create_monitor_for_pid(pid: usize, args: &Args) -> Result<ProcessMonitor> {
    match ProcessMonitor::from_pid_with_options(
        pid,
        Duration::from_millis(args.interval),
        Duration::from_millis(args.max_interval),
        args.since_process_start,
    ) {
        Ok(monitor) => {
            if !args.quiet && !args.json {
                println!(
                    "Monitoring existing process with PID: {}",
                    pid.to_string().cyan()
                );
            }
            Ok(monitor)
        }
        Err(err) => {
            eprintln!("Error attaching to process {pid}: {err}");
            exit(1);
        }
    }
}

/// Execute monitoring with output handling
fn execute_monitoring_with_output(
    mut monitor: ProcessMonitor,
    mut file_handles: OutputHandles,
    args: &Args,
) -> Result<()> {
    // In JSON mode all human-readable UI is suppressed so stdout stays
    // parseable (e.g. piping to jq). Errors still go to stderr.
    let ui_quiet = args.quiet || args.json;

    // Set debug mode if requested
    if args.debug {
        monitor.set_debug_mode(true);
        if !ui_quiet {
            println!("Debug mode enabled - verbose output will be shown");
        }
    }

    // Set debug mode for eBPF if requested
    #[cfg(feature = "ebpf")]
    {
        unsafe {
            debug::set_debug_mode(args.debug);
        }
        if args.debug && !ui_quiet {
            println!("Debug mode enabled for eBPF profiling - verbose output will be shown");
        }
    }

    // Enable eBPF profiling if requested
    if args.enable_ebpf {
        if let Err(e) = monitor.enable_ebpf() {
            if !args.quiet {
                eprintln!("Warning: Failed to enable eBPF profiling: {e}");
                eprintln!("Hint: Try running with sudo or setting CAP_BPF capability:");
                eprintln!("  sudo setcap cap_bpf+ep target/release/denet");

                if args.debug {
                    eprintln!("\nFor detailed diagnostics, run: cargo run --bin ebpf_diag --features ebpf");
                    eprintln!("(Add --debug flag for even more verbose output)");
                } else {
                    eprintln!("Run with --debug flag for more detailed error information");
                }

                eprintln!("Continuing without eBPF profiling...");
            }
        } else if !ui_quiet {
            println!("eBPF profiling enabled");
        }
    }

    // Setup signal handling for clean shutdown
    let running = Arc::new(AtomicBool::new(true));
    let r = running.clone();

    ctrlc::set_handler(move || {
        r.store(false, Ordering::SeqCst);
        if !ui_quiet {
            println!("\nReceived Ctrl-C, finishing...");
        }
    })
    .expect("Error setting Ctrl-C handler");

    if !ui_quiet {
        println!("Press Ctrl+C to stop monitoring");
        println!();
    }

    // For in-place updates - use a sophisticated approach
    let mut terminal_width = 80; // Default fallback
    if let Ok((w, _)) = crossterm::terminal::size() {
        terminal_width = w as usize;
    }
    let update_in_place = !args.no_update && !args.json;
    let mut needs_newline_on_exit = false;

    // Progress indicator for in-place updates
    let progress_chars = ['', '', '', '', '', '', '', '', '', ''];
    let mut progress_index = 0;

    // Variables for collecting results
    let start_time = Instant::now();
    let mut metrics_count = 0;
    let mut results = Vec::new();
    let mut aggregated_metrics: Vec<AggregatedMetrics> = Vec::new();

    // Calculate timeout if duration is specified
    let timeout = if args.duration > 0 {
        Some(Duration::from_secs(args.duration))
    } else {
        None
    };

    // Emit env record first (if requested) — captures host/NUMA/affinity for reproducibility.
    if args.write_env {
        let env_json = tagged_json("env", &monitor.get_env()).unwrap();
        if let Some(file) = &mut file_handles.out_file {
            writeln!(file, "{env_json}")?;
        }
        if args.json && !args.quiet {
            println!("{env_json}");
        }
    }

    // Get metadata
    let metadata = monitor.get_metadata();

    // Emit metadata (always for files, only output to console if JSON mode)
    if let Some(metadata_ref) = &metadata {
        let metadata_json = tagged_json("metadata", metadata_ref).unwrap();
        if let Some(file) = &mut file_handles.out_file {
            writeln!(file, "{metadata_json}")?;
        }
        if args.json && !args.quiet {
            println!("{metadata_json}");
        }
    }

    // Check for no-polling mode
    if args.no_polling {
        if !args.quiet {
            println!("🚀 Pure event-driven mode: eBPF collecting syscalls until completion...");
        }

        // Simple wait loop without any output
        while monitor.is_running() && running.load(Ordering::SeqCst) {
            if let Some(timeout_duration) = timeout {
                if start_time.elapsed() >= timeout_duration {
                    if !args.quiet {
                        println!("\nTimeout reached after {} seconds", args.duration);
                    }
                    break;
                }
            }
            std::thread::sleep(Duration::from_millis(100));
        }

        // Generate final summary
        if !args.quiet {
            println!("✅ Process completed. Generating comprehensive summary...");
        }

        let final_tree_metrics = monitor.sample_tree_metrics();
        if args.json {
            let json = tagged_json("tree", &final_tree_metrics).unwrap();
            println!("{json}");
        } else if let Some(agg) = final_tree_metrics.aggregated {
            results.push(convert_aggregated_to_metrics(&agg));
            metrics_count = 1;
        }
    } else {
        // Regular adaptive polling mode
        while monitor.is_running() && running.load(Ordering::SeqCst) {
            // Check timeout
            if let Some(timeout_duration) = timeout {
                if start_time.elapsed() >= timeout_duration {
                    if !args.quiet {
                        println!("\nTimeout reached after {} seconds", args.duration);
                    }
                    break;
                }
            }

            if args.exclude_children {
                // Monitor only the main process
                if let Some(metrics) = monitor.sample_metrics() {
                    metrics_count += 1;

                    // Store metrics for final summary
                    results.push(metrics.clone());

                    // Format and display metrics
                    if args.json {
                        let json = tagged_json("sample", &metrics).unwrap();
                        if let Some(file) = &mut file_handles.out_file {
                            writeln!(file, "{json}")?;
                        }
                        if !args.quiet {
                            if update_in_place {
                                // Clear line and print new content with spinner and elapsed time
                                let spinner = progress_chars[progress_index % progress_chars.len()];
                                let elapsed = start_time.elapsed().as_secs();
                                print!(
                                    "\r{}\r{} [{}s] {}",
                                    " ".repeat(terminal_width.saturating_sub(1)),
                                    spinner.to_string().cyan(),
                                    elapsed.to_string().bright_black(),
                                    json
                                );
                                io::stdout().flush()?;
                                needs_newline_on_exit = true;
                                progress_index += 1;
                            } else {
                                println!("{json}");
                            }
                        }
                    } else {
                        let formatted = format_metrics(&metrics);
                        if let Some(file) = &mut file_handles.out_file {
                            writeln!(file, "{}", tagged_json("sample", &metrics).unwrap())?;
                        }
                        if !args.quiet {
                            if update_in_place {
                                // Use compact format for in-place updates
                                let formatted_compact = format_metrics_compact(&metrics);
                                let spinner = progress_chars[progress_index % progress_chars.len()];
                                let elapsed = start_time.elapsed().as_secs();
                                print!(
                                    "\r{}\r{} [{}s] {}",
                                    " ".repeat(terminal_width.saturating_sub(1)),
                                    spinner.to_string().cyan(),
                                    elapsed.to_string().bright_black(),
                                    formatted_compact
                                );
                                io::stdout().flush()?;
                                needs_newline_on_exit = true;
                                progress_index += 1;
                            } else {
                                println!("{formatted}");
                            }
                        }
                    }
                }
            } else {
                // Monitor process tree (default behavior)
                let tree_metrics = monitor.sample_tree_metrics();
                if let Some(agg_metrics) = tree_metrics.aggregated.as_ref() {
                    metrics_count += 1;

                    // Store aggregated metrics for final summary
                    // Convert aggregated metrics to regular metrics for storage compatibility
                    let storage_metrics = convert_aggregated_to_metrics(agg_metrics);
                    results.push(storage_metrics);

                    // Also store for specialized aggregated stats
                    aggregated_metrics.push(agg_metrics.clone());

                    // Format and display tree metrics
                    if args.json {
                        let json = tagged_json("tree", &tree_metrics).unwrap();
                        if let Some(file) = &mut file_handles.out_file {
                            writeln!(file, "{json}")?;
                        }
                        if !args.quiet {
                            if update_in_place {
                                // For in-place updates, show just aggregated metrics
                                let agg_json = serde_json::to_string(&agg_metrics).unwrap();
                                let spinner = progress_chars[progress_index % progress_chars.len()];
                                let elapsed = start_time.elapsed().as_secs();
                                print!(
                                    "\r{}\r{} [{}s] {}",
                                    " ".repeat(terminal_width.saturating_sub(1)),
                                    spinner.to_string().cyan(),
                                    elapsed.to_string().bright_black(),
                                    agg_json
                                );
                                io::stdout().flush()?;
                                needs_newline_on_exit = true;
                                progress_index += 1;
                            } else {
                                println!("{json}");
                            }
                        }
                    } else {
                        // Format and display tree metrics with parent and children
                        let formatted = format_aggregated_metrics(agg_metrics);
                        if let Some(file) = &mut file_handles.out_file {
                            writeln!(file, "{}", tagged_json("tree", &tree_metrics).unwrap())?;
                        }
                        if !args.quiet {
                            if update_in_place {
                                // Use compact format for in-place updates
                                let formatted_compact =
                                    format_aggregated_metrics_compact(agg_metrics);
                                let spinner = progress_chars[progress_index % progress_chars.len()];
                                let elapsed = start_time.elapsed().as_secs();
                                print!(
                                    "\r{}\r{} [{}s] {}",
                                    " ".repeat(terminal_width.saturating_sub(1)),
                                    spinner.to_string().cyan(),
                                    elapsed.to_string().bright_black(),
                                    formatted_compact
                                );
                                io::stdout().flush()?;
                                needs_newline_on_exit = true;
                                progress_index += 1;
                            } else {
                                println!("{formatted}");
                            }
                        }
                    }
                }
            }

            // Sleep for the adaptive interval
            std::thread::sleep(monitor.adaptive_interval());
        }
    } // End of polling mode else block

    // Calculate summary
    let runtime = start_time.elapsed();

    // Only print if not in quiet/json mode
    if !args.quiet && !args.json {
        // Clean up and ensure we have a newline if we were updating in place
        if needs_newline_on_exit {
            println!();
        }

        println!(
            "\n{} {}",
            "Monitoring complete after".green(),
            format!("{:.1} seconds", runtime.as_secs_f64())
                .cyan()
                .bold()
        );
        println!(
            "📊 {} {}",
            "Collected".green(),
            format!("{metrics_count} metric samples").cyan().bold()
        );

        // If we wrote to a file, print the path
        if let Some(path) = &args.out {
            println!("Results written to {}", path.display().to_string().green());
        }

        // Generate and print summary
        if !results.is_empty() {
            print_summary(&results, runtime.as_secs_f64());
        }
    }

    Ok(())
}

fn color_for_cpu(cpu: f32) -> &'static str {
    if cpu < 10.0 {
        "green"
    } else if cpu < 50.0 {
        "yellow"
    } else {
        "red"
    }
}

fn color_for_mem(mem_mb: f64) -> &'static str {
    if mem_mb < 100.0 {
        "green"
    } else if mem_mb < 500.0 {
        "yellow"
    } else {
        "red"
    }
}

#[cfg(feature = "gpu")]
fn color_for_util(util: u32) -> &'static str {
    if util < 30 {
        "green"
    } else if util < 70 {
        "yellow"
    } else {
        "red"
    }
}

#[allow(clippy::too_many_arguments)]
fn format_base(
    cpu_usage: f32,
    mem_rss_kb: u64,
    thread_count: usize,
    disk_read_bytes: u64,
    disk_write_bytes: u64,
    sys_net_rx_bytes: u64,
    sys_net_tx_bytes: u64,
    uptime_secs: u64,
    process_count: Option<usize>,
    compact: bool,
) -> String {
    let cpu_color = color_for_cpu(cpu_usage);
    let mem_mb = mem_rss_kb as f64 / 1024.0;
    let mem_color = color_for_mem(mem_mb);

    let prefix = match (process_count, compact) {
        (Some(n), false) => format!("Tree ({n} procs): "),
        (Some(n), true) => format!("Tree({n}): "),
        (None, _) => String::new(),
    };

    if compact {
        format!(
            "{prefix}CPU {} | Mem {} | Threads {} | Disk {} rd, {} wr | Sys Net {} rx, {} tx",
            format!("{:.1}%", cpu_usage).color(cpu_color),
            format!("{mem_mb:.0}M").color(mem_color),
            thread_count,
            format_bytes(disk_read_bytes).cyan(),
            format_bytes(disk_write_bytes).cyan(),
            format_bytes(sys_net_rx_bytes).green(),
            format_bytes(sys_net_tx_bytes).green(),
        )
    } else {
        format!(
            "{prefix}CPU: {} | Memory: {} | Threads: {} | Disk: {} rd, {} wr | Sys Net: {} rx, {} tx | Uptime: {}s",
            format!("{:.1}%", cpu_usage).color(cpu_color),
            format!("{mem_mb:.1} MB").color(mem_color),
            thread_count,
            format_bytes(disk_read_bytes).cyan(),
            format_bytes(disk_write_bytes).cyan(),
            format_bytes(sys_net_rx_bytes).green(),
            format_bytes(sys_net_tx_bytes).green(),
            uptime_secs,
        )
    }
}

#[cfg(feature = "gpu")]
fn append_gpu_suffix(base: String, gpu: Option<&denet::gpu::GpuMetrics>, compact: bool) -> String {
    let Some(gpu_metrics) = gpu else { return base };
    if gpu_metrics.has_process_data {
        if let Some(util) = gpu_metrics.max_process_utilization() {
            let mem = gpu_metrics.total_process_memory_usage();
            let color = color_for_util(util);
            if compact {
                return format!("{base} | GPU {}%", format!("{util}").color(color));
            } else {
                let gb = mem as f64 / (1024.0 * 1024.0 * 1024.0);
                return format!(
                    "{base} | GPU: {}%, {gb:.1}GB",
                    format!("{util}").color(color)
                );
            }
        } else if gpu_metrics.total_process_memory_usage() > 0 {
            let mem = gpu_metrics.total_process_memory_usage();
            if compact {
                let mb = mem as f64 / (1024.0 * 1024.0);
                return format!("{base} | GPU {mb:.0}M");
            } else {
                let gb = mem as f64 / (1024.0 * 1024.0 * 1024.0);
                return format!("{base} | GPU: {gb:.1}GB");
            }
        }
    } else if let Some(util) = gpu_metrics.max_system_utilization() {
        let color = color_for_util(util);
        let sep = if compact { "" } else { ":" };
        return format!(
            "{base} | GPU{sep} {}% (sys)",
            format!("{util}").color(color)
        );
    }
    base
}

fn format_metrics(metrics: &Metrics) -> String {
    let base = format_base(
        metrics.cpu_usage,
        metrics.mem_rss_kb,
        metrics.thread_count,
        metrics.disk_read_bytes,
        metrics.disk_write_bytes,
        metrics.sys_net_rx_bytes,
        metrics.sys_net_tx_bytes,
        metrics.uptime_secs,
        None,
        false,
    );
    #[cfg(feature = "gpu")]
    return append_gpu_suffix(base, metrics.gpu.as_ref(), false);
    #[cfg(not(feature = "gpu"))]
    base
}

fn format_metrics_compact(metrics: &Metrics) -> String {
    let base = format_base(
        metrics.cpu_usage,
        metrics.mem_rss_kb,
        metrics.thread_count,
        metrics.disk_read_bytes,
        metrics.disk_write_bytes,
        metrics.sys_net_rx_bytes,
        metrics.sys_net_tx_bytes,
        metrics.uptime_secs,
        None,
        true,
    );
    #[cfg(feature = "gpu")]
    return append_gpu_suffix(base, metrics.gpu.as_ref(), true);
    #[cfg(not(feature = "gpu"))]
    base
}

fn format_aggregated_metrics(metrics: &AggregatedMetrics) -> String {
    let base = format_base(
        metrics.cpu_usage,
        metrics.mem_rss_kb,
        metrics.thread_count,
        metrics.disk_read_bytes,
        metrics.disk_write_bytes,
        metrics.sys_net_rx_bytes,
        metrics.sys_net_tx_bytes,
        metrics.uptime_secs,
        Some(metrics.process_count),
        false,
    );
    #[cfg(feature = "gpu")]
    return append_gpu_suffix(base, metrics.gpu.as_ref(), false);
    #[cfg(not(feature = "gpu"))]
    base
}

fn format_aggregated_metrics_compact(metrics: &AggregatedMetrics) -> String {
    let base = format_base(
        metrics.cpu_usage,
        metrics.mem_rss_kb,
        metrics.thread_count,
        metrics.disk_read_bytes,
        metrics.disk_write_bytes,
        metrics.sys_net_rx_bytes,
        metrics.sys_net_tx_bytes,
        metrics.uptime_secs,
        Some(metrics.process_count),
        true,
    );
    #[cfg(feature = "gpu")]
    return append_gpu_suffix(base, metrics.gpu.as_ref(), true);
    #[cfg(not(feature = "gpu"))]
    base
}

fn convert_aggregated_to_metrics(agg: &AggregatedMetrics) -> Metrics {
    Metrics {
        ts_ms: agg.ts_ms,
        cpu_usage: agg.cpu_usage,
        mem_rss_kb: agg.mem_rss_kb,
        mem_vms_kb: agg.mem_vms_kb,
        disk_read_bytes: agg.disk_read_bytes,
        disk_write_bytes: agg.disk_write_bytes,
        syscall_read_bytes: agg.syscall_read_bytes,
        syscall_write_bytes: agg.syscall_write_bytes,
        page_faults_cached: agg.page_faults_cached,
        page_faults_disk: agg.page_faults_disk,
        sys_net_rx_bytes: agg.sys_net_rx_bytes,
        sys_net_tx_bytes: agg.sys_net_tx_bytes,
        thread_count: agg.thread_count,
        uptime_secs: agg.uptime_secs,
        cpu_core: None,
        gpu: agg.gpu.clone(),
        psi_mem: agg.psi_mem,
        #[cfg_attr(target_os = "linux", allow(clippy::clone_on_copy))]
        perf: agg.perf.clone(),
    }
}

fn format_bytes(bytes: u64) -> String {
    if bytes < 1024 {
        format!("{bytes}B")
    } else if bytes < 1024 * 1024 {
        format!("{:.1}KB", bytes as f64 / 1024.0)
    } else if bytes < 1024 * 1024 * 1024 {
        format!("{:.1}MB", bytes as f64 / (1024.0 * 1024.0))
    } else {
        format!("{:.1}GB", bytes as f64 / (1024.0 * 1024.0 * 1024.0))
    }
}

/// Generate and print a summary from metrics
/// Print a summary of collected metrics
fn summary_rows(summary: &Summary) -> Vec<(&'static str, String)> {
    #[allow(unused_mut)]
    let mut rows = vec![
        (
            "Duration",
            format!("{:.2} seconds", summary.total_time_secs),
        ),
        ("Samples", format!("{}", summary.sample_count)),
        ("Max Processes", format!("{}", summary.max_processes)),
        ("Max Threads", format!("{}", summary.max_threads)),
        (
            "Peak Memory",
            format!("{} MB", (summary.peak_mem_rss_kb as f64 / 1024.0).round()),
        ),
        ("Avg CPU Usage", format!("{:.1}%", summary.avg_cpu_usage)),
        ("Disk Read", format_bytes(summary.total_disk_read_bytes)),
        ("Disk Write", format_bytes(summary.total_disk_write_bytes)),
        (
            "Network Received",
            format_bytes(summary.total_sys_net_rx_bytes),
        ),
        ("Network Sent", format_bytes(summary.total_sys_net_tx_bytes)),
    ];

    if let Some(ref mc) = summary.memory_characterization {
        rows.push(("Mem Verdict", mc.verdict.clone()));
        if let Some(ipc) = mc.mean_ipc {
            rows.push(("Mean IPC", format!("{ipc:.2}")));
        }
        if let Some(rate) = mc.llc_miss_rate {
            rows.push(("LLC Miss Rate", format!("{:.1}%", rate * 100.0)));
        }
        if let Some(stall) = mc.backend_stall_ratio {
            rows.push(("Backend Stalls", format!("{:.1}%", stall * 100.0)));
        }
        if let Some(psi) = mc.psi_some_fraction {
            rows.push(("PSI mem-stall samples", format!("{:.1}%", psi * 100.0)));
        }
    }

    #[cfg(feature = "gpu")]
    if let Some(ref gpu) = summary.gpu {
        if gpu.enabled {
            rows.push(("GPU Devices", format!("{}", gpu.device_count)));
            rows.push((
                "Peak GPU VRAM Used",
                format!(
                    "{:.2} GB / {:.1} GB",
                    gpu.peak_used_memory_gb, gpu.total_memory_gb
                ),
            ));
            rows.push((
                "Peak GPU Utilization",
                format!("{}%", gpu.max_system_gpu_utilization),
            ));
            if let Some(proc_util) = gpu.max_process_gpu_utilization {
                rows.push(("Peak Process GPU", format!("{}%", proc_util)));
            }
            if gpu.process_memory_usage_gb > 0.0 {
                rows.push((
                    "Process GPU Memory",
                    format!("{:.2} GB", gpu.process_memory_usage_gb),
                ));
            }
        }
    }

    rows
}

fn print_summary_rows(summary: &Summary) {
    let rows = summary_rows(summary);
    let mut builder = Builder::default();
    for (key, val) in &rows {
        builder.push_record([key, val.as_str()]);
    }
    let mut table = builder.build();
    table.with(Style::blank());
    println!("{table}");
}

fn print_summary(metrics: &[Metrics], duration: f64) {
    let summary = Summary::from_metrics(metrics, duration);
    println!("\n{}", "EXECUTION SUMMARY".cyan().bold());
    print_summary_rows(&summary);
}

/// Generate a summary from a JSON file with metrics
fn generate_summary_from_file(
    file_path: &PathBuf,
    json_output: bool,
    out_file: Option<&PathBuf>,
) -> Result<()> {
    if !json_output {
        println!("Generating statistics from file: {}", file_path.display());
    }

    match SummaryGenerator::from_json_file(file_path) {
        Ok(summary) => {
            if json_output {
                let json = serde_json::to_string_pretty(&summary)?;

                // If out file is specified, write JSON to the file
                if let Some(out_path) = out_file {
                    let mut file = File::create(out_path)?;
                    writeln!(file, "{json}")?;
                } else {
                    // Otherwise print to stdout
                    println!("{json}");
                }
            } else {
                // If out file is specified, write human-readable output to the file
                if let Some(out_path) = out_file {
                    let mut file = File::create(out_path)?;
                    writeln!(file, "\n{}", "FILE STATISTICS".bold())?;
                    writeln!(file, "{}", "===============".bold())?;
                    writeln!(file, "Duration: {:.2} seconds", summary.total_time_secs)?;
                    writeln!(file, "Samples: {}", summary.sample_count)?;
                    writeln!(file, "Max processes: {}", summary.max_processes)?;
                    writeln!(file, "Max threads: {}", summary.max_threads)?;
                    writeln!(
                        file,
                        "Peak memory usage: {} MB",
                        (summary.peak_mem_rss_kb as f64 / 1024.0).round()
                    )?;
                    writeln!(file, "Average CPU usage: {:.1}%", summary.avg_cpu_usage)?;
                    writeln!(
                        file,
                        "Total disk read: {}",
                        format_bytes(summary.total_disk_read_bytes)
                    )?;
                    writeln!(
                        file,
                        "Total disk write: {}",
                        format_bytes(summary.total_disk_write_bytes)
                    )?;
                    writeln!(
                        file,
                        "Total network received: {}",
                        format_bytes(summary.total_sys_net_rx_bytes)
                    )?;
                    writeln!(
                        file,
                        "Total network sent: {}",
                        format_bytes(summary.total_sys_net_tx_bytes)
                    )?;
                } else {
                    // Otherwise print to stdout
                    println!("\n{}", "FILE STATISTICS".cyan().bold());
                    print_summary_rows(&summary);
                }
            }
            Ok(())
        }
        Err(e) => {
            eprintln!("Error processing metrics file: {e}");
            Err(e)
        }
    }
}