standout 8.0.0

Styled CLI template rendering with automatic terminal detection
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
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
//! App builder and main entry point for CLI integration.
//!
//! This module provides the [`AppBuilder`] type (re-exported as [`App`](super::App))
//! for configuring CLI applications with commands, hooks, templates, themes,
//! and app-level state.
//!
//! # App State
//!
//! App-level state (database connections, configuration, API clients) can be
//! injected via `.app_state()` and accessed in handlers via `ctx.app_state`:
//!
//! ```rust,ignore
//! App::new()
//!     .app_state(Database::connect()?)
//!     .app_state(Config::load()?)
//!     .command("list", |matches, ctx| {
//!         let db = ctx.app_state.get_required::<Database>()?;
//!         Ok(Output::Render(db.list()?))
//!     }, "{{ items }}")
//!     .build()?
//! ```
//!
//! The builder is split into submodules by concern:
//! - [`config`]: Configuration methods (themes, templates, context, flags)
//! - [`commands`]: Command and handler registration
//! - [`execution`]: Dispatch macro integration and command execution
//! - [`rendering`]: Template rendering and data serialization

mod commands;
mod config;
mod execution;
mod rendering;

use crate::context::ContextRegistry;
use crate::setup::SetupError;
use crate::topics::{
    display_with_pager, render_topic, render_topics_list, TopicRegistry, TopicRenderConfig,
};
use crate::TemplateRegistry;
use crate::{render_auto, OutputMode, Theme};
use clap::{Arg, ArgAction, ArgMatches, Command};
use serde::Serialize;
use std::cell::RefCell;
use std::collections::HashMap;
use std::path::PathBuf;
use std::rc::Rc;

use super::default_command::ParseFailure;
use super::dispatch::DispatchFn;
use super::group::CommandRecipe;
use super::handler::{CommandContext, Extensions, HandlerResult, Output as HandlerOutput};
use super::help::{render_help, render_help_with_topics, CommandGroup, HelpConfig};
use super::hooks::{ArtifactOutput, HookError, Hooks, RenderedOutput, TextOutput};
use super::questionnaire::QuestionnaireCommand;
use super::result::{HelpDisplay, HelpResult};
use standout_dispatch::verify::ExpectedArg;

/// Stores a pending command recipe along with its resolved template.
struct PendingCommand {
    recipe: Box<dyn CommandRecipe>,
    template: String,
}

/// Main entry point for standout-clap integration.
///
/// `AppBuilder` is re-exported as `App` in the public API. It serves as both
/// the builder for configuration and the runtime for command dispatch, rendering,
/// and help.
///
/// # Example
///
/// ```rust
/// use standout::cli::App;
///
/// let standout = App::new()
///     .help_handling(true)
///     .topics_dir(".").unwrap()
///     .output_flag(Some("format"))
///     .build();
/// ```
///
/// # Context Injection
///
/// You can inject additional context objects into templates using `.context()` for
/// static values and `.context_fn()` for dynamic values computed at render time:
///
/// ```rust,ignore
/// use standout::cli::App;
/// use crate::context::RenderContext;
/// use minijinja::Value;
///
/// App::new()
///     // Static context
///     .context("app_version", Value::from("1.0.0"))
///
///     // Dynamic context (computed at render time)
///     .context_fn("terminal", |ctx: &RenderContext| {
///         Value::from_iter([
///             ("width", Value::from(ctx.terminal_width.unwrap_or(80))),
///             ("is_tty", Value::from(ctx.output_mode == standout::OutputMode::Term)),
///         ])
///     })
///     .command("list", handler, "Width: {{ terminal.width }}")
///     .build()?
///     .run(cmd, args);
/// ```
pub struct AppBuilder {
    pub(crate) registry: TopicRegistry,
    pub(crate) output_flag: Option<String>,
    pub(crate) output_file_flag: Option<String>,
    pub(crate) theme: Option<Theme>,
    /// Stylesheet registry (built from embedded styles)
    pub(crate) stylesheet_registry: Option<crate::StylesheetRegistry>,
    /// Template registry (built from embedded templates)
    pub(crate) template_registry: Option<Rc<TemplateRegistry>>,
    pub(crate) default_theme_name: Option<String>,
    /// Pending commands - closures are created lazily at dispatch time
    pending_commands: RefCell<HashMap<String, PendingCommand>>,
    /// Finalized dispatch functions (lazily created from pending_commands)
    finalized_commands: RefCell<Option<HashMap<String, DispatchFn>>>,
    pub(crate) command_hooks: HashMap<String, Hooks>,
    pub(crate) questionnaire_commands: HashMap<String, QuestionnaireCommand>,
    pub(crate) context_registry: ContextRegistry,
    pub(crate) template_dir: Option<PathBuf>,
    pub(crate) template_ext: String,
    /// Static default command to use when no subcommand is specified
    pub(crate) default_command: Option<String>,
    /// Invocation-aware default command chooser, consulted before the static
    /// default. See [`crate::cli::default_command`].
    pub(crate) default_command_resolver: Option<crate::cli::DefaultCommandResolver>,
    /// Whether to include framework-supplied templates (default: true)
    pub(crate) include_framework_templates: bool,
    /// Whether to include framework-supplied styles (default: true)
    pub(crate) include_framework_styles: bool,
    /// App-level state shared across all dispatches.
    ///
    /// Stored as `Rc<Extensions>` so it can be cloned cheaply into CommandContext.
    /// During builder phase, `Rc::get_mut` is used since only the builder holds the Rc.
    pub(crate) app_state: Rc<Extensions>,

    /// Optional template engine.
    ///
    /// If not provided, a default MiniJinja engine will be created.
    pub(crate) template_engine: Rc<Box<dyn standout_render::template::TemplateEngine>>,

    /// Command groups for organized help display.
    pub(crate) help_command_groups: Option<Vec<CommandGroup>>,

    /// Whether standout intercepts and renders help (default: false).
    ///
    /// When true, standout replaces clap's built-in help subcommand with its
    /// own — where the install policy allows, see `help_word` — and renders
    /// themed, grouped help for every invocation form (`help`, `--help`, `-h`).
    /// Required when using `command_groups` or topics.
    pub(crate) help_handling: bool,

    /// Whether a flat CLI with positionals opts into the `help` word.
    ///
    /// Only consulted for the one shape standout will not decide on its own —
    /// see [`installs_help_word`](AppBuilder::installs_help_word).
    pub(crate) help_word: bool,

    /// Explicit East Asian Ambiguous width policy.
    pub(crate) ambiguous_width: crate::AmbiguousWidth,
}

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

impl AppBuilder {
    /// Creates a new App with default settings.
    ///
    /// By default, the `--output` flag is enabled, framework templates and styles
    /// are included, and no hooks are registered.
    pub fn new() -> Self {
        Self {
            registry: TopicRegistry::new(),
            output_flag: Some("output".to_string()), // Enabled by default
            output_file_flag: Some("output-file-path".to_string()),
            theme: None,
            stylesheet_registry: None,
            template_registry: None,
            default_theme_name: None,
            pending_commands: RefCell::new(HashMap::new()),
            finalized_commands: RefCell::new(None),
            command_hooks: HashMap::new(),
            questionnaire_commands: HashMap::new(),
            context_registry: ContextRegistry::new(),
            template_dir: None,
            template_ext: ".j2".to_string(),
            default_command: None,
            default_command_resolver: None,
            include_framework_templates: true,
            include_framework_styles: true,
            app_state: Rc::new(Extensions::new()),
            template_engine: Rc::new(Box::new(standout_render::template::MiniJinjaEngine::new())),
            help_command_groups: None,
            help_handling: false,
            help_word: false,
            ambiguous_width: crate::AmbiguousWidth::Narrow,
        }
    }

    /// Backwards-compatible alias for `new()`.
    pub fn builder() -> Self {
        Self::new()
    }

    /// Adds app-level state that will be available to all handlers.
    ///
    /// App state is immutable and shared across all dispatches via `Rc<Extensions>`.
    /// Use for long-lived resources like database connections, configuration, and
    /// API clients.
    ///
    /// # Shared Mutable State
    ///
    /// To share mutable state (like metrics or caches), use interior mutability:
    ///
    /// ```rust
    /// use standout::cli::{App, Output};
    /// use std::sync::atomic::{AtomicUsize, Ordering};
    ///
    /// struct Metrics {
    ///     requests: AtomicUsize,
    /// }
    ///
    /// let app = App::new()
    ///     .app_state(Metrics { requests: AtomicUsize::new(0) })
    ///     .command("test", |_m, ctx| {
    ///         let metrics = ctx.app_state.get_required::<Metrics>()?;
    ///         metrics.requests.fetch_add(1, Ordering::SeqCst);
    ///         Ok(Output::<()>::Silent)
    ///     }, "").unwrap()
    ///     .build()
    ///     .unwrap();
    /// ```
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use standout::cli::App;
    ///
    /// struct Database { url: String }
    /// struct Config { debug: bool }
    ///
    /// let app = App::new()
    ///     .app_state(Database { url: "postgres://localhost".into() })
    ///     .app_state(Config { debug: true })
    ///     .command("list", |matches, ctx| {
    ///         let db = ctx.app_state.get_required::<Database>()?;
    ///         let config = ctx.app_state.get_required::<Config>()?;
    ///         // Use db and config...
    ///         Ok(Output::Render(vec!["item1", "item2"]))
    ///     }, "{{ items }}")
    ///     .build()?;
    /// ```
    ///
    /// # Type Safety
    ///
    /// Each type can only be stored once. Inserting a second value of the same
    /// type replaces the first:
    ///
    /// ```rust,ignore
    /// App::new()
    ///     .app_state(Config { debug: false })
    ///     .app_state(Config { debug: true })  // Replaces previous Config
    /// ```
    pub fn app_state<T: 'static>(mut self, value: T) -> Self {
        // During builder phase, only the builder holds the Rc, so get_mut succeeds.
        Rc::get_mut(&mut self.app_state)
            .expect("app_state Rc should be exclusively owned during builder phase")
            .insert(value);
        self
    }

    /// sets a custom template engine to be used for rendering.
    ///
    /// If not set, the default MiniJinja engine will be used.
    pub fn template_engine(
        mut self,
        engine: Box<dyn standout_render::template::TemplateEngine>,
    ) -> Self {
        self.template_engine = Rc::new(engine);
        self
    }

    /// Ensures all pending commands have been finalized into dispatch functions.
    ///
    /// This method is called lazily on first dispatch. It creates the actual
    /// dispatch closures from the stored recipes. The theme is NOT captured here -
    /// it is passed at runtime via late binding, which allows `.theme()` to be
    /// called in any order relative to `.command()`.
    fn ensure_commands_finalized(&self) {
        // Already finalized?
        if self.finalized_commands.borrow().is_some() {
            return;
        }

        let context_registry = &self.context_registry;

        // Build dispatch functions from recipes
        let mut commands = HashMap::new();
        for (path, pending) in self.pending_commands.borrow().iter() {
            let dispatch = pending.recipe.create_dispatch(
                &pending.template,
                context_registry,
                self.template_engine.clone(),
            );
            commands.insert(path.clone(), dispatch);
        }

        *self.finalized_commands.borrow_mut() = Some(commands);
    }

    /// Returns the finalized commands map, creating it if necessary.
    fn get_commands(&self) -> std::cell::Ref<'_, HashMap<String, DispatchFn>> {
        self.ensure_commands_finalized();
        std::cell::Ref::map(self.finalized_commands.borrow(), |opt| {
            opt.as_ref()
                .expect("finalized_commands should be Some after ensure_commands_finalized")
        })
    }

    /// Test helper: Check if a command path is registered.
    #[cfg(test)]
    pub(crate) fn has_command(&self, path: &str) -> bool {
        self.pending_commands.borrow().contains_key(path)
    }

    /// Finalizes the App, resolving themes, loading templates, and preparing
    /// for dispatch and rendering.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - A `default_theme()` was specified but the theme wasn't found in the stylesheet registry
    /// - `command_groups` or topics are configured without `.help_handling(true)`
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let standout = App::new()
    ///     .styles(embed_styles!("src/styles"))
    ///     .default_theme("dark")
    ///     .build()?;
    /// ```
    pub fn build(mut self) -> Result<Self, SetupError> {
        use crate::assets::FRAMEWORK_TEMPLATES;

        // Add framework templates if enabled (BEFORE finalizing commands)
        if self.include_framework_templates {
            match self.template_registry.as_mut() {
                Some(arc) => {
                    // Get mutable access to the registry
                    if let Some(registry) = Rc::get_mut(arc) {
                        registry.add_framework_entries(FRAMEWORK_TEMPLATES);
                    } else {
                        // Shouldn't happen during build before finalization
                        panic!("template registry was shared before build completed");
                    }
                }
                None => {
                    // Create new registry with just framework templates
                    let mut registry = TemplateRegistry::new();
                    registry.add_framework_entries(FRAMEWORK_TEMPLATES);
                    self.template_registry = Some(Rc::new(registry));
                }
            };
        }

        // Populate engine with templates from registry
        // We use Rc::get_mut to mutate the engine in-place before sharing it
        if let Some(registry) = &self.template_registry {
            if let Some(engine_box) = Rc::get_mut(&mut self.template_engine) {
                for name in registry.names() {
                    if let Ok(content) = registry.get_content(name) {
                        let _ = engine_box.add_template(name, &content);
                    }
                }
            }
        }

        // Resolve theme BEFORE finalization
        // Theme resolution: explicit .theme() takes precedence, then .default_theme() from stylesheet registry
        if self.theme.is_none() {
            if let Some(ref mut registry) = self.stylesheet_registry {
                let resolved = if let Some(name) = &self.default_theme_name {
                    Some(
                        registry
                            .get(name)
                            .map_err(|_| SetupError::ThemeNotFound(name.to_string()))?,
                    )
                } else {
                    // Try defaults in order: default, theme, base
                    registry
                        .get("default")
                        .or_else(|_| registry.get("theme"))
                        .or_else(|_| registry.get("base"))
                        .ok()
                };
                self.theme = resolved;
            }
        }

        // Validate help configuration: features that require help interception
        // must not be used without enabling it.
        if !self.help_handling {
            let has_groups = self.help_command_groups.is_some();
            let has_topics = !self.registry.list_topics().is_empty();
            if has_groups || has_topics {
                let feature = if has_groups {
                    "command_groups"
                } else {
                    "topics"
                };
                return Err(SetupError::Config(format!(
                    "{feature} requires .help_handling(true) — \
                     standout cannot render grouped/topic help without intercepting help"
                )));
            }
            if self.help_word {
                return Err(SetupError::Config(
                    "help_word requires .help_handling(true) — the `help` word is \
                     standout's own subcommand, so there is nothing to install without \
                     help interception"
                        .to_string(),
                ));
            }
        }

        // Finalize commands (now theme is resolved and will be captured correctly)
        self.ensure_commands_finalized();

        Ok(self)
    }

    /// Builds and parses CLI arguments in one step.
    ///
    /// # Panics
    ///
    /// Panics if building fails (e.g., theme not found). For proper error handling,
    /// use `build()` followed by `parse_with()` instead.
    pub fn parse(self, cmd: clap::Command) -> clap::ArgMatches {
        self.build().expect("Failed to build App").parse_with(cmd)
    }

    // =========================================================================
    // Accessors
    // =========================================================================

    /// Returns a reference to the topic registry.
    pub fn registry(&self) -> &TopicRegistry {
        &self.registry
    }

    /// Returns a mutable reference to the topic registry.
    pub fn registry_mut(&mut self) -> &mut TopicRegistry {
        &mut self.registry
    }

    /// Returns the current output mode (always Auto for the App itself;
    /// per-render mode is passed as a parameter).
    pub fn output_mode(&self) -> OutputMode {
        OutputMode::Auto
    }

    /// Returns the hooks registered for a specific command path.
    pub fn get_hooks(&self, path: &str) -> Option<&Hooks> {
        self.command_hooks.get(path)
    }

    /// Returns the default theme, if configured.
    pub fn get_default_theme(&self) -> Option<&Theme> {
        self.theme.as_ref()
    }

    /// Gets a theme by name from the stylesheet registry.
    ///
    /// This allows using themes other than the default at runtime.
    ///
    /// # Errors
    ///
    /// Returns an error if no stylesheet registry is configured or if the theme
    /// is not found.
    pub fn get_theme(&mut self, name: &str) -> Result<Theme, SetupError> {
        self.stylesheet_registry
            .as_mut()
            .ok_or_else(|| SetupError::Config("No stylesheet registry configured".into()))?
            .get(name)
            .map_err(|_| SetupError::ThemeNotFound(name.to_string()))
    }

    /// Returns the names of all available templates.
    ///
    /// Returns an empty iterator if no template registry is configured.
    pub fn template_names(&self) -> impl Iterator<Item = &str> {
        self.template_registry
            .as_ref()
            .map(|r| r.names())
            .into_iter()
            .flatten()
    }

    /// Returns the names of all available themes.
    ///
    /// Returns an empty vector if no stylesheet registry is configured.
    pub fn theme_names(&self) -> Vec<String> {
        self.stylesheet_registry
            .as_ref()
            .map(|r| r.names().map(String::from).collect())
            .unwrap_or_default()
    }

    // =========================================================================
    // Parsing & Help
    // =========================================================================

    /// Parses CLI arguments with this configured App instance.
    pub fn parse_with(&self, cmd: Command) -> clap::ArgMatches {
        self.parse_from(cmd, std::env::args())
    }

    /// Like `parse_with`, but takes arguments from an iterator.
    pub fn parse_from<I, T>(&self, cmd: Command, itr: I) -> clap::ArgMatches
    where
        I: IntoIterator<Item = T>,
        T: Into<std::ffi::OsString> + Clone,
    {
        match self.get_matches_from(cmd, itr) {
            HelpResult::Matches(m) => m,
            HelpResult::Help(h) => {
                println!("{}", h);
                std::process::exit(0);
            }
            HelpResult::PagedHelp(h) => {
                if display_with_pager(&h).is_err() {
                    println!("{}", h);
                }
                std::process::exit(0);
            }
            HelpResult::Error(e) => e.exit(),
        }
    }

    /// Attempts to get matches, intercepting `help` requests.
    ///
    /// For most use cases, prefer `parse_with()` which handles help display automatically.
    pub fn get_matches(&self, cmd: Command) -> HelpResult {
        self.get_matches_from(cmd, std::env::args())
    }

    /// Attempts to get matches from the given arguments, intercepting `help` requests.
    ///
    /// When `help_handling` is enabled, every help invocation is intercepted and
    /// rendered through standout: `--help` / `-h` always, and the bare `help`
    /// word where the install policy put it (see
    /// [`help_word`](Self::help_word)). When disabled, only output flags are
    /// augmented and clap handles help natively.
    ///
    /// Which command a line means is Clap's answer, read off the parse. Only a
    /// parse that selected no command is naked, and only a naked line resolves
    /// a default command — statically via
    /// [`default_command`](Self::default_command) or per-invocation via
    /// [`default_command_with`](Self::default_command_with). `dispatch_from`
    /// parses through the same seam, so consumers that parse first and build
    /// dispatch state afterwards see one consistent answer.
    pub fn get_matches_from<I, T>(&self, cmd: Command, itr: I) -> HelpResult
    where
        I: IntoIterator<Item = T>,
        T: Into<std::ffi::OsString> + Clone,
    {
        let mut cmd = self.augment_command_with_help(cmd);

        // Verbatim, all the way to Clap: a non-UTF8 argument is a real argument.
        let args: Vec<std::ffi::OsString> = itr.into_iter().map(Into::into).collect();

        let matches = match self.parse_with_default_command(&cmd, &args) {
            Ok(matches) => matches,
            Err(ParseFailure::UnknownDefault(e)) => {
                return HelpResult::Error(
                    cmd.clone()
                        .error(clap::error::ErrorKind::InvalidSubcommand, e.to_string()),
                )
            }
            Err(ParseFailure::Clap(e)) => {
                return match self.intercept_display_help(&mut cmd, &args, &e) {
                    Some(display) => display.into(),
                    None => HelpResult::Error(e),
                }
            }
        };

        match self.intercept_help_word(&mut cmd, &matches) {
            Some(display) => display.into(),
            None => HelpResult::Matches(matches),
        }
    }

    /// Answers the `help` word, when Clap routed the line to it.
    ///
    /// The word is a declared subcommand, so Clap parses it and its arguments
    /// like any other; this reads the result. `None` means the line went
    /// somewhere else, which is when the caller's matches stand.
    ///
    /// Both parse paths call this on their parse, so `get_matches_from` and
    /// `dispatch_from` answer the word identically.
    pub(crate) fn intercept_help_word(
        &self,
        cmd: &mut Command,
        matches: &ArgMatches,
    ) -> Option<HelpDisplay> {
        if !self.help_handling {
            return None;
        }
        let (name, sub_matches) = matches.subcommand()?;
        (name == "help").then(|| self.render_help_word(cmd, matches, sub_matches))
    }

    /// Answers Clap's `DisplayHelp` short-circuit, when standout owns help.
    ///
    /// Clap's native `--help`/`-h` is kept on purpose — it short-circuits
    /// argument validation — so the request arrives as an "error" from the
    /// authoritative parse. Both parse paths hand it here to be rendered
    /// through standout instead of surfaced as Clap's own text. `None` means
    /// the error was not a help request (or standout does not own help), and
    /// belongs to the caller.
    pub(crate) fn intercept_display_help(
        &self,
        cmd: &mut Command,
        args: &[std::ffi::OsString],
        error: &clap::Error,
    ) -> Option<HelpDisplay> {
        (self.help_handling && error.kind() == clap::error::ErrorKind::DisplayHelp)
            .then(|| self.render_help_for_display_help_error(cmd, args))
    }

    /// Renders the help the `help` word asked for.
    ///
    /// Its arguments come from Clap: `sub_matches` is the word's own parse
    /// (`topic`, `--page`), and the output mode is read from the root, where
    /// the global flag that carries it lives.
    fn render_help_word(
        &self,
        cmd: &mut Command,
        matches: &ArgMatches,
        sub_matches: &ArgMatches,
    ) -> HelpDisplay {
        let config = HelpConfig {
            output_mode: Some(self.extract_output_mode(matches)),
            theme: self.theme.clone(),
            command_groups: self.help_command_groups.clone(),
            ..Default::default()
        };
        let use_pager = sub_matches.get_flag("page");

        if let Some(topic_args) = sub_matches.get_many::<String>("topic") {
            let keywords: Vec<_> = topic_args.map(|s| s.as_str()).collect();
            if !keywords.is_empty() {
                return self.handle_help_request(cmd, &keywords, use_pager, Some(config));
            }
        }

        self.render_root_help(cmd, Some(config), use_pager)
    }

    /// Reports a failed help render.
    ///
    /// Every rendering step funnels here, because a broken template or theme is
    /// the application's bug however help was asked for. Reporting it as
    /// [`HelpDisplay::RenderFailed`] is what keeps it from reaching the user as
    /// a usage error — or, worse, as "that topic wasn't recognized", which is
    /// what a swallowed render failure used to look like.
    fn render_failure(cmd: &Command, error: impl std::fmt::Display) -> HelpDisplay {
        HelpDisplay::RenderFailed(cmd.clone().error(
            clap::error::ErrorKind::Io,
            format!("failed to render help: {error}"),
        ))
    }

    /// Renders root help, returning an error if rendering fails.
    fn render_root_help(
        &self,
        cmd: &Command,
        config: Option<HelpConfig>,
        use_pager: bool,
    ) -> HelpDisplay {
        match render_help_with_topics(cmd, &self.registry, config) {
            Ok(text) => HelpDisplay::Rendered {
                text,
                paged: use_pager,
            },
            Err(e) => Self::render_failure(cmd, e),
        }
    }

    /// Handles a `DisplayHelp` error from clap by rendering standout help.
    ///
    /// Which command's help to render is Clap's answer, not a reading of the
    /// arguments: `--help` short-circuits before producing matches and its
    /// error does not name the command it was raised for, so the line is handed
    /// back to Clap with the help flag disabled. Everything that could name a
    /// command precedes the flag, so `ignore_errors` tolerating the now-unknown
    /// flag (and whatever follows it) costs nothing here.
    ///
    /// No output mode is threaded through: the request short-circuited, so
    /// `--output` written after it was never parsed, and honouring only the
    /// half written before it would make the mode depend on where the user put
    /// it. The render falls back to [`OutputMode::Auto`]; the `help` word does
    /// honour the flag, because Clap parses the word's line in full. The
    /// asymmetry is documented in `docs/topics/standout-help.md`.
    fn render_help_for_display_help_error(
        &self,
        cmd: &mut Command,
        args: &[std::ffi::OsString],
    ) -> HelpDisplay {
        let target = Self::help_target(cmd, args);

        let config = HelpConfig {
            theme: self.theme.clone(),
            command_groups: self.help_command_groups.clone(),
            ..Default::default()
        };

        if target.is_empty() {
            return self.render_root_help(cmd, Some(config), false);
        }

        let keywords: Vec<&str> = target.iter().map(|s| s.as_str()).collect();
        self.handle_help_request(cmd, &keywords, false, Some(config))
    }

    /// The command chain a help request was raised for, as Clap reads it.
    ///
    /// Empty means the root. Disabling the help flag is what lets the parse run
    /// far enough to answer: with it enabled the parse short-circuits again and
    /// reports nothing.
    fn help_target(cmd: &Command, args: &[std::ffi::OsString]) -> Vec<String> {
        let Ok(matches) = cmd
            .clone()
            .disable_help_flag(true)
            .ignore_errors(true)
            .try_get_matches_from(args)
        else {
            return Vec::new();
        };

        let mut chain = Vec::new();
        let mut current = &matches;
        while let Some((name, sub)) = current.subcommand() {
            chain.push(name.to_string());
            current = sub;
        }
        chain
    }

    /// Handles a request for specific help e.g. `help foo`
    fn handle_help_request(
        &self,
        cmd: &mut Command,
        keywords: &[&str],
        use_pager: bool,
        config: Option<HelpConfig>,
    ) -> HelpDisplay {
        let sub_name = keywords[0];

        // 0. Check for "topics" - list all available topics
        if sub_name == "topics" {
            let topic_config = TopicRenderConfig {
                output_mode: config.as_ref().and_then(|c| c.output_mode),
                theme: config.as_ref().and_then(|c| c.theme.clone()),
                ..Default::default()
            };
            return match render_topics_list(
                &self.registry,
                &format!("{} help", cmd.get_name()),
                Some(topic_config),
            ) {
                Ok(text) => HelpDisplay::Rendered {
                    text,
                    paged: use_pager,
                },
                Err(e) => Self::render_failure(cmd, e),
            };
        }

        // 1. Check if it's a real command
        if super::app::find_subcommand(cmd, sub_name).is_some() {
            if let Some(target) = super::app::find_subcommand_recursive(cmd, keywords) {
                return match render_help(target, config.clone()) {
                    Ok(text) => HelpDisplay::Rendered {
                        text,
                        paged: use_pager,
                    },
                    Err(e) => Self::render_failure(cmd, e),
                };
            }
        }

        // 2. Check if it is a topic
        if let Some(topic) = self.registry.get_topic(sub_name) {
            let topic_config = TopicRenderConfig {
                output_mode: config.as_ref().and_then(|c| c.output_mode),
                theme: config.as_ref().and_then(|c| c.theme.clone()),
                ..Default::default()
            };
            return match render_topic(topic, Some(topic_config)) {
                Ok(text) => HelpDisplay::Rendered {
                    text,
                    paged: use_pager,
                },
                Err(e) => Self::render_failure(cmd, e),
            };
        }

        // 3. Not found
        let err = cmd.error(
            clap::error::ErrorKind::InvalidSubcommand,
            format!("The subcommand or topic '{}' wasn't recognized", sub_name),
        );
        HelpDisplay::Clap(err)
    }

    /// Augments a command with the `help` word and output flags.
    ///
    /// When `help_handling` is enabled, this disables clap's built-in help
    /// subcommand and installs standout's own, where the install policy allows
    /// it (see [`help_word`](Self::help_word)). Clap's native
    /// `--help`/`-h` flag is kept so it short-circuits arg validation (showing
    /// help even when required args are missing), but `DisplayHelp` errors are
    /// intercepted — by `get_matches_from` and `dispatch_from` alike — and
    /// rendered through standout.
    ///
    /// When `help_handling` is disabled, clap's built-in help is left intact.
    ///
    /// Both parse paths augment through here, so the word's install policy is
    /// the command's shape and never the entry point the application chose.
    ///
    /// # Ordering: shape-dependent decisions come last
    ///
    /// The framework's own surface is augmented **first**, and only then is the
    /// install policy evaluated. The rule behind that is general, and this is
    /// the easiest place to break it:
    ///
    /// > A decision that branches on the command's *assembled* shape may only
    /// > be evaluated once all structural augmentation has completed.
    ///
    /// [`augment_framework_surface`](Self::augment_framework_surface) is the
    /// augmentation in question: it injects the questionnaire surface through
    /// `augment_questionnaire_commands`, which adds a `questions` subcommand at
    /// every registered questionnaire path — the root included. So a root that
    /// declares no subcommands of its own can still have one by the time a user
    /// meets it, and "does this root have subcommands?" asked any earlier
    /// answers for a shape nobody runs.
    ///
    /// [`installs_help_word`](Self::installs_help_word) is the only such
    /// decision today. A second one belongs below the same line, not above it.
    ///
    /// The opposite constraint exists and is not a contradiction: the
    /// questionnaire *validators* (`validate_questionnaire_surfaces`,
    /// `validate_command_groups`) read the shape the application author wrote,
    /// precisely to catch names that collide with what the framework is about
    /// to inject, so they run before augmentation and must keep doing so.
    pub fn augment_command_with_help(&self, cmd: Command) -> Command {
        let cmd = self.augment_framework_surface(cmd);

        if !self.help_handling {
            return cmd;
        }

        // Disable clap's help subcommand and replace with standout's.
        // Keep clap's native --help/-h flag — it short-circuits validation
        // so `myapp subcmd --help` works even with required args.
        // The resulting DisplayHelp error is intercepted by both parse paths.
        let cmd = cmd.disable_help_subcommand(true);
        if self.installs_help_word(&cmd) {
            // `subcommand_negates_reqs` is what makes the installed word
            // reachable: without it a root that requires arguments rejects
            // `myapp help` before Clap can route it, which is the defect this
            // whole surface exists to fix. It is set *here*, and only here,
            // because it relaxes the root's requirements for the application's
            // own subcommands too — a semantic an app that did not get the word
            // never asked for.
            cmd.subcommand(help_word_command())
                .subcommand_negates_reqs(true)
        } else {
            cmd
        }
    }

    /// Whether the bare `help` word is installed on this root.
    ///
    /// Installing it reserves the word out of the root's data namespace, which
    /// is only standout's call to make when nothing else could claim it:
    ///
    /// - the root **has subcommands** — a bare word there is already a command;
    /// - the root is **flat with no positionals** — there is nothing to collide
    ///   with;
    /// - the root is **flat with positionals** — a bare word is data
    ///   (`echo help`), so the word is installed only behind
    ///   [`help_word(true)`](Self::help_word).
    ///
    /// `--help` / `-h` are unaffected either way: they are Clap's flags, always
    /// present, and their `DisplayHelp` is rendered through standout.
    ///
    /// # `cmd` must be the assembled command
    ///
    /// This branches on the command's shape, so it may only be asked once all
    /// structural augmentation has run: the framework injects subcommands of
    /// its own (the questionnaire `questions` command, at the root among other
    /// paths), and a root that gains one is a root where a bare word is already
    /// a command. [`augment_command_with_help`](Self::augment_command_with_help)
    /// is the only caller and orders itself accordingly — see the ordering rule
    /// on it, which is the general form of this requirement and the thing to
    /// preserve if a second shape-dependent decision is ever added.
    pub(crate) fn installs_help_word(&self, cmd: &Command) -> bool {
        self.help_word
            || cmd.get_subcommands().next().is_some()
            || cmd.get_positionals().next().is_none()
    }

    /// Extracts the output mode from parsed ArgMatches.
    pub fn extract_output_mode(&self, matches: &ArgMatches) -> OutputMode {
        if self.output_flag.is_some() {
            match matches
                .get_one::<String>("_output_mode")
                .map(|s| s.as_str())
            {
                Some("term") => OutputMode::Term,
                Some("text") => OutputMode::Text,
                Some("term-debug") => OutputMode::TermDebug,
                Some("json") => OutputMode::Json,
                Some("yaml") => OutputMode::Yaml,
                Some("xml") => OutputMode::Xml,
                Some("csv") => OutputMode::Csv,
                _ => OutputMode::Auto,
            }
        } else {
            OutputMode::Auto
        }
    }

    // =========================================================================
    // Manual Command Execution
    // =========================================================================

    /// Executes a command handler with hooks applied automatically.
    ///
    /// This is for when you handle dispatch manually but still want
    /// to benefit from registered hooks.
    ///
    /// The method:
    /// 1. Runs pre-dispatch hooks (if any)
    /// 2. Calls your handler closure
    /// 3. Renders the result using the template
    /// 4. Runs post-output hooks (if any)
    /// 5. Returns the final output
    ///
    /// # Final writes
    ///
    /// This is the manual-dispatch seam, so it performs no final write. An
    /// [`Output::Artifact`](crate::cli::Output::Artifact) comes back as
    /// [`RenderedOutput::Artifact`] with its report serialized but not
    /// rendered: destination selection, the write, and the receipt-bearing
    /// report belong to [`dispatch`](Self::dispatch) / [`run`](Self::run),
    /// which own that transaction end to end.
    pub fn run_command<F, T>(
        &self,
        path: &str,
        matches: &ArgMatches,
        handler: F,
        template: &str,
    ) -> Result<RenderedOutput, HookError>
    where
        F: FnOnce(&ArgMatches, &CommandContext) -> HandlerResult<T>,
        T: Serialize,
    {
        let mut ctx = CommandContext::new(
            path.split('.').map(String::from).collect(),
            self.app_state.clone(),
        );

        let hooks = self.command_hooks.get(path);

        // Run pre-dispatch hooks
        if let Some(hooks) = hooks {
            hooks.run_pre_dispatch(matches, &mut ctx)?;
        }

        // Run handler
        let result = handler(matches, &ctx);

        // Convert result to RenderedOutput
        let output = match result {
            Ok(HandlerOutput::Render(data)) => {
                let mut json_data = serde_json::to_value(&data)
                    .map_err(|e| HookError::post_dispatch("Serialization error").with_source(e))?;

                if let Some(hooks) = hooks {
                    json_data = hooks.run_post_dispatch(matches, &ctx, json_data)?;
                }

                let theme = self.theme.clone().unwrap_or_default();
                match render_auto(template, &json_data, &theme, OutputMode::Auto) {
                    Ok(rendered) => RenderedOutput::Text(TextOutput::plain(rendered)),
                    Err(e) => return Err(HookError::post_output("Render error").with_source(e)),
                }
            }
            Err(e) => {
                return Err(HookError::post_output("Handler error").with_source(e));
            }
            Ok(HandlerOutput::Silent) => RenderedOutput::Silent,
            Ok(HandlerOutput::Binary { data, filename }) => RenderedOutput::Binary(data, filename),
            Ok(HandlerOutput::Artifact(artifact)) => {
                let (bytes, suggested_destination, stdout_allowed, report) = artifact.into_parts();
                let report = match report {
                    Some(report) => {
                        let mut json = serde_json::to_value(&report).map_err(|e| {
                            HookError::post_dispatch("Serialization error").with_source(e)
                        })?;
                        if let Some(hooks) = hooks {
                            json = hooks.run_post_dispatch(matches, &ctx, json)?;
                        }
                        Some(json)
                    }
                    None => None,
                };
                RenderedOutput::Artifact(ArtifactOutput {
                    bytes,
                    suggested_destination,
                    stdout_allowed,
                    report,
                })
            }
            Ok(_) => {
                return Err(HookError::post_output(
                    "Unsupported handler output variant: this standout version cannot present it",
                ));
            }
        };

        // Run post-output hooks
        if let Some(hooks) = hooks {
            hooks.run_post_output(matches, &ctx, output)
        } else {
            Ok(output)
        }
    }

    // =========================================================================
    // Verification
    // =========================================================================

    /// Verifies that registered handlers match the CLI command definition.
    ///
    /// Checks that all required arguments expected by handlers are present
    /// in the clap Command definition with compatible types.
    pub fn verify_command(&self, cmd: &Command) -> Result<(), SetupError> {
        self.validate_questionnaire_surfaces(cmd)?;
        let expected_args: HashMap<String, Vec<ExpectedArg>> = self
            .pending_commands
            .borrow()
            .iter()
            .map(|(path, cmd)| (path.clone(), cmd.recipe.expected_args()))
            .collect();
        super::app::verify_recursive(cmd, &expected_args, &[], true)
    }
}

/// Standout's `help` word, the replacement for clap's built-in one.
///
/// Built in one place because it is both installed on the root and parsed
/// standalone when the word is dispatched, and the two must agree on what
/// arguments the word takes.
fn help_word_command() -> Command {
    Command::new("help")
        .about("Print this message or the help of the given subcommand(s)")
        .arg(
            Arg::new("topic")
                .action(ArgAction::Set)
                .num_args(1..)
                .help("The subcommand or topic to print help for"),
        )
        .arg(
            Arg::new("page")
                .long("page")
                .action(ArgAction::SetTrue)
                .help("Display help through a pager"),
        )
}

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

    #[test]
    fn test_builder_output_flag_enabled_by_default() {
        let standout = AppBuilder::new().build().unwrap();
        assert!(standout.output_flag.is_some());
        assert_eq!(standout.output_flag.as_deref(), Some("output"));
    }

    #[test]
    fn test_no_output_flag() {
        let standout = AppBuilder::new().no_output_flag().build().unwrap();
        assert!(standout.output_flag.is_none());
    }

    #[test]
    fn test_custom_output_flag_name() {
        let standout = AppBuilder::new()
            .output_flag(Some("format"))
            .build()
            .unwrap();
        assert_eq!(standout.output_flag.as_deref(), Some("format"));
    }

    #[test]
    fn test_theme_fallback_precedence() {
        use std::fs;
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();

        // Create base.yaml
        fs::write(temp_dir.path().join("base.yaml"), "style: { fg: blue }").unwrap();

        // 1. Only base exists
        let app = AppBuilder::new()
            .styles_dir(temp_dir.path())
            .unwrap()
            .build()
            .unwrap();

        assert!(app.theme.is_some());
        let theme = app.theme.as_ref().unwrap();
        assert_eq!(theme.name(), Some("base"));

        // 2. theme.yaml exists (should override base)
        fs::write(temp_dir.path().join("theme.yaml"), "style: { fg: red }").unwrap();

        let app = AppBuilder::new()
            .styles_dir(temp_dir.path())
            .unwrap()
            .build()
            .unwrap();

        assert_eq!(app.theme.as_ref().unwrap().name(), Some("theme"));

        // 3. default.yaml exists (should override theme)
        fs::write(temp_dir.path().join("default.yaml"), "style: { fg: green }").unwrap();

        let app = AppBuilder::new()
            .styles_dir(temp_dir.path())
            .unwrap()
            .build()
            .unwrap();

        assert_eq!(app.theme.as_ref().unwrap().name(), Some("default"));
    }

    // ============================================================================
    // App State Tests
    // ============================================================================

    #[test]
    fn test_app_state_single_type() {
        struct Database {
            url: String,
        }

        let app = AppBuilder::new()
            .app_state(Database {
                url: "postgres://localhost".into(),
            })
            .build()
            .unwrap();

        let db = app.app_state.get::<Database>().unwrap();
        assert_eq!(db.url, "postgres://localhost");
    }

    #[test]
    fn test_app_state_multiple_types() {
        struct Database {
            url: String,
        }
        struct Config {
            debug: bool,
        }

        let app = AppBuilder::new()
            .app_state(Database {
                url: "postgres://localhost".into(),
            })
            .app_state(Config { debug: true })
            .build()
            .unwrap();

        let db = app.app_state.get::<Database>().unwrap();
        assert_eq!(db.url, "postgres://localhost");

        let config = app.app_state.get::<Config>().unwrap();
        assert!(config.debug);
    }

    #[test]
    fn test_app_state_replacement() {
        struct Config {
            value: i32,
        }

        let app = AppBuilder::new()
            .app_state(Config { value: 1 })
            .app_state(Config { value: 2 }) // Replaces first
            .build()
            .unwrap();

        let config = app.app_state.get::<Config>().unwrap();
        assert_eq!(config.value, 2);
    }

    #[test]
    fn test_app_state_empty_by_default() {
        struct NotSet;

        let app = AppBuilder::new().build().unwrap();

        assert!(app.app_state.is_empty());
        assert!(app.app_state.get::<NotSet>().is_none());
    }
}