osp-cli 1.5.1

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

pub use crate::core::shell_words::QuoteStyle;
use std::{collections::BTreeMap, ops::Range};

/// Semantic type for values completed by the engine.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ValueType {
    /// Filesystem path value.
    Path,
}

/// Replacement details for the token currently being completed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CursorState {
    /// Normalized token text used for matching suggestions.
    pub token_stub: String,
    /// Raw slice from the input buffer that will be replaced.
    pub raw_stub: String,
    /// Byte range in the input buffer that should be replaced.
    pub replace_range: Range<usize>,
    /// Quote style active at the cursor, if the token is quoted.
    pub quote_style: Option<QuoteStyle>,
}

impl CursorState {
    /// Creates a cursor state from explicit replacement data.
    ///
    /// `raw_stub` keeps the exact buffer slice that will be replaced, while
    /// `token_stub` keeps the normalized text used for matching.
    ///
    /// # Examples
    ///
    /// ```
    /// use osp_cli::completion::{CursorState, QuoteStyle};
    ///
    /// let state = CursorState::new("tok", "\"tok", 3..7, Some(QuoteStyle::Double));
    ///
    /// assert_eq!(state.token_stub, "tok");
    /// assert_eq!(state.raw_stub, "\"tok");
    /// assert_eq!(state.replace_range, 3..7);
    /// assert_eq!(state.quote_style, Some(QuoteStyle::Double));
    /// ```
    pub fn new(
        token_stub: impl Into<String>,
        raw_stub: impl Into<String>,
        replace_range: Range<usize>,
        quote_style: Option<QuoteStyle>,
    ) -> Self {
        Self {
            token_stub: token_stub.into(),
            raw_stub: raw_stub.into(),
            replace_range,
            quote_style,
        }
    }

    /// Creates a synthetic cursor state for a standalone token stub.
    ///
    /// This is useful in tests and non-editor callers that only care about a
    /// single token rather than a full input buffer.
    ///
    /// # Examples
    ///
    /// ```
    /// use osp_cli::completion::CursorState;
    ///
    /// let state = CursorState::synthetic("ldap");
    ///
    /// assert_eq!(state.raw_stub, "ldap");
    /// assert_eq!(state.replace_range, 0..4);
    /// ```
    pub fn synthetic(token_stub: impl Into<String>) -> Self {
        let token_stub = token_stub.into();
        let len = token_stub.len();
        Self {
            raw_stub: token_stub.clone(),
            token_stub,
            replace_range: 0..len,
            quote_style: None,
        }
    }
}

impl Default for CursorState {
    fn default() -> Self {
        Self::synthetic("")
    }
}

/// Scope used when merging context-only flags into the cursor view.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum ContextScope {
    /// Merge the flag regardless of the matched command path.
    Global,
    /// Merge the flag only within the matched subtree.
    #[default]
    Subtree,
}

/// Suggestion payload shown to the user and inserted on accept.
///
/// This separates the inserted value from the optional display label so menu
/// UIs can stay human-friendly without changing what lands in the buffer.
#[derive(Debug, Clone, PartialEq, Eq)]
#[must_use]
pub struct SuggestionEntry {
    /// Text inserted into the buffer if this suggestion is accepted.
    pub value: String,
    /// Short right-column description in menu-style UIs.
    pub meta: Option<String>,
    /// Optional human-friendly label when the inserted value should stay terse.
    pub display: Option<String>,
    /// Hidden sort key for cases where display order should differ from labels.
    pub sort: Option<String>,
}

impl SuggestionEntry {
    /// Creates a suggestion that inserts `value`.
    pub fn value(value: impl Into<String>) -> Self {
        Self {
            value: value.into(),
            meta: None,
            display: None,
            sort: None,
        }
    }

    /// Sets the right-column metadata text.
    ///
    /// If omitted, menu-style UIs show no metadata for this suggestion.
    pub fn meta(mut self, meta: impl Into<String>) -> Self {
        self.meta = Some(meta.into());
        self
    }

    /// Sets the human-friendly label shown in menus.
    ///
    /// If omitted, UIs can fall back to the inserted value.
    pub fn display(mut self, display: impl Into<String>) -> Self {
        self.display = Some(display.into());
        self
    }

    /// Sets the hidden sort key for this suggestion.
    ///
    /// If omitted, the suggestion carries no explicit sort hint.
    pub fn sort(mut self, sort: impl Into<String>) -> Self {
        self.sort = Some(sort.into());
        self
    }
}

impl From<&str> for SuggestionEntry {
    fn from(value: &str) -> Self {
        Self::value(value)
    }
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
/// OS version suggestions shared globally or scoped by provider.
pub struct OsVersions {
    /// Suggestions indexed by OS name across all providers.
    pub union: BTreeMap<String, Vec<SuggestionEntry>>,
    /// Suggestions indexed first by provider, then by OS name.
    pub by_provider: BTreeMap<String, BTreeMap<String, Vec<SuggestionEntry>>>,
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
/// Request-form hints used to derive flag and value suggestions.
pub struct RequestHints {
    /// Known request keys.
    pub keys: Vec<String>,
    /// Request keys that must be present.
    pub required: Vec<String>,
    /// Allowed values grouped by tier.
    pub tiers: BTreeMap<String, Vec<String>>,
    /// Default values by request key.
    pub defaults: BTreeMap<String, String>,
    /// Explicit value choices by request key.
    pub choices: BTreeMap<String, Vec<String>>,
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
/// Request hints shared globally and overridden by provider.
pub struct RequestHintSet {
    /// Hints available regardless of provider.
    pub common: RequestHints,
    /// Provider-specific request hints.
    pub by_provider: BTreeMap<String, RequestHints>,
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
/// Flag-name hints shared globally and overridden by provider.
pub struct FlagHints {
    /// Optional flags available regardless of provider.
    pub common: Vec<String>,
    /// Optional flags available for specific providers.
    pub by_provider: BTreeMap<String, Vec<String>>,
    /// Required flags available regardless of provider.
    pub required_common: Vec<String>,
    /// Required flags available for specific providers.
    pub required_by_provider: BTreeMap<String, Vec<String>>,
}

/// Positional argument definition for one command slot.
///
/// This is declarative completion metadata, not parser state. One `ArgNode`
/// says what a command slot expects once command-path resolution has reached the
/// owning node.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[must_use]
pub struct ArgNode {
    /// Argument name shown in completion UIs.
    pub name: Option<String>,
    /// Optional description shown alongside the argument.
    pub tooltip: Option<String>,
    /// Whether the argument may consume multiple values.
    pub multi: bool,
    /// Semantic type for the argument value.
    pub value_type: Option<ValueType>,
    /// Suggested values for the argument.
    pub suggestions: Vec<SuggestionEntry>,
}

impl ArgNode {
    /// Creates an argument node with a visible argument name.
    ///
    /// # Examples
    ///
    /// ```
    /// use osp_cli::completion::{ArgNode, SuggestionEntry, ValueType};
    ///
    /// let entry = SuggestionEntry::value("alma")
    ///     .meta("linux")
    ///     .display("AlmaLinux")
    ///     .sort("02");
    /// let arg = ArgNode::named("image")
    ///     .tooltip("Image name")
    ///     .multi()
    ///     .value_type(ValueType::Path)
    ///     .suggestions([entry.clone()]);
    ///
    /// assert_eq!(entry.meta.as_deref(), Some("linux"));
    /// assert_eq!(entry.display.as_deref(), Some("AlmaLinux"));
    /// assert_eq!(entry.sort.as_deref(), Some("02"));
    /// assert_eq!(arg.name.as_deref(), Some("image"));
    /// assert_eq!(arg.tooltip.as_deref(), Some("Image name"));
    /// assert!(arg.multi);
    /// assert_eq!(arg.value_type, Some(ValueType::Path));
    /// assert_eq!(arg.suggestions, vec![entry]);
    /// ```
    pub fn named(name: impl Into<String>) -> Self {
        Self {
            name: Some(name.into()),
            ..Self::default()
        }
    }

    /// Sets the display tooltip for this argument.
    ///
    /// If omitted, completion UIs show no description for this argument.
    pub fn tooltip(mut self, tooltip: impl Into<String>) -> Self {
        self.tooltip = Some(tooltip.into());
        self
    }

    /// Marks this argument as accepting multiple values.
    ///
    /// If omitted, the argument accepts a single value.
    pub fn multi(mut self) -> Self {
        self.multi = true;
        self
    }

    /// Sets the semantic value type for this argument.
    ///
    /// If omitted, the argument carries no special value-type hint.
    pub fn value_type(mut self, value_type: ValueType) -> Self {
        self.value_type = Some(value_type);
        self
    }

    /// Replaces the suggestion list for this argument.
    ///
    /// If omitted, the argument contributes no direct value suggestions.
    pub fn suggestions(mut self, suggestions: impl IntoIterator<Item = SuggestionEntry>) -> Self {
        self.suggestions = suggestions.into_iter().collect();
        self
    }
}

/// Completion metadata for a flag spelling.
///
/// Flags can contribute both direct value suggestions and context that affects
/// later completion. `context_only` flags are the bridge for options that shape
/// suggestion scope even when the cursor is not currently editing that flag.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[must_use]
pub struct FlagNode {
    /// Optional description shown alongside the flag.
    pub tooltip: Option<String>,
    /// Whether the flag does not accept a value.
    pub flag_only: bool,
    /// Whether the flag may be repeated.
    pub multi: bool,
    // Context-only flags are merged from the full line into the cursor context.
    // `context_scope` controls whether merge is global or path-scoped.
    /// Whether the flag should be merged from the full line into cursor context.
    pub context_only: bool,
    /// Scope used when merging a context-only flag.
    pub context_scope: ContextScope,
    /// Semantic type for the flag value, if any.
    pub value_type: Option<ValueType>,
    /// Generic suggestions for the flag value.
    pub suggestions: Vec<SuggestionEntry>,
    /// Provider-specific value suggestions.
    pub suggestions_by_provider: BTreeMap<String, Vec<SuggestionEntry>>,
    /// Allowed providers by OS name.
    pub os_provider_map: BTreeMap<String, Vec<String>>,
    /// OS version suggestions attached to this flag.
    pub os_versions: Option<OsVersions>,
    /// Request-form hints attached to this flag.
    pub request_hints: Option<RequestHintSet>,
    /// Extra flag-name hints attached to this flag.
    pub flag_hints: Option<FlagHints>,
}

impl FlagNode {
    /// Creates an empty flag node.
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the display tooltip for this flag.
    ///
    /// If omitted, completion UIs show no description for this flag.
    pub fn tooltip(mut self, tooltip: impl Into<String>) -> Self {
        self.tooltip = Some(tooltip.into());
        self
    }

    /// Marks this flag as taking no value.
    ///
    /// If omitted, the flag is treated as value-taking when the surrounding
    /// completion metadata asks for values.
    pub fn flag_only(mut self) -> Self {
        self.flag_only = true;
        self
    }

    /// Marks this flag as repeatable.
    ///
    /// If omitted, the flag is treated as non-repeatable.
    pub fn multi(mut self) -> Self {
        self.multi = true;
        self
    }

    /// Marks this flag as context-only within the given scope.
    ///
    /// If omitted, later occurrences of the flag are not merged into cursor
    /// context unless the user is actively editing that flag.
    pub fn context_only(mut self, scope: ContextScope) -> Self {
        self.context_only = true;
        self.context_scope = scope;
        self
    }

    /// Sets the semantic value type for this flag.
    ///
    /// If omitted, the flag carries no special value-type hint.
    pub fn value_type(mut self, value_type: ValueType) -> Self {
        self.value_type = Some(value_type);
        self
    }

    /// Replaces the suggestion list for this flag value.
    ///
    /// If omitted, the flag contributes no direct generic value suggestions.
    pub fn suggestions(mut self, suggestions: impl IntoIterator<Item = SuggestionEntry>) -> Self {
        self.suggestions = suggestions.into_iter().collect();
        self
    }
}

/// One node in the immutable completion tree.
///
/// A node owns the completion contract for one resolved command scope:
/// subcommands, flags, positional arguments, and any hidden defaults inherited
/// through aliases or shell scope.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[must_use]
pub struct CompletionNode {
    /// Optional description shown alongside the node.
    pub tooltip: Option<String>,
    /// Optional suggestion-order hint for command/subcommand completion.
    pub sort: Option<String>,
    /// Whether an exact token should commit scope even without a trailing delimiter.
    pub exact_token_commits: bool,
    /// This node expects the next token to be a key chosen from `children`.
    pub value_key: bool,
    /// This node is itself a terminal value that can be suggested/accepted.
    pub value_leaf: bool,
    /// Hidden context flags injected when this node is matched.
    pub prefilled_flags: BTreeMap<String, Vec<String>>,
    /// Fixed positional values contributed before user-provided args.
    pub prefilled_positionals: Vec<String>,
    /// Nested subcommands or value-like children.
    pub children: BTreeMap<String, CompletionNode>,
    /// Flags visible in this command scope.
    pub flags: BTreeMap<String, FlagNode>,
    /// Positional arguments accepted in this command scope.
    pub args: Vec<ArgNode>,
    /// Extra flag-name hints contributed by this node.
    pub flag_hints: Option<FlagHints>,
}

impl CompletionNode {
    /// Sets the hidden sort key for this node.
    pub fn sort(mut self, sort: impl Into<String>) -> Self {
        self.sort = Some(sort.into());
        self
    }

    /// Adds a child node keyed by command or value name.
    ///
    /// # Examples
    ///
    /// ```
    /// use osp_cli::completion::{
    ///     CompletionNode, ContextScope, FlagNode, SuggestionEntry, ValueType,
    /// };
    ///
    /// let flag = FlagNode::new()
    ///     .tooltip("Provider")
    ///     .flag_only()
    ///     .multi()
    ///     .context_only(ContextScope::Global)
    ///     .value_type(ValueType::Path)
    ///     .suggestions([SuggestionEntry::from("vmware")]);
    ///
    /// let node = CompletionNode::default()
    ///     .sort("01")
    ///     .with_child("status", CompletionNode::default())
    ///     .with_flag("--provider", flag.clone());
    ///
    /// assert_eq!(flag.tooltip.as_deref(), Some("Provider"));
    /// assert!(flag.flag_only);
    /// assert!(flag.multi);
    /// assert!(flag.context_only);
    /// assert_eq!(flag.context_scope, ContextScope::Global);
    /// assert_eq!(flag.value_type, Some(ValueType::Path));
    /// assert_eq!(flag.suggestions.len(), 1);
    /// assert_eq!(node.sort.as_deref(), Some("01"));
    /// assert!(node.children.contains_key("status"));
    /// assert_eq!(node.flags.get("--provider"), Some(&flag));
    /// ```
    pub fn with_child(mut self, name: impl Into<String>, node: CompletionNode) -> Self {
        self.children.insert(name.into(), node);
        self
    }

    /// Adds a flag node keyed by its spelling.
    pub fn with_flag(mut self, name: impl Into<String>, node: FlagNode) -> Self {
        self.flags.insert(name.into(), node);
        self
    }
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
/// Immutable completion data consumed by the engine.
pub struct CompletionTree {
    /// Root completion node for the command hierarchy.
    pub root: CompletionNode,
    /// Pipe verbs are kept separate from the command tree because they only
    /// become visible after the parser has entered DSL mode.
    pub pipe_verbs: BTreeMap<String, String>,
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
/// Parsed command-line structure before higher-level completion analysis.
pub struct CommandLine {
    /// Command path tokens matched before tail parsing starts.
    pub(crate) head: Vec<String>,
    /// Parsed flags and positional arguments after the command path.
    pub(crate) tail: Vec<TailItem>,
    /// Merged flag values keyed by spelling.
    pub(crate) flag_values: BTreeMap<String, Vec<String>>,
    /// Tokens that appear after the first pipe.
    pub(crate) pipes: Vec<String>,
    /// Whether the parser entered pipe mode.
    pub(crate) has_pipe: bool,
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
/// One occurrence of a flag and the values consumed with it.
pub struct FlagOccurrence {
    /// Flag spelling as it appeared in the input.
    pub name: String,
    /// Values consumed by this flag occurrence.
    pub values: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
/// Item in the parsed tail after the command path.
pub enum TailItem {
    /// A flag occurrence with any values it consumed.
    Flag(FlagOccurrence),
    /// A positional argument.
    Positional(String),
}

impl CommandLine {
    /// Returns the matched command path tokens.
    pub fn head(&self) -> &[String] {
        &self.head
    }

    /// Returns the parsed tail items after the command path.
    pub fn tail(&self) -> &[TailItem] {
        &self.tail
    }

    /// Returns tokens in the pipe segment, if present.
    pub fn pipes(&self) -> &[String] {
        &self.pipes
    }

    /// Returns whether the line entered pipe mode.
    pub fn has_pipe(&self) -> bool {
        self.has_pipe
    }

    /// Returns all merged flag values keyed by flag spelling.
    pub fn flag_values_map(&self) -> &BTreeMap<String, Vec<String>> {
        &self.flag_values
    }

    /// Returns values collected for one flag spelling.
    pub fn flag_values(&self, name: &str) -> Option<&[String]> {
        self.flag_values.get(name).map(Vec::as_slice)
    }

    /// Returns whether the command line contains the flag spelling.
    pub fn has_flag(&self, name: &str) -> bool {
        self.flag_values.contains_key(name)
    }

    /// Iterates over flag occurrences in input order.
    pub fn flag_occurrences(&self) -> impl Iterator<Item = &FlagOccurrence> {
        self.tail.iter().filter_map(|item| match item {
            TailItem::Flag(flag) => Some(flag),
            TailItem::Positional(_) => None,
        })
    }

    /// Returns the last flag occurrence, if any.
    pub fn last_flag_occurrence(&self) -> Option<&FlagOccurrence> {
        self.flag_occurrences().last()
    }

    /// Iterates over positional arguments in the tail.
    pub fn positional_args(&self) -> impl Iterator<Item = &String> {
        self.tail.iter().filter_map(|item| match item {
            TailItem::Positional(value) => Some(value),
            TailItem::Flag(_) => None,
        })
    }

    /// Returns the number of tail items.
    pub fn tail_len(&self) -> usize {
        self.tail.len()
    }

    /// Appends a flag occurrence and merges its values into the lookup map.
    #[cfg(test)]
    pub(crate) fn push_flag_occurrence(&mut self, occurrence: FlagOccurrence) {
        self.flag_values
            .entry(occurrence.name.clone())
            .or_default()
            .extend(occurrence.values.iter().cloned());
        self.tail.push(TailItem::Flag(occurrence));
    }

    /// Appends a positional argument to the tail.
    #[cfg(test)]
    pub(crate) fn push_positional(&mut self, value: impl Into<String>) {
        self.tail.push(TailItem::Positional(value.into()));
    }

    /// Merges additional values for a flag spelling.
    pub(crate) fn merge_flag_values(&mut self, name: impl Into<String>, values: Vec<String>) {
        self.flag_values
            .entry(name.into())
            .or_default()
            .extend(values);
    }

    /// Inserts positional values ahead of the existing tail.
    pub(crate) fn prepend_positional_values(&mut self, values: impl IntoIterator<Item = String>) {
        let mut values = values
            .into_iter()
            .filter(|value| !value.trim().is_empty())
            .map(TailItem::Positional)
            .collect::<Vec<_>>();
        if values.is_empty() {
            return;
        }
        values.extend(std::mem::take(&mut self.tail));
        self.tail = values;
    }

    /// Marks the command line as piped and stores the pipe tokens.
    #[cfg(test)]
    pub(crate) fn set_pipe(&mut self, pipes: Vec<String>) {
        self.has_pipe = true;
        self.pipes = pipes;
    }

    /// Appends one segment to the command path.
    #[cfg(test)]
    pub(crate) fn push_head(&mut self, segment: impl Into<String>) {
        self.head.push(segment.into());
    }
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
/// Parser output for the full line and the cursor-local prefix.
pub struct ParsedLine {
    /// Cursor offset clamped to a valid UTF-8 boundary.
    pub safe_cursor: usize,
    /// Tokens parsed from the full line.
    pub full_tokens: Vec<String>,
    /// Tokens parsed from the line prefix before the cursor.
    pub cursor_tokens: Vec<String>,
    /// Parsed command-line structure for the full line.
    pub full_cmd: CommandLine,
    /// Parsed command-line structure for the prefix before the cursor.
    pub cursor_cmd: CommandLine,
}

#[derive(Debug, Clone, PartialEq, Eq)]
/// Explicit request kind for the current cursor position.
pub enum CompletionRequest {
    /// Completing a DSL pipe verb.
    Pipe,
    /// Completing a flag spelling in the current flag scope.
    FlagNames {
        /// Command path that contributes visible flags.
        flag_scope_path: Vec<String>,
    },
    /// Completing values for a specific flag.
    FlagValues {
        /// Command path that contributes the flag definition.
        flag_scope_path: Vec<String>,
        /// Flag currently requesting values.
        flag: String,
    },
    /// Completing subcommands, positional values, or empty-stub flags.
    Positionals {
        /// Command path contributing subcommands or positional args.
        context_path: Vec<String>,
        /// Command path that contributes visible flags.
        flag_scope_path: Vec<String>,
        /// Positional argument index relative to the resolved command path.
        arg_index: usize,
        /// Whether subcommand names should be suggested.
        show_subcommands: bool,
        /// Whether empty-stub flag spellings should also be suggested.
        show_flag_names: bool,
    },
}

impl Default for CompletionRequest {
    fn default() -> Self {
        Self::Positionals {
            context_path: Vec::new(),
            flag_scope_path: Vec::new(),
            arg_index: 0,
            show_subcommands: false,
            show_flag_names: false,
        }
    }
}

impl CompletionRequest {
    /// Returns the stable request-kind label used by tests and debug surfaces.
    pub fn kind(&self) -> &'static str {
        match self {
            Self::Pipe => "pipe",
            Self::FlagNames { .. } => "flag-names",
            Self::FlagValues { .. } => "flag-values",
            Self::Positionals {
                show_subcommands: true,
                ..
            } => "subcommands",
            Self::Positionals { .. } => "positionals",
        }
    }
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
/// Full completion analysis derived from parsing and context resolution.
pub struct CompletionAnalysis {
    /// Full parser output plus the cursor-local context derived from it.
    pub parsed: ParsedLine,
    /// Replacement details for the active token.
    pub cursor: CursorState,
    /// Resolved command context used for suggestion generation.
    pub context: CompletionContext,
    /// Explicit request kind for suggestion generation.
    pub request: CompletionRequest,
}

/// Resolved completion state for the cursor position.
///
/// The parser only knows about tokens. This structure captures the derived
/// command context the suggester/debug layers actually care about:
/// which command path matched, which node contributes visible flags, and
/// whether the cursor is still in subcommand-selection mode.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct CompletionContext {
    /// Command path matched before the cursor.
    pub matched_path: Vec<String>,
    /// Command path that contributes visible flags.
    pub flag_scope_path: Vec<String>,
    /// Whether the cursor is completing a subcommand name.
    pub subcommand_context: bool,
}

/// High-level classification for a completion candidate.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MatchKind {
    /// Candidate belongs to pipe-mode completion.
    Pipe,
    /// Candidate is a flag spelling.
    Flag,
    /// Candidate is a top-level command.
    Command,
    /// Candidate is a nested subcommand.
    Subcommand,
    /// Candidate is a value or positional suggestion.
    Value,
}

impl MatchKind {
    /// Returns the stable string form used by presentation layers.
    ///
    /// # Examples
    ///
    /// ```
    /// use osp_cli::completion::MatchKind;
    ///
    /// let labels = [
    ///     MatchKind::Pipe,
    ///     MatchKind::Flag,
    ///     MatchKind::Command,
    ///     MatchKind::Subcommand,
    ///     MatchKind::Value,
    /// ]
    /// .into_iter()
    /// .map(MatchKind::as_str)
    /// .collect::<Vec<_>>();
    ///
    /// assert_eq!(labels, vec!["pipe", "flag", "command", "subcommand", "value"]);
    /// ```
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Pipe => "pipe",
            Self::Flag => "flag",
            Self::Command => "command",
            Self::Subcommand => "subcommand",
            Self::Value => "value",
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
/// Ranked suggestion ready for formatting or rendering.
pub struct Suggestion {
    /// Text inserted into the buffer if accepted.
    pub text: String,
    /// Short metadata shown alongside the suggestion.
    pub meta: Option<String>,
    /// Optional human-friendly label.
    pub display: Option<String>,
    /// Whether the suggestion exactly matches the current stub.
    pub is_exact: bool,
    /// Hidden sort key for ordering.
    pub sort: Option<String>,
    /// Numeric score used for ranking.
    pub match_score: u32,
}

impl Suggestion {
    /// Creates a suggestion with default ranking metadata.
    ///
    /// # Examples
    ///
    /// ```
    /// use osp_cli::completion::Suggestion;
    ///
    /// let suggestion = Suggestion::new("hello");
    ///
    /// assert_eq!(suggestion.text, "hello");
    /// assert_eq!(suggestion.meta, None);
    /// assert_eq!(suggestion.display, None);
    /// assert!(!suggestion.is_exact);
    /// assert_eq!(suggestion.sort, None);
    /// assert_eq!(suggestion.match_score, u32::MAX);
    /// ```
    pub fn new(text: impl Into<String>) -> Self {
        Self {
            text: text.into(),
            meta: None,
            display: None,
            is_exact: false,
            sort: None,
            match_score: u32::MAX,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
/// Output emitted by the suggestion engine.
pub enum SuggestionOutput {
    /// A normal suggestion item.
    Item(Suggestion),
    /// Sentinel indicating that filesystem path completion should run next.
    PathSentinel,
}

#[cfg(test)]
mod tests;