proc-cli 1.14.5

A semantic CLI tool for process management
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
//! Output formatting for proc CLI
//!
//! Provides colored terminal output and JSON formatting.

use crate::core::{PortInfo, Process};
use crate::error::{ExitCode, ProcError, Result};
use crate::ui::format::{colorize_status, format_duration, format_memory, plural, truncate_string};
use colored::*;
use comfy_table::presets::NOTHING;
use comfy_table::{Attribute, Cell, CellAlignment, Color, ContentArrangement, Table};
use dialoguer::Confirm;
use serde::Serialize;

/// Output format selection
#[derive(Debug, Clone, Copy, Default)]
pub enum OutputFormat {
    /// Colored, human-readable terminal output
    #[default]
    Human,
    /// Machine-readable JSON output for scripting
    Json,
}

/// Main printer for CLI output
pub struct Printer {
    format: OutputFormat,
    verbose: bool,
}

/// Detect terminal width, falling back to 120 when stdout is not a TTY.
fn terminal_width() -> u16 {
    crossterm::terminal::size().map(|(w, _)| w).unwrap_or(120)
}

impl Printer {
    /// Creates a new printer with the specified format and verbosity.
    pub fn new(format: OutputFormat, verbose: bool) -> Self {
        Self { format, verbose }
    }

    /// Create a printer from common CLI flags.
    pub fn from_flags(json: bool, verbose: bool) -> Self {
        Self::new(
            if json {
                OutputFormat::Json
            } else {
                OutputFormat::Human
            },
            verbose,
        )
    }

    /// Print a success message (human only — use `print_empty_result` for JSON-safe success)
    pub fn success(&self, message: &str) {
        match self.format {
            OutputFormat::Human => {
                println!("{} {}", "✓".green().bold(), message.green());
            }
            OutputFormat::Json => {
                // JSON output handled separately
            }
        }
    }

    /// Print a "nothing found" success result with JSON support.
    ///
    /// In human mode, prints a green success message. In JSON mode, outputs
    /// structured JSON so scripts/LLMs always get parseable output.
    pub fn print_empty_result(&self, action: &str, message: &str) {
        match self.format {
            OutputFormat::Human => self.success(message),
            OutputFormat::Json => self.print_json(&EmptyResult {
                action,
                success: true,
                count: 0,
                message,
            }),
        }
    }

    /// Print an error message
    pub fn error(&self, message: &str) {
        match self.format {
            OutputFormat::Human => {
                eprintln!("{} {}", "✗".red().bold(), message.red());
            }
            OutputFormat::Json => {
                // JSON output handled separately
            }
        }
    }

    /// Print a warning message
    pub fn warning(&self, message: &str) {
        match self.format {
            OutputFormat::Human => {
                println!("{} {}", "⚠".yellow().bold(), message.yellow());
            }
            OutputFormat::Json => {
                // JSON output handled separately
            }
        }
    }

    /// Print a list of processes with action name and optional context.
    ///
    /// The `action` parameter sets the JSON `action` field (e.g. "list", "by", "stuck").
    pub fn print_processes_as(&self, action: &str, processes: &[Process], context: Option<&str>) {
        match self.format {
            OutputFormat::Human => self.print_processes_human(processes, context),
            OutputFormat::Json => self.print_json(&ProcessListOutput {
                action,
                success: true,
                count: processes.len(),
                processes,
            }),
        }
    }

    /// Print a list of processes with optional context (e.g., "in /path/to/dir").
    /// Uses "list" as the JSON action name.
    pub fn print_processes_with_context(&self, processes: &[Process], context: Option<&str>) {
        self.print_processes_as("list", processes, context)
    }

    /// Print a list of processes. Uses "list" as the JSON action name.
    pub fn print_processes(&self, processes: &[Process]) {
        self.print_processes_with_context(processes, None)
    }

    fn print_processes_human(&self, processes: &[Process], context: Option<&str>) {
        if processes.is_empty() {
            let msg = match context {
                Some(ctx) => format!("No processes found {}", ctx),
                None => "No processes found".to_string(),
            };
            self.warning(&msg);
            return;
        }

        let context_str = context.map(|c| format!(" {}", c)).unwrap_or_default();
        println!(
            "{} Found {} process{}{}",
            "✓".green().bold(),
            processes.len().to_string().cyan().bold(),
            if processes.len() == 1 { "" } else { "es" },
            context_str.bright_black()
        );
        println!();

        self.print_process_rows(processes);
    }

    /// Like `print_processes_as`, for a caller that has printed its own headline
    /// (`⚠ Found 2 orphaned processes`): the generic `✓ Found 2 processes` line
    /// would repeat it, so only the table is printed.
    pub fn print_processes_under_headline(&self, action: &str, processes: &[Process]) {
        match self.format {
            OutputFormat::Human => {
                println!();
                self.print_process_rows(processes);
            }
            OutputFormat::Json => self.print_processes_as(action, processes, None),
        }
    }

    /// The process table (or the verbose list), without a headline
    fn print_process_rows(&self, processes: &[Process]) {
        if self.verbose {
            // Verbose: full details, nothing truncated
            for proc in processes {
                let status_str = format!("{:?}", proc.status);
                let status_colored = colorize_status(&proc.status, &status_str);

                println!(
                    "{} {} {}  {:.1}% CPU  {}  {}",
                    proc.pid.to_string().cyan().bold(),
                    proc.name.white().bold(),
                    format!("[{}]", status_colored).bright_black(),
                    proc.cpu_percent,
                    format_memory(proc.memory_mb),
                    proc.user.as_deref().unwrap_or("-").bright_black()
                );

                if let Some(ref cmd) = proc.command {
                    println!("    {} {}", "cmd:".bright_black(), cmd);
                }
                if let Some(ref path) = proc.exe_path {
                    println!("    {} {}", "exe:".bright_black(), path.bright_black());
                }
                if let Some(ref cwd) = proc.cwd {
                    println!("    {} {}", "cwd:".bright_black(), cwd.bright_black());
                }
                if let Some(ppid) = proc.parent_pid {
                    println!(
                        "    {} {}",
                        "parent:".bright_black(),
                        ppid.to_string().bright_black()
                    );
                }
                if let Some(uptime) = proc.uptime_secs {
                    println!(
                        "    {} {}",
                        "uptime:".bright_black(),
                        format_duration(uptime).bright_black()
                    );
                }
                println!();
            }
        } else {
            let width = terminal_width();
            // UPTIME only fits next to a readable ARGS column on wider terminals
            let show_uptime = width >= 100;

            let mut table = Table::new();
            table
                .load_preset(NOTHING)
                .set_content_arrangement(ContentArrangement::Dynamic)
                .set_width(width);

            // Header
            let mut header = vec![
                Cell::new("PID")
                    .fg(Color::Blue)
                    .add_attribute(Attribute::Bold),
                Cell::new("DIR")
                    .fg(Color::Blue)
                    .add_attribute(Attribute::Bold),
                Cell::new("NAME")
                    .fg(Color::Blue)
                    .add_attribute(Attribute::Bold),
                Cell::new("ARGS")
                    .fg(Color::Blue)
                    .add_attribute(Attribute::Bold),
                Cell::new("CPU%")
                    .fg(Color::Blue)
                    .add_attribute(Attribute::Bold)
                    .set_alignment(CellAlignment::Right),
                Cell::new("MEM")
                    .fg(Color::Blue)
                    .add_attribute(Attribute::Bold)
                    .set_alignment(CellAlignment::Right),
            ];
            if show_uptime {
                header.push(
                    Cell::new("UPTIME")
                        .fg(Color::Blue)
                        .add_attribute(Attribute::Bold)
                        .set_alignment(CellAlignment::Right),
                );
            }
            header.push(
                Cell::new("STATUS")
                    .fg(Color::Blue)
                    .add_attribute(Attribute::Bold)
                    .set_alignment(CellAlignment::Right),
            );
            table.set_header(header);

            // Set fixed-width columns and flexible ones
            use comfy_table::ColumnConstraint::*;
            use comfy_table::Width::*;
            // Fixed widths must account for comfy-table's per-cell padding (1 left + 1 right = 2)
            // Content width = Fixed(N) - 2
            table
                .column_mut(0)
                .expect("PID column")
                .set_constraint(Absolute(Fixed(8))); // 6 content — fits "999999"
            table
                .column_mut(1)
                .expect("DIR column")
                .set_constraint(LowerBoundary(Fixed(20)));
            table
                .column_mut(2)
                .expect("NAME column")
                .set_constraint(LowerBoundary(Fixed(10)));
            // ARGS: flexible but capped so it doesn't squeeze other columns
            let args_max = (width / 2).max(30);
            table
                .column_mut(3)
                .expect("ARGS column")
                .set_constraint(UpperBoundary(Fixed(args_max)));
            table
                .column_mut(4)
                .expect("CPU% column")
                .set_constraint(Absolute(Fixed(8))); // 6 content — fits "100.0"
            table
                .column_mut(5)
                .expect("MEM column")
                .set_constraint(Absolute(Fixed(11))); // 9 content — fits "9999.9MB"
            let status_column = if show_uptime {
                table
                    .column_mut(6)
                    .expect("UPTIME column")
                    .set_constraint(Absolute(Fixed(10))); // 8 content — fits "999d 23h"
                7
            } else {
                6
            };
            table
                .column_mut(status_column)
                .expect("STATUS column")
                .set_constraint(Absolute(Fixed(12))); // 10 content — fits "Sleeping"

            for proc in processes {
                let status_str = format!("{:?}", proc.status);

                // Show working directory (where the process was started from)
                let path_display = proc.cwd.as_deref().unwrap_or("-").to_string();

                // Show command args (skip executable, simplify paths to filenames)
                let cmd_display = proc
                    .command
                    .as_ref()
                    .map(|c| {
                        let parts: Vec<&str> = c.split_whitespace().collect();
                        if parts.len() > 1 {
                            let args: Vec<String> = parts[1..]
                                .iter()
                                .map(|arg| {
                                    if arg.contains('/') && !arg.starts_with('-') {
                                        std::path::Path::new(arg)
                                            .file_name()
                                            .map(|f| f.to_string_lossy().to_string())
                                            .unwrap_or_else(|| arg.to_string())
                                    } else {
                                        arg.to_string()
                                    }
                                })
                                .collect();
                            let result = args.join(" ");
                            if result.is_empty() {
                                "-".to_string()
                            } else {
                                truncate_string(&result, (args_max as usize).saturating_sub(2))
                            }
                        } else {
                            // No args beyond the executable itself
                            "-".to_string()
                        }
                    })
                    .unwrap_or_else(|| "-".to_string());

                let mem_display = format_memory(proc.memory_mb);

                let status_color = match proc.status {
                    crate::core::ProcessStatus::Running => Color::Green,
                    crate::core::ProcessStatus::Sleeping => Color::Blue,
                    crate::core::ProcessStatus::Stopped => Color::Yellow,
                    crate::core::ProcessStatus::Zombie => Color::Red,
                    _ => Color::White,
                };

                let mut row = vec![
                    Cell::new(proc.pid).fg(Color::Cyan),
                    Cell::new(&path_display).fg(Color::DarkGrey),
                    Cell::new(&proc.name).fg(Color::White),
                    Cell::new(&cmd_display).fg(Color::DarkGrey),
                    Cell::new(format!("{:.1}", proc.cpu_percent))
                        .set_alignment(CellAlignment::Right),
                    Cell::new(&mem_display).set_alignment(CellAlignment::Right),
                ];
                if show_uptime {
                    let uptime_display = proc
                        .uptime_secs
                        .map(format_duration)
                        .unwrap_or_else(|| "-".to_string());
                    row.push(Cell::new(uptime_display).set_alignment(CellAlignment::Right));
                }
                row.push(
                    Cell::new(&status_str)
                        .fg(status_color)
                        .set_alignment(CellAlignment::Right),
                );
                table.add_row(row);
            }

            println!("{table}");
        }
        println!();
    }

    /// Print port information
    pub fn print_ports(&self, ports: &[PortInfo]) {
        match self.format {
            OutputFormat::Human => self.print_ports_human(ports),
            OutputFormat::Json => self.print_json(&PortListOutput {
                action: "ports",
                success: true,
                count: ports.len(),
                ports,
            }),
        }
    }

    fn print_ports_human(&self, ports: &[PortInfo]) {
        if ports.is_empty() {
            self.warning("No listening ports found");
            return;
        }

        println!(
            "{} Found {} listening port{}",
            "✓".green().bold(),
            ports.len().to_string().cyan().bold(),
            if ports.len() == 1 { "" } else { "s" }
        );
        println!();

        let width = terminal_width();

        let mut table = Table::new();
        table
            .load_preset(NOTHING)
            .set_content_arrangement(ContentArrangement::Dynamic)
            .set_width(width);

        table.set_header(vec![
            Cell::new("PORT")
                .fg(Color::Blue)
                .add_attribute(Attribute::Bold),
            Cell::new("PROTO")
                .fg(Color::Blue)
                .add_attribute(Attribute::Bold),
            Cell::new("PID")
                .fg(Color::Blue)
                .add_attribute(Attribute::Bold),
            Cell::new("PROCESS")
                .fg(Color::Blue)
                .add_attribute(Attribute::Bold),
            Cell::new("ADDRESS")
                .fg(Color::Blue)
                .add_attribute(Attribute::Bold),
        ]);

        use comfy_table::ColumnConstraint::*;
        use comfy_table::Width::*;
        table
            .column_mut(0)
            .expect("PORT column")
            .set_constraint(Absolute(Fixed(8)));
        table
            .column_mut(1)
            .expect("PROTO column")
            .set_constraint(Absolute(Fixed(6)));
        table
            .column_mut(2)
            .expect("PID column")
            .set_constraint(Absolute(Fixed(8)));
        table
            .column_mut(3)
            .expect("PROCESS column")
            .set_constraint(LowerBoundary(Fixed(12)));
        table
            .column_mut(4)
            .expect("ADDRESS column")
            .set_constraint(LowerBoundary(Fixed(10)));

        for port in ports {
            let addr = port.address.as_deref().unwrap_or("*");
            let proto = format!("{:?}", port.protocol).to_uppercase();

            table.add_row(vec![
                Cell::new(port.port).fg(Color::Cyan),
                Cell::new(&proto).fg(Color::White),
                Cell::new(port.pid).fg(Color::Cyan),
                Cell::new(truncate_string(&port.process_name, 19)).fg(Color::White),
                Cell::new(addr).fg(Color::DarkGrey),
            ]);
        }

        println!("{table}");
        println!();
    }

    /// Print a single port info (for `proc on :port`)
    pub fn print_port_info(&self, port_info: &PortInfo) {
        match self.format {
            OutputFormat::Human => {
                println!(
                    "{} Process on port {}:",
                    "✓".green().bold(),
                    port_info.port.to_string().cyan().bold()
                );
                println!();
                println!(
                    "  {} {}",
                    "Name:".bright_black(),
                    port_info.process_name.white().bold()
                );
                println!(
                    "  {} {}",
                    "PID:".bright_black(),
                    port_info.pid.to_string().cyan()
                );
                println!("  {} {:?}", "Protocol:".bright_black(), port_info.protocol);
                if let Some(ref addr) = port_info.address {
                    println!("  {} {}", "Address:".bright_black(), addr);
                }
                println!();
            }
            OutputFormat::Json => self.print_json(&SinglePortOutput {
                action: "on",
                success: true,
                port: port_info,
            }),
        }
    }

    /// Print JSON output for any serializable type
    pub fn print_json<T: Serialize>(&self, data: &T) {
        match serde_json::to_string_pretty(data) {
            Ok(json) => println!("{}", json),
            Err(e) => eprintln!("Failed to serialize JSON: {}", e),
        }
    }

    /// Print action result (generalized for kill/stop/freeze/thaw).
    ///
    /// The `action` parameter is the command name (e.g. "kill", "stop", "freeze").
    /// It is used as-is in JSON output and as the verb for human display.
    ///
    /// Returns `Err(ProcError::Reported)` when any process failed, so the command
    /// exits non-zero without printing a second result.
    pub fn print_action_result(
        &self,
        action: &str,
        succeeded: &[Process],
        failed: &[(Process, String)],
    ) -> Result<()> {
        self.print_action_result_as(action, action, succeeded, failed)
    }

    /// Print action result where the JSON `action` differs from the verb shown
    /// to humans (e.g. `proc orphans --kill` reports action "orphans", verb "kill").
    pub fn print_action_result_as(
        &self,
        action: &str,
        verb: &str,
        succeeded: &[Process],
        failed: &[(Process, String)],
    ) -> Result<()> {
        // Past tense for human display: "kill" → "Killed", "stop" → "Stopped"
        let past_tense = match verb {
            "kill" => "Killed".to_string(),
            "stop" => "Stopped".to_string(),
            "freeze" => "Frozen".to_string(),
            "thaw" => "Thawed".to_string(),
            _ => format!("{}{}ed", verb[..1].to_uppercase(), &verb[1..]),
        };

        match self.format {
            OutputFormat::Human => {
                if !succeeded.is_empty() {
                    println!(
                        "{} {} {} process{}",
                        "✓".green().bold(),
                        past_tense,
                        succeeded.len().to_string().cyan().bold(),
                        plural(succeeded.len())
                    );
                    for proc in succeeded {
                        println!(
                            "  {} {} [PID {}]",
                            "→".bright_black(),
                            proc.name.white(),
                            proc.pid.to_string().cyan()
                        );
                    }
                }
                if !failed.is_empty() {
                    println!(
                        "{} Failed to {} {} process{}",
                        "✗".red().bold(),
                        verb,
                        failed.len(),
                        plural(failed.len())
                    );
                    for (proc, err) in failed {
                        println!(
                            "  {} {} [PID {}]: {}",
                            "→".bright_black(),
                            proc.name.white(),
                            proc.pid.to_string().cyan(),
                            err.red()
                        );
                    }
                }
            }
            OutputFormat::Json => {
                self.print_json(&ActionOutput {
                    action,
                    success: failed.is_empty(),
                    succeeded_count: succeeded.len(),
                    failed_count: failed.len(),
                    succeeded,
                    failed: &failed
                        .iter()
                        .map(|(p, e)| FailedAction {
                            process: p,
                            error: e,
                        })
                        .collect::<Vec<_>>(),
                });
            }
        }

        if failed.is_empty() {
            Ok(())
        } else {
            Err(ProcError::reported(
                ExitCode::GeneralError,
                format!(
                    "Failed to {} {} process{}",
                    verb,
                    failed.len(),
                    plural(failed.len())
                ),
            ))
        }
    }

    /// Print kill result (delegates to print_action_result)
    pub fn print_kill_result(
        &self,
        killed: &[Process],
        failed: &[(Process, String)],
    ) -> Result<()> {
        self.print_action_result("kill", killed, failed)
    }

    /// Print dry-run summary for a destructive command.
    ///
    /// The `action` is the command name (e.g. "kill", "stop", "freeze", "thaw"),
    /// used both as the JSON `action` and as the verb in the human summary.
    pub fn print_dry_run(&self, action: &str, processes: &[Process]) {
        self.print_dry_run_with(
            action,
            processes,
            &format!(
                "Dry run: would {} {} process{}",
                action,
                processes.len(),
                plural(processes.len())
            ),
        );
    }

    /// Print dry-run summary with a custom human message.
    ///
    /// JSON output is always `{"action", "success", "dry_run": true, "count", "processes"}`.
    pub fn print_dry_run_with(&self, action: &str, processes: &[Process], message: &str) {
        match self.format {
            OutputFormat::Human => {
                self.print_processes_human(processes, None);
                self.warning(message);
            }
            OutputFormat::Json => self.print_json(&DryRunOutput {
                action,
                success: true,
                dry_run: true,
                count: processes.len(),
                processes,
            }),
        }
    }

    /// Show confirmation prompt and return whether the user confirmed.
    ///
    /// Returns `Ok(true)` if confirmed or skipped (--yes / --json).
    /// Returns `Ok(false)` if the user declined (prints "Cancelled").
    pub fn ask_confirm(&self, action: &str, processes: &[Process], yes: bool) -> Result<bool> {
        if yes {
            return Ok(true);
        }
        match self.format {
            OutputFormat::Json => Ok(true),
            OutputFormat::Human => {
                self.print_confirmation(action, processes);
                let prompt = format!(
                    "{}{} {} process{}?",
                    action[..1].to_uppercase(),
                    &action[1..],
                    processes.len(),
                    plural(processes.len())
                );
                let confirmed = Confirm::new()
                    .with_prompt(prompt)
                    .default(false)
                    .interact()?;
                if !confirmed {
                    self.warning("Cancelled");
                }
                Ok(confirmed)
            }
        }
    }

    /// Print a confirmation prompt showing processes about to be acted on
    pub fn print_confirmation(&self, action: &str, processes: &[Process]) {
        println!(
            "\n{} Found {} process{} to {}:\n",
            "⚠".yellow().bold(),
            processes.len().to_string().cyan().bold(),
            if processes.len() == 1 { "" } else { "es" },
            action
        );

        for proc in processes {
            println!(
                "  {} {} [PID {}] - CPU: {:.1}%, MEM: {}",
                "→".bright_black(),
                proc.name.white().bold(),
                proc.pid.to_string().cyan(),
                proc.cpu_percent,
                format_memory(proc.memory_mb)
            );
        }
        println!();
    }
}

// JSON output structures
#[derive(Serialize)]
struct EmptyResult<'a> {
    action: &'a str,
    success: bool,
    count: usize,
    message: &'a str,
}

#[derive(Serialize)]
struct ProcessListOutput<'a> {
    action: &'a str,
    success: bool,
    count: usize,
    processes: &'a [Process],
}

#[derive(Serialize)]
struct DryRunOutput<'a> {
    action: &'a str,
    success: bool,
    dry_run: bool,
    count: usize,
    processes: &'a [Process],
}

#[derive(Serialize)]
struct PortListOutput<'a> {
    action: &'static str,
    success: bool,
    count: usize,
    ports: &'a [PortInfo],
}

#[derive(Serialize)]
struct SinglePortOutput<'a> {
    action: &'static str,
    success: bool,
    port: &'a PortInfo,
}

#[derive(Serialize)]
struct ActionOutput<'a> {
    action: &'a str,
    success: bool,
    succeeded_count: usize,
    failed_count: usize,
    succeeded: &'a [Process],
    failed: &'a [FailedAction<'a>],
}

#[derive(Serialize)]
struct FailedAction<'a> {
    process: &'a Process,
    error: &'a str,
}

impl Default for Printer {
    fn default() -> Self {
        Self::new(OutputFormat::Human, false)
    }
}