rch 2.1.20

Remote Compilation Helper - PreToolUse hook CLI
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
//! RchConsole - Context-aware wrapper around rich_rust's Console.
//!
//! This module provides the primary interface for rich terminal output in RCH commands.
//! It automatically respects output context (interactive, piped, hook, etc.) and
//! routes output to stderr by design (stdout is reserved for data).
//!
//! # Design Philosophy
//!
//! - **stdout** is for DATA (JSON, compilation output, etc.)
//! - **stderr** is for DIAGNOSTICS (status, progress, errors)
//!
//! Rich output goes to stderr so that:
//! 1. Agents can parse stdout reliably
//! 2. Piping `rch status | jq` works correctly
//! 3. Compilation output passthrough is unaffected
//!
//! # Example
//!
//! ```ignore
//! use rch::ui::console::{RchConsole, CONSOLE};
//!
//! // Using global instance
//! CONSOLE.print_success("Operation completed");
//!
//! // Using local instance with explicit context
//! let console = RchConsole::new();
//! if console.is_machine() {
//!     console.print_json(&data)?;
//! } else {
//!     console.print_rich("[bold]Status[/bold]");
//! }
//! ```

#[cfg(all(feature = "rich-ui", unix))]
use rich_rust::prelude::*;
#[cfg(all(feature = "rich-ui", unix))]
use rich_rust::renderables::Renderable;

use rch_common::ui::{Icons, OutputContext, RchTheme};

/// Context-aware console wrapper that respects output mode.
///
/// This is the primary interface for rich output in RCH commands.
/// It automatically:
/// - Detects output context (interactive, piped, hook, etc.)
/// - Routes output to stderr (stdout reserved for data)
/// - Falls back to plain text when appropriate
/// - Respects NO_COLOR and FORCE_COLOR
pub struct RchConsole {
    /// The underlying rich_rust Console (only when rich-ui feature enabled).
    #[cfg(all(feature = "rich-ui", unix))]
    inner: Console,

    /// Detected output context.
    context: OutputContext,
}

impl RchConsole {
    /// Create a new RchConsole with automatic context detection.
    #[must_use]
    pub fn new() -> Self {
        let context = OutputContext::detect();
        Self::with_context(context)
    }

    /// Create with explicit context (useful for testing).
    #[must_use]
    pub fn with_context(context: OutputContext) -> Self {
        #[cfg(all(feature = "rich-ui", unix))]
        let inner = Self::build_console(context);

        Self {
            #[cfg(all(feature = "rich-ui", unix))]
            inner,
            context,
        }
    }

    #[cfg(all(feature = "rich-ui", unix))]
    fn build_console(context: OutputContext) -> Console {
        Console::builder()
            .force_terminal(context.supports_rich())
            // Output to stderr by default for rich content
            // stdout is reserved for machine-readable data
            .build()
    }

    // ========================================================================
    // CONTEXT QUERIES
    // ========================================================================

    /// Check if rich output is available.
    #[must_use]
    pub fn is_rich(&self) -> bool {
        self.context.supports_rich()
    }

    /// Check if colors are available.
    #[must_use]
    pub fn is_colored(&self) -> bool {
        self.context.supports_color()
    }

    /// Check if in machine output mode (Hook or Machine).
    #[must_use]
    pub fn is_machine(&self) -> bool {
        self.context.is_machine()
    }

    /// Get the detected context.
    #[must_use]
    pub fn context(&self) -> OutputContext {
        self.context
    }

    /// Get terminal width (or default 80).
    #[must_use]
    pub fn width(&self) -> usize {
        #[cfg(all(feature = "rich-ui", unix))]
        {
            self.inner.width()
        }
        #[cfg(not(all(feature = "rich-ui", unix)))]
        {
            terminal_size::terminal_size()
                .map(|(w, _)| w.0 as usize)
                .unwrap_or(80)
        }
    }

    // ========================================================================
    // RICH OUTPUT METHODS (only work in rich mode)
    // ========================================================================

    /// Print with markup parsing (only if interactive).
    ///
    /// Does nothing in machine/plain modes.
    #[cfg(all(feature = "rich-ui", unix))]
    pub fn print_rich(&self, content: &str) {
        if self.context.supports_rich() {
            self.inner.print(content);
        }
    }

    /// Print a renderable (table, panel, etc.).
    ///
    /// Does nothing in machine/plain modes.
    #[cfg(all(feature = "rich-ui", unix))]
    pub fn print_renderable<R: Renderable>(&self, renderable: &R) {
        if self.context.supports_rich() {
            self.inner.print_renderable(renderable);
        }
    }

    /// Print a horizontal rule.
    ///
    /// Falls back to dashes in non-rich modes.
    pub fn rule(&self, title: Option<&str>) {
        #[cfg(all(feature = "rich-ui", unix))]
        if self.context.supports_rich() {
            self.inner.rule(title);
            return;
        }

        if !self.context.is_machine() {
            // Plain fallback
            let width: usize = 60;
            if let Some(t) = title {
                let padding = width.saturating_sub(t.len()).saturating_sub(2) / 2;
                eprintln!("{} {} {}", "-".repeat(padding), t, "-".repeat(padding));
            } else {
                eprintln!("{}", "-".repeat(width));
            }
        }
    }

    /// Print a blank line.
    pub fn line(&self) {
        if !self.context.is_machine() {
            #[cfg(all(feature = "rich-ui", unix))]
            {
                self.inner.line();
            }
            #[cfg(not(all(feature = "rich-ui", unix)))]
            {
                eprintln!();
            }
        }
    }

    // ========================================================================
    // FALLBACK OUTPUT METHODS
    // ========================================================================

    /// Print with rich/plain fallback.
    ///
    /// - In rich mode: prints rich content
    /// - In plain mode: prints plain content
    /// - In machine mode: prints nothing
    pub fn print_or_plain(&self, _rich: &str, plain: &str) {
        #[cfg(all(feature = "rich-ui", unix))]
        if self.context.supports_rich() {
            self.inner.print(_rich);
            return;
        }

        if !self.context.is_machine() {
            eprintln!("{plain}");
        }
    }

    /// Print plain text to stderr (always, unless machine mode).
    ///
    /// Use for messages that should appear in plain mode too.
    pub fn print_plain(&self, content: &str) {
        if !self.context.is_machine() {
            eprintln!("{content}");
        }
    }

    /// Print error with rich panel or plain fallback.
    ///
    /// Always prints (errors should show even in machine mode to stderr).
    #[cfg(all(feature = "rich-ui", unix))]
    pub fn print_error(&self, title: &str, message: &str) {
        if self.context.supports_rich() {
            let icon = Icons::cross(self.context);
            let title_text = format!("{icon} {title}");
            let panel = Panel::from_text(message)
                .title(title_text.as_str())
                .border_style(RchTheme::error())
                .rounded();
            self.inner.print_renderable(&panel);
        } else {
            let icon = Icons::cross(self.context);
            eprintln!("{icon} Error: {title}");
            eprintln!("{message}");
        }
    }

    /// Print error with plain fallback (non-rich-ui version).
    #[cfg(not(all(feature = "rich-ui", unix)))]
    pub fn print_error(&self, title: &str, message: &str) {
        let icon = Icons::cross(self.context);
        eprintln!("{icon} Error: {title}");
        eprintln!("{message}");
    }

    /// Print success message.
    pub fn print_success(&self, message: &str) {
        let icon = Icons::check(self.context);

        #[cfg(all(feature = "rich-ui", unix))]
        if self.context.supports_rich() {
            self.inner
                .print(&format!("[bold {}]{icon}[/] {message}", RchTheme::SUCCESS));
            return;
        }

        if !self.context.is_machine() {
            eprintln!("{icon} {message}");
        }
    }

    /// Print warning message.
    pub fn print_warning(&self, message: &str) {
        let icon = Icons::warning(self.context);

        #[cfg(all(feature = "rich-ui", unix))]
        if self.context.supports_rich() {
            self.inner
                .print(&format!("[bold {}]{icon}[/] {message}", RchTheme::WARNING));
            return;
        }

        if !self.context.is_machine() {
            eprintln!("{icon} {message}");
        }
    }

    /// Print info message.
    pub fn print_info(&self, message: &str) {
        let icon = Icons::info(self.context);

        #[cfg(all(feature = "rich-ui", unix))]
        if self.context.supports_rich() {
            self.inner
                .print(&format!("[bold {}]{icon}[/] {message}", RchTheme::INFO));
            return;
        }

        if !self.context.is_machine() {
            eprintln!("{icon} {message}");
        }
    }

    // ========================================================================
    // MACHINE OUTPUT (to stdout)
    // ========================================================================

    /// Print JSON to stdout (for --json flag).
    ///
    /// This goes to stdout, not stderr!
    pub fn print_json<T: serde::Serialize>(&self, value: &T) -> serde_json::Result<()> {
        let json = serde_json::to_string_pretty(value)?;
        println!("{json}");
        Ok(())
    }

    // ========================================================================
    // ACCESS TO UNDERLYING CONSOLE
    // ========================================================================

    /// Get the underlying rich_rust Console.
    ///
    /// Use sparingly - prefer the wrapper methods.
    #[cfg(all(feature = "rich-ui", unix))]
    #[must_use]
    pub fn inner(&self) -> &Console {
        &self.inner
    }
}

impl Default for RchConsole {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// CONVENIENCE FUNCTION
// ============================================================================

/// Create a new console instance with automatic context detection.
///
/// Use this for quick access in command handlers:
/// ```ignore
/// use rch::ui::console::console;
/// console().print_success("Done!");
/// ```
///
/// Note: This creates a new instance each time. If you need to reuse
/// the same instance across multiple calls, create one with `RchConsole::new()`
/// and store it locally.
#[must_use]
pub fn console() -> RchConsole {
    RchConsole::new()
}

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

    #[test]
    fn test_machine_mode_no_rich() {
        let console = RchConsole::with_context(OutputContext::Machine);
        // These should do nothing (not panic)
        console.print_plain("test"); // Should be suppressed
        assert!(console.is_machine());
        assert!(!console.is_rich());
    }

    #[test]
    fn test_hook_mode_is_machine() {
        let console = RchConsole::with_context(OutputContext::Hook);
        assert!(console.is_machine());
        assert!(!console.is_rich());
        assert!(!console.is_colored());
    }

    #[test]
    fn test_plain_mode_no_markup() {
        let console = RchConsole::with_context(OutputContext::Plain);
        // Should work but without markup
        assert!(!console.is_machine());
        assert!(!console.is_rich());
    }

    #[test]
    fn test_context_queries_interactive() {
        let console = RchConsole::with_context(OutputContext::Interactive);
        assert!(console.is_rich());
        assert!(console.is_colored());
        assert!(!console.is_machine());
    }

    #[test]
    fn test_context_queries_colored() {
        let console = RchConsole::with_context(OutputContext::Colored);
        assert!(!console.is_rich()); // FORCE_COLOR doesn't mean we have a rich terminal
        assert!(console.is_colored());
        assert!(!console.is_machine());
    }

    #[test]
    fn test_context_accessor_returns_value() {
        let console = RchConsole::with_context(OutputContext::Plain);
        assert_eq!(console.context(), OutputContext::Plain);
    }

    #[test]
    fn test_with_context_all_modes() {
        let cases = [
            (OutputContext::Interactive, true, true, false),
            (OutputContext::Colored, false, true, false),
            (OutputContext::Plain, false, false, false),
            (OutputContext::Machine, false, false, true),
            (OutputContext::Hook, false, false, true),
        ];

        for (context, rich, colored, machine) in cases {
            let console = RchConsole::with_context(context);
            assert_eq!(console.is_rich(), rich, "rich mismatch for {context:?}");
            assert_eq!(
                console.is_colored(),
                colored,
                "color mismatch for {context:?}"
            );
            assert_eq!(
                console.is_machine(),
                machine,
                "machine mismatch for {context:?}"
            );
        }
    }

    #[test]
    fn test_width_returns_reasonable_value() {
        let console = RchConsole::new();
        let width = console.width();
        assert!(width >= 40, "Width should be at least 40: {width}");
        assert!(width <= 500, "Width should be at most 500: {width}");
    }

    #[test]
    fn test_default_creates_valid_console() {
        let console = RchConsole::default();
        // Should not panic and context should be valid
        let _ = console.context();
    }

    #[test]
    fn test_console_function() {
        let c1 = console();
        let c2 = console();
        // Both should have the same context detection result
        assert_eq!(c1.context(), c2.context());
    }

    #[test]
    fn test_print_json_succeeds() {
        let console = RchConsole::with_context(OutputContext::Machine);
        #[derive(serde::Serialize)]
        struct TestData {
            value: i32,
        }
        // Should not panic (output goes to stdout)
        let result = console.print_json(&TestData { value: 42 });
        assert!(result.is_ok());
    }

    #[test]
    fn test_rule_plain_mode() {
        let console = RchConsole::with_context(OutputContext::Plain);
        // Should not panic
        console.rule(None);
        console.rule(Some("Test Title"));
    }

    #[test]
    fn test_rule_machine_mode_silent() {
        let console = RchConsole::with_context(OutputContext::Machine);
        // Should not panic, should do nothing
        console.rule(None);
        console.rule(Some("Test Title"));
    }

    #[test]
    fn test_rule_plain_long_title() {
        let console = RchConsole::with_context(OutputContext::Plain);
        console.rule(Some(
            "A Very Long Title That Exceeds The Default Width For Rules",
        ));
    }

    #[test]
    fn test_line_plain_mode() {
        let console = RchConsole::with_context(OutputContext::Plain);
        // Should not panic
        console.line();
    }

    #[test]
    fn test_line_machine_mode() {
        let console = RchConsole::with_context(OutputContext::Machine);
        console.line();
    }

    #[test]
    fn test_print_or_plain_modes() {
        // Machine mode: should print nothing
        let console = RchConsole::with_context(OutputContext::Machine);
        console.print_or_plain("[bold]rich[/]", "plain");

        // Plain mode: should print plain
        let console = RchConsole::with_context(OutputContext::Plain);
        console.print_or_plain("[bold]rich[/]", "plain");
    }

    #[test]
    fn test_print_or_plain_interactive() {
        let console = RchConsole::with_context(OutputContext::Interactive);
        console.print_or_plain("[bold]rich[/]", "plain");
    }

    #[test]
    fn test_print_plain_suppressed_in_machine_mode() {
        let console = RchConsole::with_context(OutputContext::Machine);
        console.print_plain("plain");
    }

    #[test]
    fn test_status_messages_machine_mode() {
        let console = RchConsole::with_context(OutputContext::Machine);
        // These should be suppressed in machine mode (except print_error)
        console.print_success("success");
        console.print_warning("warning");
        console.print_info("info");
    }

    #[test]
    fn test_status_messages_plain_and_colored() {
        let console = RchConsole::with_context(OutputContext::Plain);
        console.print_success("success");
        console.print_warning("warning");
        console.print_info("info");

        let console = RchConsole::with_context(OutputContext::Colored);
        console.print_success("success");
        console.print_warning("warning");
        console.print_info("info");
    }

    #[test]
    fn test_print_plain_non_machine() {
        let console = RchConsole::with_context(OutputContext::Plain);
        console.print_plain("plain");

        let console = RchConsole::with_context(OutputContext::Interactive);
        console.print_plain("plain");
    }

    #[test]
    fn test_print_json_plain_mode() {
        let console = RchConsole::with_context(OutputContext::Plain);
        #[derive(serde::Serialize)]
        struct TestData {
            label: &'static str,
        }
        let result = console.print_json(&TestData { label: "ok" });
        assert!(result.is_ok());
    }

    #[cfg(all(feature = "rich-ui", unix))]
    #[test]
    fn test_print_rich_suppressed_in_machine_mode() {
        let console = RchConsole::with_context(OutputContext::Machine);
        console.print_rich("[bold]test[/]");
    }

    #[cfg(all(feature = "rich-ui", unix))]
    #[test]
    fn test_print_renderable_suppressed_in_plain_mode() {
        let console = RchConsole::with_context(OutputContext::Plain);
        let panel = rich_rust::renderables::Panel::from_text("renderable");
        console.print_renderable(&panel);
    }

    #[cfg(all(feature = "rich-ui", unix))]
    #[test]
    fn test_inner_console_access() {
        let console = RchConsole::with_context(OutputContext::Interactive);
        let _inner = console.inner();
    }

    #[test]
    fn test_print_error_always_outputs() {
        // Even in machine mode, errors should output to stderr
        let console = RchConsole::with_context(OutputContext::Machine);
        console.print_error("Test Error", "This is a test error message");
        // Should not panic - error output always happens
    }

    #[test]
    fn test_threaded_console_usage() {
        use std::thread;

        let handles: Vec<_> = (0..4)
            .map(|_| {
                thread::spawn(|| {
                    let console = RchConsole::with_context(OutputContext::Plain);
                    console.print_plain("test");
                    console.print_or_plain("[bold]rich[/]", "plain");
                    console.rule(None);
                })
            })
            .collect();

        for handle in handles {
            handle.join().unwrap();
        }
    }

    #[cfg(all(feature = "rich-ui", unix))]
    #[test]
    fn test_rich_paths_interactive() {
        let console = RchConsole::with_context(OutputContext::Interactive);
        console.print_rich("[bold]rich[/]");
        let panel = rich_rust::renderables::Panel::from_text("renderable");
        console.print_renderable(&panel);
        console.rule(Some("Title"));
        console.line();
        console.print_error("Title", "Message");
        console.print_success("success");
        console.print_warning("warning");
        console.print_info("info");
        console.print_or_plain("[bold]rich[/]", "plain");
    }
}