void-cli 0.0.2

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

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fmt;
use std::io::IsTerminal;
use std::time::{SystemTime, UNIX_EPOCH};
use thiserror::Error;

/// CLI schema version for JSON envelope.
pub const CLI_SCHEMA: &str = "void.cli/v1";

/// CLI options parsed from command-line arguments.
#[derive(Debug, Clone, Default)]
pub struct CliOptions {
    /// Output JSON format.
    pub json: bool,
    /// Force human-readable output even when piped.
    pub human: bool,
    /// Suppress all non-JSON output.
    pub quiet: bool,
    /// Show debug information.
    pub debug: bool,
    /// Verbose output.
    pub verbose: bool,
}

impl CliOptions {
    /// Determines output mode.
    /// Priority: --human (force human) > --json (force JSON) > TTY detection
    pub fn is_json_mode(&self) -> bool {
        if self.human {
            return false;
        }
        if self.json {
            return true;
        }
        !std::io::stdout().is_terminal()
    }

    /// Returns true if human-readable mode is active.
    pub fn is_human_mode(&self) -> bool {
        !self.is_json_mode()
    }
}

/// Error codes matching the TypeScript CLI.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ErrorCode {
    /// Bad input/usage
    InvalidArgs,
    /// No void repo found
    NotInitialized,
    /// Missing resource
    NotFound,
    /// Merge conflict
    Conflict,
    /// I/O error
    IoError,
    /// Encryption/decryption error
    EncryptionError,
    /// Feature not implemented
    NotImplemented,
    /// Other errors
    Internal,
}

impl ErrorCode {
    /// Returns the exit code for this error.
    pub fn exit_code(self) -> i32 {
        match self {
            ErrorCode::InvalidArgs => 2,
            ErrorCode::NotInitialized => 4,
            ErrorCode::NotFound => 5,
            ErrorCode::Conflict => 6,
            // IO_ERROR and ENCRYPTION_ERROR use exit code 1 to match TS behavior
            // (TS getExitCode() has no special cases for these, they fall under default => 1)
            ErrorCode::IoError => 1,
            ErrorCode::EncryptionError => 1,
            ErrorCode::NotImplemented => 3,
            ErrorCode::Internal => 1,
        }
    }
}

impl fmt::Display for ErrorCode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ErrorCode::InvalidArgs => write!(f, "INVALID_ARGS"),
            ErrorCode::NotInitialized => write!(f, "NOT_INITIALIZED"),
            ErrorCode::NotFound => write!(f, "NOT_FOUND"),
            ErrorCode::Conflict => write!(f, "CONFLICT"),
            ErrorCode::IoError => write!(f, "IO_ERROR"),
            ErrorCode::EncryptionError => write!(f, "ENCRYPTION_ERROR"),
            ErrorCode::NotImplemented => write!(f, "NOT_IMPLEMENTED"),
            ErrorCode::Internal => write!(f, "INTERNAL"),
        }
    }
}

/// CLI error with code, message, and optional details.
#[derive(Debug, Error, Clone, Serialize, Deserialize)]
pub struct CliError {
    /// Error code for categorization.
    pub code: ErrorCode,
    /// Human-readable error message.
    pub message: String,
    /// Optional additional details (matches TS: details?: Record<string, unknown>).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub details: Option<HashMap<String, serde_json::Value>>,
}

impl fmt::Display for CliError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}: {}", self.code, self.message)?;
        if let Some(details) = &self.details {
            if !details.is_empty() {
                write!(f, " ({:?})", details)?;
            }
        }
        Ok(())
    }
}

impl CliError {
    /// Creates a new CLI error.
    pub fn new(code: ErrorCode, message: impl Into<String>) -> Self {
        Self {
            code,
            message: message.into(),
            details: None,
        }
    }

    /// Creates a new CLI error with additional details.
    pub fn with_details(
        code: ErrorCode,
        message: impl Into<String>,
        details: HashMap<String, serde_json::Value>,
    ) -> Self {
        Self {
            code,
            message: message.into(),
            details: Some(details),
        }
    }

    /// Returns the exit code for this error.
    pub fn exit_code(&self) -> i32 {
        self.code.exit_code()
    }

    /// Creates an INVALID_ARGS error.
    pub fn invalid_args(message: impl Into<String>) -> Self {
        Self::new(ErrorCode::InvalidArgs, message)
    }

    /// Creates a NOT_INITIALIZED error.
    pub fn not_initialized(message: impl Into<String>) -> Self {
        Self::new(ErrorCode::NotInitialized, message)
    }

    /// Creates a NOT_FOUND error.
    pub fn not_found(message: impl Into<String>) -> Self {
        Self::new(ErrorCode::NotFound, message)
    }

    /// Creates a CONFLICT error.
    pub fn conflict(message: impl Into<String>) -> Self {
        Self::new(ErrorCode::Conflict, message)
    }

    /// Creates an INTERNAL error.
    pub fn internal(message: impl Into<String>) -> Self {
        Self::new(ErrorCode::Internal, message)
    }

    /// Creates an IO_ERROR error.
    pub fn io_error(msg: impl Into<String>) -> Self {
        Self::new(ErrorCode::IoError, msg)
    }

    /// Creates an ENCRYPTION_ERROR error.
    pub fn encryption_error(msg: impl Into<String>) -> Self {
        Self::new(ErrorCode::EncryptionError, msg)
    }

    /// Creates a NOT_IMPLEMENTED error.
    #[allow(dead_code)]
    pub fn not_implemented(msg: impl Into<String>) -> Self {
        Self::new(ErrorCode::NotImplemented, msg)
    }
}

/// A log entry for progress/warning/info/error messages.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LogEntry {
    /// Type of log entry.
    #[serde(rename = "type")]
    pub entry_type: LogEntryType,
    /// Log message.
    pub message: String,
    /// Timestamp in milliseconds since Unix epoch.
    pub ts: u64,
}

/// Type of log entry.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum LogEntryType {
    /// Progress update.
    Progress,
    /// Warning message.
    Warn,
    /// Informational log.
    Info,
    /// Error message.
    Error,
}

impl LogEntry {
    /// Creates a new log entry with the current timestamp.
    pub fn new(entry_type: LogEntryType, message: impl Into<String>) -> Self {
        Self {
            entry_type,
            message: message.into(),
            ts: SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .map(|d| d.as_millis() as u64)
                .unwrap_or(0),
        }
    }

    /// Creates a progress log entry.
    pub fn progress(message: impl Into<String>) -> Self {
        Self::new(LogEntryType::Progress, message)
    }

    /// Creates a warning log entry.
    pub fn warn(message: impl Into<String>) -> Self {
        Self::new(LogEntryType::Warn, message)
    }

    /// Creates an informational log entry.
    pub fn info(message: impl Into<String>) -> Self {
        Self::new(LogEntryType::Info, message)
    }

    /// Creates an error log entry.
    #[allow(dead_code)]
    pub fn error(message: impl Into<String>) -> Self {
        Self::new(LogEntryType::Error, message)
    }
}

/// JSON envelope for successful output.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SuccessEnvelope<T> {
    /// Schema version.
    pub schema: String,
    /// Always true for success.
    pub ok: bool,
    /// Command name.
    pub command: String,
    /// Result data.
    pub result: T,
}

/// JSON envelope for error output.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ErrorEnvelope {
    /// Schema version.
    pub schema: String,
    /// Always false for errors.
    pub ok: bool,
    /// Command name.
    pub command: String,
    /// Error details.
    pub error: CliError,
    /// Log entries from command execution (always present, may be empty).
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub log: Vec<LogEntry>,
}

/// Result wrapper that includes log entries.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResultWithLog<T> {
    /// The actual result data.
    #[serde(flatten)]
    pub data: T,
    /// Log entries from command execution (always present, may be empty).
    pub log: Vec<LogEntry>,
}

#[allow(dead_code)]
impl<T> ResultWithLog<T> {
    /// Creates a new result with an empty log.
    pub fn new(data: T) -> Self {
        Self {
            data,
            log: Vec::new(),
        }
    }

    /// Creates a new result with log entries.
    pub fn with_log(data: T, log: Vec<LogEntry>) -> Self {
        Self { data, log }
    }
}

/// Get terminal width for compact JSON formatting.
fn get_terminal_width() -> usize {
    terminal_size::terminal_size()
        .map(|(w, _)| w.0 as usize)
        .unwrap_or(80)
}

/// Compact JSON stringifier that tries single-line first, then expands.
fn compact_stringify<T: Serialize>(value: &T) -> String {
    // Try compact single-line first
    let compact = serde_json::to_string(value).unwrap_or_default();
    let terminal_width = get_terminal_width();

    // If it fits on one line, use compact
    if compact.len() <= terminal_width {
        return compact;
    }

    // Otherwise use 2-space indented format
    serde_json::to_string_pretty(value).unwrap_or(compact)
}

/// ANSI color codes for JSON colorization.
mod json_colors {
    pub const CYAN: &str = "\x1b[36m";
    pub const GREEN: &str = "\x1b[32m";
    pub const MAGENTA: &str = "\x1b[35m";
    pub const YELLOW: &str = "\x1b[33m";
    pub const DIM: &str = "\x1b[2m";
    pub const RESET: &str = "\x1b[0m";
}

/// Colorize JSON output for TTY display.
fn colorize_json(json: &str) -> String {
    let mut result = String::with_capacity(json.len() * 2);
    let mut chars = json.chars().peekable();
    let mut in_string = false;
    let mut after_colon = false;

    while let Some(c) = chars.next() {
        match c {
            // Handle escape sequences inside strings — skip the escaped character
            '\\' if in_string => {
                result.push(c);
                if let Some(escaped) = chars.next() {
                    result.push(escaped);
                }
            }
            '"' if !in_string => {
                in_string = true;
                // Look ahead to determine if this is a key or value
                let mut lookahead = String::new();
                let mut temp_chars = chars.clone();
                while let Some(&next) = temp_chars.peek() {
                    if next == '"' {
                        temp_chars.next();
                        break;
                    }
                    lookahead.push(next);
                    temp_chars.next();
                }
                // Check if followed by colon (it's a key)
                while let Some(&next) = temp_chars.peek() {
                    if next.is_whitespace() {
                        temp_chars.next();
                    } else {
                        break;
                    }
                }
                let is_key = temp_chars.peek() == Some(&':');

                if after_colon {
                    // String value - green
                    result.push_str(json_colors::GREEN);
                    after_colon = false;
                } else if is_key {
                    // Key - cyan
                    result.push_str(json_colors::CYAN);
                } else {
                    // String value - green
                    result.push_str(json_colors::GREEN);
                }
                result.push(c);
            }
            '"' if in_string => {
                result.push(c);
                result.push_str(json_colors::RESET);
                in_string = false;
            }
            ':' if !in_string => {
                result.push(c);
                after_colon = true;
            }
            '0'..='9' | '-' | '.' if !in_string && after_colon => {
                // Number - magenta
                result.push_str(json_colors::MAGENTA);
                result.push(c);
                // Continue collecting number
                while let Some(&next) = chars.peek() {
                    if next.is_ascii_digit()
                        || next == '.'
                        || next == 'e'
                        || next == 'E'
                        || next == '+'
                        || next == '-'
                    {
                        result.push(chars.next().unwrap());
                    } else {
                        break;
                    }
                }
                result.push_str(json_colors::RESET);
                after_colon = false;
            }
            't' if !in_string => {
                // Check for "true"
                if chars.clone().take(3).collect::<String>() == "rue" {
                    result.push_str(json_colors::YELLOW);
                    result.push_str("true");
                    for _ in 0..3 {
                        chars.next();
                    }
                    result.push_str(json_colors::RESET);
                    after_colon = false;
                } else {
                    result.push(c);
                }
            }
            'f' if !in_string => {
                // Check for "false"
                if chars.clone().take(4).collect::<String>() == "alse" {
                    result.push_str(json_colors::YELLOW);
                    result.push_str("false");
                    for _ in 0..4 {
                        chars.next();
                    }
                    result.push_str(json_colors::RESET);
                    after_colon = false;
                } else {
                    result.push(c);
                }
            }
            'n' if !in_string => {
                // Check for "null"
                if chars.clone().take(3).collect::<String>() == "ull" {
                    result.push_str(json_colors::DIM);
                    result.push_str("null");
                    for _ in 0..3 {
                        chars.next();
                    }
                    result.push_str(json_colors::RESET);
                    after_colon = false;
                } else {
                    result.push(c);
                }
            }
            ',' | '{' | '}' | '[' | ']' if !in_string => {
                result.push(c);
                if c == ',' {
                    after_colon = false;
                }
            }
            _ => {
                result.push(c);
            }
        }
    }
    result
}

/// Outputs a successful result as JSON.
pub fn output_success<T: Serialize>(command: &str, result: T) {
    let envelope = SuccessEnvelope {
        schema: CLI_SCHEMA.to_string(),
        ok: true,
        command: command.to_string(),
        result,
    };

    let json = compact_stringify(&envelope);

    // Colorize if stdout is a TTY
    if std::io::stdout().is_terminal() {
        println!("{}", colorize_json(&json));
    } else {
        println!("{}", json);
    }
}

/// Outputs an error as JSON.
pub fn output_error(command: &str, error: &CliError, log: Vec<LogEntry>, opts: &CliOptions) {
    let envelope = ErrorEnvelope {
        schema: CLI_SCHEMA.to_string(),
        ok: false,
        command: command.to_string(),
        error: error.clone(),
        log,
    };

    let json = compact_stringify(&envelope);

    // Colorize if stderr is a TTY
    if std::io::stderr().is_terminal() {
        eprintln!("{}", colorize_json(&json));
    } else {
        eprintln!("{}", json);
    }

    // In debug mode for non-TTY (piped) output, print details separately (matches TS behavior)
    if opts.debug && !std::io::stderr().is_terminal() {
        if let Some(details) = &error.details {
            eprintln!("Debug details: {:?}", details);
        }
    }
}

/// Context for command execution with logging capabilities.
#[allow(dead_code)]
pub struct CommandContext {
    /// Command name.
    command: String,
    /// CLI options.
    opts: CliOptions,
    /// Collected log entries.
    log: Vec<LogEntry>,
    /// When true, default to human output even when piped (non-TTY).
    /// JSON is only used when `--json` is explicitly passed.
    /// Useful for commands like `diff`, `log`, `show` that are commonly piped
    /// to a pager (e.g. `void diff | less`).
    prefer_human: bool,
}

#[allow(dead_code)]
impl CommandContext {
    /// Creates a new command context.
    pub fn new(command: impl Into<String>, opts: CliOptions) -> Self {
        Self {
            command: command.into(),
            opts,
            log: Vec::new(),
            prefer_human: false,
        }
    }

    /// Marks this command as preferring human-readable output even when piped.
    ///
    /// When set, JSON output is only used when `--json` is explicitly passed,
    /// not from TTY auto-detection. This is intended for commands whose output
    /// is commonly piped to a pager (e.g. `void diff | less`).
    pub fn set_prefer_human(&mut self) {
        self.prefer_human = true;
    }

    /// Logs a progress message. Goes to stderr in human mode.
    pub fn progress(&mut self, message: impl Into<String>) {
        let msg = message.into();
        self.log.push(LogEntry::progress(&msg));

        if self.opts.is_human_mode() && !self.opts.quiet {
            eprintln!("{}", msg);
        }
    }

    /// Logs a warning message. Goes to stderr in human mode.
    pub fn warn(&mut self, message: impl Into<String>) {
        let msg = message.into();
        self.log.push(LogEntry::warn(&msg));

        if self.opts.is_human_mode() && !self.opts.quiet {
            eprintln!("warning: {}", msg);
        }
    }

    /// Logs an informational message. Goes to stderr in human mode (matching TS).
    pub fn info(&mut self, message: impl Into<String>) {
        let msg = message.into();
        self.log.push(LogEntry::info(&msg));

        if self.opts.is_human_mode() && !self.opts.quiet {
            eprintln!("{}", msg);
        }
    }

    /// Logs an error message. Goes to stderr in human mode.
    pub fn error(&mut self, message: impl Into<String>) {
        let msg = message.into();
        self.log.push(LogEntry::error(&msg));

        if self.opts.is_human_mode() && !self.opts.quiet {
            eprintln!("error: {}", msg);
        }
    }

    /// Logs a verbose message (only shown in verbose mode). Goes to stderr.
    pub fn verbose(&mut self, message: impl Into<String>) {
        if self.opts.verbose {
            let msg = message.into();
            self.log.push(LogEntry::info(&msg));

            if self.opts.is_human_mode() && !self.opts.quiet {
                eprintln!("[verbose] {}", msg);
            }
        }
    }

    /// Logs a debug message (only shown in debug mode). Goes to stderr.
    pub fn debug(&mut self, message: impl Into<String>) {
        if self.opts.debug {
            let msg = message.into();
            self.log.push(LogEntry::info(&msg));

            if self.opts.is_human_mode() && !self.opts.quiet {
                eprintln!("[debug] {}", msg);
            }
        }
    }

    /// Returns whether JSON output is enabled.
    ///
    /// When `prefer_human` is set, only returns true for explicit `--json`,
    /// ignoring TTY auto-detection.
    pub fn use_json(&self) -> bool {
        if self.prefer_human {
            // Only use JSON when explicitly requested, not from TTY fallback
            self.opts.json && !self.opts.human
        } else {
            self.opts.is_json_mode()
        }
    }

    /// Returns whether verbose mode is enabled.
    pub fn is_verbose(&self) -> bool {
        self.opts.verbose
    }

    /// Returns whether debug mode is enabled.
    pub fn is_debug(&self) -> bool {
        self.opts.debug
    }

    /// Returns whether quiet mode is enabled.
    pub fn is_quiet(&self) -> bool {
        self.opts.quiet
    }

    /// Returns the command name.
    pub fn command(&self) -> &str {
        &self.command
    }

    /// Returns a reference to the CLI options.
    pub fn opts(&self) -> &CliOptions {
        &self.opts
    }

    /// Consumes the context and returns collected log entries.
    pub fn into_log(self) -> Vec<LogEntry> {
        self.log
    }
}

/// Runs a command with structured output handling.
///
/// This wrapper handles:
/// - JSON vs human-readable output formatting
/// - Error handling and exit codes
/// - Log collection
///
/// # Example
///
/// ```ignore
/// use crate::output::{run_command, CliError, CliOptions, ResultWithLog};
/// use serde::Serialize;
///
/// #[derive(Serialize)]
/// struct InitResult {
///     path: String,
/// }
///
/// fn run(cwd: &Path, opts: &CliOptions) -> Result<(), CliError> {
///     run_command("init", opts, |ctx| {
///         ctx.progress("Initializing repository...");
///
///         // Do work...
///
///         Ok(InitResult { path: cwd.display().to_string() })
///     })
/// }
/// ```
pub fn run_command<T, F>(command: &str, opts: &CliOptions, f: F) -> Result<(), CliError>
where
    T: Serialize,
    F: FnOnce(&mut CommandContext) -> Result<T, CliError>,
{
    let mut ctx = CommandContext::new(command, opts.clone());

    match f(&mut ctx) {
        Ok(result) => {
            let json_mode = ctx.use_json();
            if json_mode {
                let result_with_log = ResultWithLog::with_log(result, ctx.into_log());
                output_success(command, result_with_log);
            }
            Ok(())
        }
        Err(error) => {
            if ctx.use_json() {
                output_error(command, &error, ctx.into_log(), opts);
            } else {
                // Always show errors, even when --quiet (matches TS behavior)
                eprintln!("error: {}", error);
                // Show additional details in debug mode
                if opts.debug {
                    if let Some(details) = &error.details {
                        eprintln!("\nDebug details: {:?}", details);
                    }
                }
            }
            Err(error)
        }
    }
}

/// Trait for converting errors into CliError.
#[allow(dead_code)]
pub trait IntoCliError {
    /// Converts this error into a CliError.
    fn into_cli_error(self) -> CliError;
}

impl IntoCliError for std::io::Error {
    fn into_cli_error(self) -> CliError {
        CliError::internal(self.to_string())
    }
}

impl IntoCliError for serde_json::Error {
    fn into_cli_error(self) -> CliError {
        CliError::internal(format!("JSON error: {}", self))
    }
}

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

    #[derive(Serialize)]
    struct TestResult {
        value: i32,
    }

    #[test]
    fn test_error_codes() {
        assert_eq!(ErrorCode::InvalidArgs.exit_code(), 2);
        assert_eq!(ErrorCode::NotInitialized.exit_code(), 4);
        assert_eq!(ErrorCode::NotFound.exit_code(), 5);
        assert_eq!(ErrorCode::Conflict.exit_code(), 6);
        assert_eq!(ErrorCode::Internal.exit_code(), 1);
    }

    #[test]
    fn test_cli_error_display() {
        let err = CliError::invalid_args("missing path argument");
        assert!(err.to_string().contains("INVALID_ARGS"));
        assert!(err.to_string().contains("missing path argument"));

        let mut details = HashMap::new();
        details.insert(
            "path".to_string(),
            serde_json::Value::String("path/to/file.txt".to_string()),
        );
        let err_with_details =
            CliError::with_details(ErrorCode::NotFound, "file not found", details);
        assert!(err_with_details.to_string().contains("path/to/file.txt"));
    }

    #[test]
    fn test_log_entry_types() {
        let progress = LogEntry::progress("Loading...");
        assert_eq!(progress.entry_type, LogEntryType::Progress);

        let warn = LogEntry::warn("Deprecated feature");
        assert_eq!(warn.entry_type, LogEntryType::Warn);

        let info = LogEntry::info("Done");
        assert_eq!(info.entry_type, LogEntryType::Info);

        let error = LogEntry::error("Something failed");
        assert_eq!(error.entry_type, LogEntryType::Error);
    }

    #[test]
    fn test_success_envelope_serialization() {
        let envelope = SuccessEnvelope {
            schema: CLI_SCHEMA.to_string(),
            ok: true,
            command: "test".to_string(),
            result: TestResult { value: 42 },
        };

        let json = serde_json::to_string(&envelope).unwrap();
        assert!(json.contains("\"schema\":\"void.cli/v1\""));
        assert!(json.contains("\"ok\":true"));
        assert!(json.contains("\"command\":\"test\""));
        assert!(json.contains("\"value\":42"));
    }

    #[test]
    fn test_error_envelope_serialization() {
        let envelope = ErrorEnvelope {
            schema: CLI_SCHEMA.to_string(),
            ok: false,
            command: "test".to_string(),
            error: CliError::not_found("resource missing"),
            log: vec![],
        };

        let json = serde_json::to_string(&envelope).unwrap();
        assert!(json.contains("\"ok\":false"));
        assert!(json.contains("\"code\":\"NOT_FOUND\""));
        // Log should be omitted when empty (skip_serializing_if)
        assert!(!json.contains("\"log\""));
    }

    #[test]
    fn test_error_envelope_with_log() {
        let envelope = ErrorEnvelope {
            schema: CLI_SCHEMA.to_string(),
            ok: false,
            command: "test".to_string(),
            error: CliError::not_found("resource missing"),
            log: vec![LogEntry::progress("Starting..."), LogEntry::info("Step 1")],
        };

        let json = serde_json::to_string(&envelope).unwrap();
        assert!(json.contains("\"ok\":false"));
        assert!(json.contains("\"code\":\"NOT_FOUND\""));
        assert!(json.contains("\"log\""));
        assert!(json.contains("\"type\":\"progress\""));
        assert!(json.contains("\"type\":\"info\""));
    }

    #[test]
    fn test_result_with_log_always_has_log() {
        let result = ResultWithLog::new(TestResult { value: 1 });

        let json = serde_json::to_string(&result).unwrap();
        assert!(json.contains("\"value\":1"));
        // Log should always be present (even if empty)
        assert!(json.contains("\"log\":[]"));
    }

    #[test]
    fn test_result_with_log_entries() {
        let result =
            ResultWithLog::with_log(TestResult { value: 1 }, vec![LogEntry::progress("test")]);

        let json = serde_json::to_string(&result).unwrap();
        assert!(json.contains("\"value\":1"));
        assert!(json.contains("\"log\""));
        assert!(json.contains("\"type\":\"progress\""));
    }

    #[test]
    fn test_cli_options_mode_priority() {
        // --human wins over everything
        let opts = CliOptions {
            human: true,
            json: true,
            ..Default::default()
        };
        assert!(!opts.is_json_mode());
        assert!(opts.is_human_mode());

        // --json wins over TTY detection
        let opts = CliOptions {
            json: true,
            ..Default::default()
        };
        assert!(opts.is_json_mode());

        // Default: TTY detection (in test environment, usually not a TTY)
        let opts = CliOptions::default();
        // In tests, stdout is typically not a TTY, so JSON mode would be true
        // We can't easily test TTY detection without mocking
    }

    #[test]
    fn test_compact_stringify_short() {
        let data = TestResult { value: 42 };
        let json = compact_stringify(&data);
        // Short values should be compact
        assert!(!json.contains('\n'));
        assert!(json.contains("\"value\":42"));
    }

    #[test]
    fn test_colorize_json() {
        let json = r#"{"key":"value","num":42,"bool":true,"nil":null}"#;
        let colored = colorize_json(json);
        // Should contain ANSI codes
        assert!(colored.contains("\x1b["));
        // Should still contain the original content
        assert!(colored.contains("key"));
        assert!(colored.contains("value"));
        assert!(colored.contains("42"));
        assert!(colored.contains("true"));
        assert!(colored.contains("null"));
    }

    #[test]
    fn test_colorize_json_escaped_quotes() {
        // JSON with escaped quotes inside a string value
        let json = r#"{"msg":"say \"hello\" world"}"#;
        let colored = colorize_json(json);

        // The escaped quotes should NOT cause a color reset mid-string.
        // Count RESET codes — expect exactly 2: one after the key, one after the value.
        let reset_count = colored.matches(json_colors::RESET).count();
        assert_eq!(reset_count, 2, "escaped quotes should not produce extra RESETs");

        // The escaped quotes must survive colorization
        assert!(colored.contains(r#"\"hello\""#));
    }

    #[test]
    fn test_error_log_entry_type() {
        let error = LogEntry::error("Test error");
        let json = serde_json::to_string(&error).unwrap();
        assert!(json.contains("\"type\":\"error\""));
    }
}