par-term-config 0.11.1

Configuration system for par-term terminal emulator
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
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
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
//! Configuration types for snippets and custom actions.
//!
//! This module provides:
//! - Snippet definitions with variable substitution
//! - Custom action definitions (shell commands, text insertion, key sequences)
//! - Built-in and custom variable support

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Default timeout for shell commands (30 seconds).
const fn default_shell_command_timeout_secs() -> u64 {
    30
}

/// A text snippet that can be inserted into the terminal.
///
/// Snippets support variable substitution using \(variable\) syntax.
/// Example: "echo 'Today is \(date)'" will replace \(date) with the current date.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct SnippetConfig {
    /// Unique identifier for the snippet
    pub id: String,

    /// Human-readable title for the snippet
    pub title: String,

    /// The text content to insert (may contain variables)
    pub content: String,

    /// Optional keyboard shortcut to trigger the snippet (e.g., "Ctrl+Shift+D")
    #[serde(default)]
    pub keybinding: Option<String>,

    /// Whether the keybinding is enabled (default: true)
    /// If false, the keybinding won't be registered even if keybinding is set
    #[serde(default = "crate::defaults::bool_true")]
    pub keybinding_enabled: bool,

    /// Optional folder/collection for organization (e.g., "Git", "Docker")
    #[serde(default)]
    pub folder: Option<String>,

    /// Whether this snippet is enabled
    #[serde(default = "crate::defaults::bool_true")]
    pub enabled: bool,

    /// Optional description of what the snippet does
    #[serde(default)]
    pub description: Option<String>,

    /// Whether to automatically send Enter after inserting the snippet (default: false)
    /// If true, a newline character is appended to execute the command immediately
    #[serde(default)]
    pub auto_execute: bool,

    /// Custom variables defined for this snippet
    #[serde(default)]
    pub variables: HashMap<String, String>,
}

impl SnippetConfig {
    /// Create a new snippet with the given ID and title.
    pub fn new(id: String, title: String, content: String) -> Self {
        Self {
            id,
            title,
            content,
            keybinding: None,
            keybinding_enabled: true,
            folder: None,
            enabled: true,
            description: None,
            auto_execute: false,
            variables: HashMap::new(),
        }
    }

    /// Add a keybinding to the snippet.
    pub fn with_keybinding(mut self, keybinding: String) -> Self {
        self.keybinding = Some(keybinding);
        self
    }

    /// Disable the keybinding for this snippet.
    pub fn with_keybinding_disabled(mut self) -> Self {
        self.keybinding_enabled = false;
        self
    }

    /// Add a folder to the snippet.
    pub fn with_folder(mut self, folder: String) -> Self {
        self.folder = Some(folder);
        self
    }

    /// Add a custom variable to the snippet.
    pub fn with_variable(mut self, name: String, value: String) -> Self {
        self.variables.insert(name, value);
        self
    }

    /// Enable auto-execute (send Enter after inserting the snippet).
    pub fn with_auto_execute(mut self) -> Self {
        self.auto_execute = true;
        self
    }
}

/// A portable snippet library for import/export.
///
/// Wraps a list of snippets for serialization to/from YAML files.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SnippetLibrary {
    /// The snippets in this library
    pub snippets: Vec<SnippetConfig>,
}

/// Default delay in ms before sending text to a newly split pane.
const fn default_split_pane_delay_ms() -> u64 {
    200
}

/// Normalize an action prefix character for matching and conflict detection.
///
/// ASCII letters are matched case-insensitively; all other characters remain exact.
pub fn normalize_action_prefix_char(ch: char) -> char {
    if ch.is_ascii_alphabetic() {
        ch.to_ascii_lowercase()
    } else {
        ch
    }
}

/// Default split percent: existing pane keeps 66% of the space.
const fn default_split_percent() -> u8 {
    66
}

/// The six fields that are identical across every [`CustomActionConfig`] variant.
///
/// # Note on `#[serde(flatten)]`
///
/// Serde does not support combining `#[serde(tag = "type")]` (internally tagged enum)
/// with `#[serde(flatten)]` on a variant field — the combination silently produces
/// incorrect output or a runtime error depending on the format. Therefore `ActionBase`
/// is **not** used as a flattened serde field inside the enum variants; the six fields
/// remain individually declared in each variant to preserve existing YAML compatibility.
///
/// `ActionBase` is used purely as a value-transfer helper in [`CustomActionConfig::base`]
/// and [`CustomActionConfig::apply_base`], which together eliminate the eight-arm match
/// repetition in every mutator method.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct ActionBase {
    /// Action identifier (for keybinding reference).
    pub id: String,
    /// Human-readable title.
    pub title: String,
    /// Optional keyboard shortcut.
    pub keybinding: Option<String>,
    /// Optional single character triggered after the global prefix key.
    pub prefix_char: Option<char>,
    /// Whether the keybinding is active (default: `true`).
    pub keybinding_enabled: bool,
    /// Optional human-readable description.
    pub description: Option<String>,
}

impl ActionBase {
    /// Create a minimal base with just an id and title.
    pub fn new(id: impl Into<String>, title: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            title: title.into(),
            keybinding: None,
            prefix_char: None,
            keybinding_enabled: true,
            description: None,
        }
    }
}

/// Split direction for a custom action pane split.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum ActionSplitDirection {
    /// New pane below (panes stacked top/bottom)
    #[default]
    Horizontal,
    /// New pane to the right (side by side)
    Vertical,
}

impl ActionSplitDirection {
    /// All directions for UI dropdowns.
    pub fn all() -> &'static [ActionSplitDirection] {
        &[Self::Horizontal, Self::Vertical]
    }

    /// Human-readable label.
    pub fn label(self) -> &'static str {
        match self {
            Self::Horizontal => "Horizontal (below)",
            Self::Vertical => "Vertical (right)",
        }
    }
}

/// What to do when a sequence step "fails".
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum SequenceStepBehavior {
    /// Halt sequence and show error toast (default).
    #[default]
    Abort,
    /// Halt sequence silently.
    Stop,
    /// Ignore failure and continue to the next step.
    Continue,
}

/// A single step in a Sequence action.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct SequenceStep {
    /// ID of the action to execute.
    pub action_id: String,
    /// Delay in milliseconds before this step runs (default: 0).
    #[serde(default)]
    pub delay_ms: u64,
    /// What to do if this step fails (default: Abort).
    #[serde(default)]
    pub on_failure: SequenceStepBehavior,
}

/// Condition to check for a Condition action.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum ConditionCheck {
    /// Check the exit code of the last captured ShellCommand.
    ExitCode { value: i32 },
    /// Check whether the last captured output contains a pattern.
    OutputContains {
        pattern: String,
        #[serde(default)]
        case_sensitive: bool,
    },
    /// Check an environment variable (None value = existence check only).
    EnvVar {
        name: String,
        #[serde(default)]
        value: Option<String>,
    },
    /// Glob match on the current terminal CWD.
    DirMatches { pattern: String },
    /// Glob match on the current git branch.
    GitBranch { pattern: String },
}

/// A custom action that can be triggered via keybinding.
///
/// Actions can execute shell commands, open a new tab, insert text, simulate key
/// sequences, or split the active pane.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum CustomActionConfig {
    /// Execute a shell command
    ShellCommand {
        /// Action identifier (for keybinding reference)
        id: String,

        /// Human-readable title
        title: String,

        /// Command to execute (e.g., "git", "npm")
        command: String,

        /// Command arguments (e.g., ["status", "--short"])
        #[serde(default)]
        args: Vec<String>,

        /// Whether to show command output in a notification
        #[serde(default)]
        notify_on_success: bool,

        /// Timeout in seconds for the command (default: 30)
        #[serde(default = "default_shell_command_timeout_secs")]
        timeout_secs: u64,

        /// Capture stdout+stderr into WorkflowContext for use by Sequence/Condition actions.
        /// When true, output is capped at 64 KB. Default: false.
        #[serde(default)]
        capture_output: bool,

        /// Optional keyboard shortcut to trigger the action (e.g., "Ctrl+Shift+R")
        #[serde(default)]
        keybinding: Option<String>,

        /// Optional single character triggered after the global custom action prefix key.
        #[serde(default)]
        prefix_char: Option<char>,

        /// Whether the keybinding is enabled (default: true)
        #[serde(default = "crate::defaults::bool_true")]
        keybinding_enabled: bool,

        /// Optional description
        #[serde(default)]
        description: Option<String>,
    },

    /// Open a new tab and optionally run a command in its shell
    NewTab {
        /// Action identifier
        id: String,

        /// Human-readable title
        title: String,

        /// Optional command to send to the new tab's shell after it opens
        #[serde(default)]
        command: Option<String>,

        /// Optional keyboard shortcut to trigger the action
        #[serde(default)]
        keybinding: Option<String>,

        /// Optional single character triggered after the global custom action prefix key.
        #[serde(default)]
        prefix_char: Option<char>,

        /// Whether the keybinding is enabled (default: true)
        #[serde(default = "crate::defaults::bool_true")]
        keybinding_enabled: bool,

        /// Optional description
        #[serde(default)]
        description: Option<String>,
    },

    /// Insert text into the terminal (like a snippet but no editing UI)
    InsertText {
        /// Action identifier
        id: String,

        /// Human-readable title
        title: String,

        /// Text to insert (supports variable substitution)
        text: String,

        /// Custom variables for substitution
        #[serde(default)]
        variables: HashMap<String, String>,

        /// Optional keyboard shortcut to trigger the action
        #[serde(default)]
        keybinding: Option<String>,

        /// Optional single character triggered after the global custom action prefix key.
        #[serde(default)]
        prefix_char: Option<char>,

        /// Whether the keybinding is enabled (default: true)
        #[serde(default = "crate::defaults::bool_true")]
        keybinding_enabled: bool,

        /// Optional description
        #[serde(default)]
        description: Option<String>,
    },

    /// Simulate a key sequence
    KeySequence {
        /// Action identifier
        id: String,

        /// Human-readable title
        title: String,

        /// Key sequence to simulate (e.g., "Ctrl+C", "Up Up Down Down")
        keys: String,

        /// Optional keyboard shortcut to trigger the action
        #[serde(default)]
        keybinding: Option<String>,

        /// Optional single character triggered after the global custom action prefix key.
        #[serde(default)]
        prefix_char: Option<char>,

        /// Whether the keybinding is enabled (default: true)
        #[serde(default = "crate::defaults::bool_true")]
        keybinding_enabled: bool,

        /// Optional description
        #[serde(default)]
        description: Option<String>,
    },

    /// Split the active pane and optionally send a command to the new pane
    SplitPane {
        /// Action identifier
        id: String,

        /// Human-readable title
        title: String,

        /// Split direction: horizontal (new pane below) or vertical (new pane right)
        #[serde(default)]
        direction: ActionSplitDirection,

        /// Command for the new pane.
        ///
        /// Behaviour depends on `command_is_direct`:
        /// - `false` (default): text is sent to the shell with a trailing newline after `delay_ms`.
        /// - `true`: the string is split on whitespace and used as the pane's initial process
        ///   (like running `htop` directly). The pane closes when the process exits.
        #[serde(default)]
        command: Option<String>,

        /// When `true`, `command` is the pane's initial process (argv), not a shell command.
        /// The pane closes when the process exits. `delay_ms` is ignored.
        /// When `false` (default), `command` is sent as text to the shell.
        #[serde(default)]
        command_is_direct: bool,

        /// Whether to focus the new pane after splitting (default: true)
        #[serde(default = "crate::defaults::bool_true")]
        focus_new_pane: bool,

        /// Delay in ms before sending the command text to the new pane (default: 200).
        /// Only used when `command_is_direct` is `false`.
        #[serde(default = "default_split_pane_delay_ms")]
        delay_ms: u64,

        /// Percent of the current pane that the existing pane retains after the split.
        /// Range 10–90. Default: 66 (existing pane keeps 66%, new pane gets 34%).
        #[serde(default = "default_split_percent")]
        split_percent: u8,

        /// Optional keyboard shortcut to trigger the action
        #[serde(default)]
        keybinding: Option<String>,

        /// Optional single character triggered after the global custom action prefix key.
        #[serde(default)]
        prefix_char: Option<char>,

        /// Whether the keybinding is enabled (default: true)
        #[serde(default = "crate::defaults::bool_true")]
        keybinding_enabled: bool,

        /// Optional description
        #[serde(default)]
        description: Option<String>,
    },

    /// Run an ordered list of actions (steps) in sequence.
    Sequence {
        /// Action identifier
        id: String,
        /// Human-readable title
        title: String,
        /// Optional keyboard shortcut
        #[serde(default)]
        keybinding: Option<String>,
        /// Optional single character triggered after the global custom action prefix key.
        #[serde(default)]
        prefix_char: Option<char>,
        /// Whether the keybinding is enabled (default: true)
        #[serde(default = "crate::defaults::bool_true")]
        keybinding_enabled: bool,
        /// Optional description
        #[serde(default)]
        description: Option<String>,
        /// Ordered list of steps to execute.
        #[serde(default)]
        steps: Vec<SequenceStep>,
    },

    /// Evaluate a condition and branch to different actions.
    Condition {
        /// Action identifier
        id: String,
        /// Human-readable title
        title: String,
        /// Optional keyboard shortcut
        #[serde(default)]
        keybinding: Option<String>,
        /// Optional single character triggered after the global custom action prefix key.
        #[serde(default)]
        prefix_char: Option<char>,
        /// Whether the keybinding is enabled (default: true)
        #[serde(default = "crate::defaults::bool_true")]
        keybinding_enabled: bool,
        /// Optional description
        #[serde(default)]
        description: Option<String>,
        /// The condition to evaluate.
        check: ConditionCheck,
        /// Action ID to execute when check is true (standalone use only; ignored in Sequence).
        #[serde(default)]
        on_true_id: Option<String>,
        /// Action ID to execute when check is false (standalone use only; ignored in Sequence).
        #[serde(default)]
        on_false_id: Option<String>,
    },

    /// Execute an action repeatedly up to N times.
    Repeat {
        /// Action identifier
        id: String,
        /// Human-readable title
        title: String,
        /// Optional keyboard shortcut
        #[serde(default)]
        keybinding: Option<String>,
        /// Optional single character triggered after the global custom action prefix key.
        #[serde(default)]
        prefix_char: Option<char>,
        /// Whether the keybinding is enabled (default: true)
        #[serde(default = "crate::defaults::bool_true")]
        keybinding_enabled: bool,
        /// Optional description
        #[serde(default)]
        description: Option<String>,
        /// ID of the action to repeat.
        action_id: String,
        /// Maximum number of repetitions (1–100).
        count: u32,
        /// Delay in milliseconds between repetitions (default: 0).
        #[serde(default)]
        delay_ms: u64,
        /// Stop early when the action succeeds (default: false).
        #[serde(default)]
        stop_on_success: bool,
        /// Stop early when the action fails (default: false).
        #[serde(default)]
        stop_on_failure: bool,
    },
}

impl CustomActionConfig {
    /// Return a snapshot of the six shared base fields.
    ///
    /// Use this to read multiple base fields at once without repeated match arms.
    /// For single-field reads, prefer the dedicated accessors (`id()`, `title()`, etc.).
    pub fn base(&self) -> ActionBase {
        match self {
            Self::ShellCommand {
                id,
                title,
                keybinding,
                prefix_char,
                keybinding_enabled,
                description,
                ..
            }
            | Self::NewTab {
                id,
                title,
                keybinding,
                prefix_char,
                keybinding_enabled,
                description,
                ..
            }
            | Self::InsertText {
                id,
                title,
                keybinding,
                prefix_char,
                keybinding_enabled,
                description,
                ..
            }
            | Self::KeySequence {
                id,
                title,
                keybinding,
                prefix_char,
                keybinding_enabled,
                description,
                ..
            }
            | Self::SplitPane {
                id,
                title,
                keybinding,
                prefix_char,
                keybinding_enabled,
                description,
                ..
            }
            | Self::Sequence {
                id,
                title,
                keybinding,
                prefix_char,
                keybinding_enabled,
                description,
                ..
            }
            | Self::Condition {
                id,
                title,
                keybinding,
                prefix_char,
                keybinding_enabled,
                description,
                ..
            }
            | Self::Repeat {
                id,
                title,
                keybinding,
                prefix_char,
                keybinding_enabled,
                description,
                ..
            } => ActionBase {
                id: id.clone(),
                title: title.clone(),
                keybinding: keybinding.clone(),
                prefix_char: *prefix_char,
                keybinding_enabled: *keybinding_enabled,
                description: description.clone(),
            },
        }
    }

    /// Overwrite all six shared base fields from an [`ActionBase`] snapshot.
    ///
    /// This is the single mutation point that replaces the eight-arm match duplication
    /// previously found in `set_keybinding`, `set_prefix_char`, `set_keybinding_enabled`,
    /// and `into_copy`.
    pub fn apply_base(&mut self, base: ActionBase) {
        match self {
            Self::ShellCommand {
                id,
                title,
                keybinding,
                prefix_char,
                keybinding_enabled,
                description,
                ..
            }
            | Self::NewTab {
                id,
                title,
                keybinding,
                prefix_char,
                keybinding_enabled,
                description,
                ..
            }
            | Self::InsertText {
                id,
                title,
                keybinding,
                prefix_char,
                keybinding_enabled,
                description,
                ..
            }
            | Self::KeySequence {
                id,
                title,
                keybinding,
                prefix_char,
                keybinding_enabled,
                description,
                ..
            }
            | Self::SplitPane {
                id,
                title,
                keybinding,
                prefix_char,
                keybinding_enabled,
                description,
                ..
            }
            | Self::Sequence {
                id,
                title,
                keybinding,
                prefix_char,
                keybinding_enabled,
                description,
                ..
            }
            | Self::Condition {
                id,
                title,
                keybinding,
                prefix_char,
                keybinding_enabled,
                description,
                ..
            }
            | Self::Repeat {
                id,
                title,
                keybinding,
                prefix_char,
                keybinding_enabled,
                description,
                ..
            } => {
                *id = base.id;
                *title = base.title;
                *keybinding = base.keybinding;
                *prefix_char = base.prefix_char;
                *keybinding_enabled = base.keybinding_enabled;
                *description = base.description;
            }
        }
    }

    /// Get the action ID (for keybinding reference).
    pub fn id(&self) -> &str {
        match self {
            Self::ShellCommand { id, .. }
            | Self::NewTab { id, .. }
            | Self::InsertText { id, .. }
            | Self::KeySequence { id, .. }
            | Self::SplitPane { id, .. }
            | Self::Sequence { id, .. }
            | Self::Condition { id, .. }
            | Self::Repeat { id, .. } => id,
        }
    }

    /// Get the action title (for UI display).
    pub fn title(&self) -> &str {
        match self {
            Self::ShellCommand { title, .. }
            | Self::NewTab { title, .. }
            | Self::InsertText { title, .. }
            | Self::KeySequence { title, .. }
            | Self::SplitPane { title, .. }
            | Self::Sequence { title, .. }
            | Self::Condition { title, .. }
            | Self::Repeat { title, .. } => title,
        }
    }

    /// Get the optional keybinding for this action.
    pub fn keybinding(&self) -> Option<&str> {
        match self {
            Self::ShellCommand { keybinding, .. }
            | Self::NewTab { keybinding, .. }
            | Self::InsertText { keybinding, .. }
            | Self::KeySequence { keybinding, .. }
            | Self::SplitPane { keybinding, .. }
            | Self::Sequence { keybinding, .. }
            | Self::Condition { keybinding, .. }
            | Self::Repeat { keybinding, .. } => keybinding.as_deref(),
        }
    }

    /// Get the optional prefix character for this action.
    pub fn prefix_char(&self) -> Option<char> {
        match self {
            Self::ShellCommand { prefix_char, .. }
            | Self::NewTab { prefix_char, .. }
            | Self::InsertText { prefix_char, .. }
            | Self::KeySequence { prefix_char, .. }
            | Self::SplitPane { prefix_char, .. }
            | Self::Sequence { prefix_char, .. }
            | Self::Condition { prefix_char, .. }
            | Self::Repeat { prefix_char, .. } => *prefix_char,
        }
    }

    /// Get the normalized prefix character for this action, if configured.
    pub fn normalized_prefix_char(&self) -> Option<char> {
        self.prefix_char().map(normalize_action_prefix_char)
    }

    /// Check if the keybinding is enabled.
    pub fn keybinding_enabled(&self) -> bool {
        match self {
            Self::ShellCommand {
                keybinding_enabled, ..
            }
            | Self::NewTab {
                keybinding_enabled, ..
            }
            | Self::InsertText {
                keybinding_enabled, ..
            }
            | Self::KeySequence {
                keybinding_enabled, ..
            }
            | Self::SplitPane {
                keybinding_enabled, ..
            }
            | Self::Sequence {
                keybinding_enabled, ..
            }
            | Self::Condition {
                keybinding_enabled, ..
            }
            | Self::Repeat {
                keybinding_enabled, ..
            } => *keybinding_enabled,
        }
    }

    /// Set the keybinding for this action.
    pub fn set_keybinding(&mut self, kb: Option<String>) {
        let mut base = self.base();
        base.keybinding = kb;
        self.apply_base(base);
    }

    /// Set the prefix character for this action.
    pub fn set_prefix_char(&mut self, prefix_char: Option<char>) {
        let mut base = self.base();
        base.prefix_char = prefix_char;
        self.apply_base(base);
    }

    /// Set whether the keybinding is enabled.
    pub fn set_keybinding_enabled(&mut self, enabled: bool) {
        let mut base = self.base();
        base.keybinding_enabled = enabled;
        self.apply_base(base);
    }

    /// Check if this is a shell command action.
    pub fn is_shell_command(&self) -> bool {
        matches!(self, Self::ShellCommand { .. })
    }

    /// Check if this is a new tab action.
    pub fn is_new_tab(&self) -> bool {
        matches!(self, Self::NewTab { .. })
    }

    /// Check if this is an insert text action.
    pub fn is_insert_text(&self) -> bool {
        matches!(self, Self::InsertText { .. })
    }

    /// Check if this is a key sequence action.
    pub fn is_key_sequence(&self) -> bool {
        matches!(self, Self::KeySequence { .. })
    }

    /// Check if this is a split pane action.
    pub fn is_split_pane(&self) -> bool {
        matches!(self, Self::SplitPane { .. })
    }

    /// Check if this is a sequence action.
    pub fn is_sequence(&self) -> bool {
        matches!(self, Self::Sequence { .. })
    }

    /// Check if this is a condition action.
    pub fn is_condition(&self) -> bool {
        matches!(self, Self::Condition { .. })
    }

    /// Check if this is a repeat action.
    pub fn is_repeat(&self) -> bool {
        matches!(self, Self::Repeat { .. })
    }

    /// Produce a duplicate of this action suitable for "Clone" in the settings UI.
    ///
    /// The returned action has:
    /// - A fresh UUID-based `id` to avoid keybinding conflicts.
    /// - The original `title` suffixed with `"-copy"`.
    /// - `keybinding` and `prefix_char` cleared to prevent immediate conflicts.
    ///
    /// All other fields are deep-cloned from `self`.
    ///
    /// This replaces the `clone_action` helper that was previously inlined in
    /// `par-term-settings-ui/src/actions_tab.rs` (see ARC-006). Keeping the logic here
    /// ensures it stays in sync with the `Clone` derive on `CustomActionConfig`.
    pub fn into_copy(&self) -> Self {
        let mut cloned = self.clone();
        // Patch the four base fields that must differ on the copy; keep the rest.
        let mut base = cloned.base();
        base.id = format!("action_{}", uuid::Uuid::new_v4());
        base.title = format!("{}-copy", base.title);
        base.keybinding = None;
        base.prefix_char = None;
        cloned.apply_base(base);
        cloned
    }
}

/// Built-in variables available for snippet substitution.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum BuiltInVariable {
    /// Current date (YYYY-MM-DD)
    Date,
    /// Current time (HH:MM:SS)
    Time,
    /// Current date and time
    DateTime,
    /// System hostname
    Hostname,
    /// Current username
    User,
    /// Current working directory
    Path,
    /// Current git branch (if in a git repository)
    GitBranch,
    /// Current git commit hash (if in a git repository)
    GitCommit,
    /// Random UUID
    Uuid,
    /// Random number (0-999999)
    Random,
}

impl BuiltInVariable {
    /// Get all built-in variables for UI display.
    pub fn all() -> &'static [(&'static str, &'static str)] {
        &[
            ("date", "Current date (YYYY-MM-DD)"),
            ("time", "Current time (HH:MM:SS)"),
            ("datetime", "Current date and time"),
            ("hostname", "System hostname"),
            ("user", "Current username"),
            ("path", "Current working directory"),
            ("git_branch", "Current git branch"),
            ("git_commit", "Current git commit hash"),
            ("uuid", "Random UUID"),
            ("random", "Random number (0-999999)"),
        ]
    }

    /// Parse a variable name into a BuiltInVariable.
    pub fn parse(name: &str) -> Option<Self> {
        match name {
            "date" => Some(Self::Date),
            "time" => Some(Self::Time),
            "datetime" => Some(Self::DateTime),
            "hostname" => Some(Self::Hostname),
            "user" => Some(Self::User),
            "path" => Some(Self::Path),
            "git_branch" => Some(Self::GitBranch),
            "git_commit" => Some(Self::GitCommit),
            "uuid" => Some(Self::Uuid),
            "random" => Some(Self::Random),
            _ => None,
        }
    }

    /// Resolve the variable to its string value.
    pub fn resolve(&self) -> String {
        match self {
            Self::Date => {
                use std::time::{SystemTime, UNIX_EPOCH};
                let duration = SystemTime::now()
                    .duration_since(UNIX_EPOCH)
                    .unwrap_or_default();
                let secs = duration.as_secs();
                let days_since_epoch = secs / 86400;

                // Simple date calculation (days since 1970-01-01)
                let years = 1970 + days_since_epoch / 365;
                let day_of_year = (days_since_epoch % 365) as u32;
                let month = (day_of_year / 30) + 1;
                let day = (day_of_year % 30) + 1;

                format!("{:04}-{:02}-{:02}", years, month, day)
            }
            Self::Time => {
                use std::time::{SystemTime, UNIX_EPOCH};
                let duration = SystemTime::now()
                    .duration_since(UNIX_EPOCH)
                    .unwrap_or_default();
                let secs = duration.as_secs();
                let hours = (secs % 86400) / 3600;
                let minutes = (secs % 3600) / 60;
                let seconds = secs % 60;

                format!("{:02}:{:02}:{:02}", hours, minutes, seconds)
            }
            Self::DateTime => {
                format!("{} {}", Self::Date.resolve(), Self::Time.resolve())
            }
            Self::Hostname => {
                std::env::var("HOSTNAME")
                    .or_else(|_| std::env::var("HOST"))
                    .unwrap_or_else(|_| {
                        // Fallback to system hostname
                        hostname::get()
                            .ok()
                            .and_then(|s| s.into_string().ok())
                            .unwrap_or_else(|| "unknown".to_string())
                    })
            }
            Self::User => std::env::var("USER")
                .or_else(|_| std::env::var("USERNAME"))
                .unwrap_or_else(|_| "unknown".to_string()),
            Self::Path => std::env::current_dir()
                .ok()
                .and_then(|p| p.to_str().map(|s| s.to_string()))
                .unwrap_or_else(|| ".".to_string()),
            Self::GitBranch => {
                // Try to get git branch from environment or command
                match std::env::var("GIT_BRANCH") {
                    Ok(branch) => branch,
                    Err(_) => {
                        // Try running git command
                        std::process::Command::new("git")
                            .args(["rev-parse", "--abbrev-ref", "HEAD"])
                            .output()
                            .ok()
                            .and_then(|o| String::from_utf8(o.stdout).ok())
                            .map(|s| s.trim().to_string())
                            .unwrap_or_default()
                    }
                }
            }
            Self::GitCommit => {
                // Try to get git commit from environment or command
                match std::env::var("GIT_COMMIT") {
                    Ok(commit) => commit,
                    Err(_) => std::process::Command::new("git")
                        .args(["rev-parse", "--short", "HEAD"])
                        .output()
                        .ok()
                        .and_then(|o| String::from_utf8(o.stdout).ok())
                        .map(|s| s.trim().to_string())
                        .unwrap_or_default(),
                }
            }
            Self::Uuid => uuid::Uuid::new_v4().to_string(),
            Self::Random => {
                use std::time::{SystemTime, UNIX_EPOCH};
                let duration = SystemTime::now()
                    .duration_since(UNIX_EPOCH)
                    .unwrap_or_default();
                format!("{}", (duration.as_nanos() % 1_000_000) as u32)
            }
        }
    }
}

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

    #[test]
    fn test_snippet_new() {
        let snippet = SnippetConfig::new(
            "test".to_string(),
            "Test Snippet".to_string(),
            "echo 'hello'".to_string(),
        );

        assert_eq!(snippet.id, "test");
        assert_eq!(snippet.title, "Test Snippet");
        assert_eq!(snippet.content, "echo 'hello'");
        assert!(snippet.enabled);
        assert!(snippet.keybinding.is_none());
        assert!(snippet.folder.is_none());
        assert!(snippet.variables.is_empty());
    }

    #[test]
    fn test_snippet_builder() {
        let snippet = SnippetConfig::new(
            "test".to_string(),
            "Test Snippet".to_string(),
            "echo 'hello'".to_string(),
        )
        .with_keybinding("Ctrl+Shift+T".to_string())
        .with_folder("Test".to_string())
        .with_variable("name".to_string(), "value".to_string());

        assert_eq!(snippet.keybinding, Some("Ctrl+Shift+T".to_string()));
        assert_eq!(snippet.folder, Some("Test".to_string()));
        assert_eq!(snippet.variables.get("name"), Some(&"value".to_string()));
    }

    #[test]
    fn test_builtin_variable_resolution() {
        // These should not panic
        let date = BuiltInVariable::Date.resolve();
        assert!(!date.is_empty());

        let time = BuiltInVariable::Time.resolve();
        assert!(!time.is_empty());

        let user = BuiltInVariable::User.resolve();
        assert!(!user.is_empty());

        let path = BuiltInVariable::Path.resolve();
        assert!(!path.is_empty());
    }

    #[test]
    fn test_builtin_variable_parse() {
        assert_eq!(BuiltInVariable::parse("date"), Some(BuiltInVariable::Date));
        assert_eq!(BuiltInVariable::parse("time"), Some(BuiltInVariable::Time));
        assert_eq!(BuiltInVariable::parse("unknown"), None);
    }

    #[test]
    fn test_custom_action_id() {
        let action = CustomActionConfig::ShellCommand {
            id: "test-action".to_string(),
            title: "Test Action".to_string(),
            command: "echo".to_string(),
            args: vec!["hello".to_string()],
            notify_on_success: false,
            timeout_secs: 30,
            capture_output: false,
            keybinding: None,
            prefix_char: Some('G'),
            keybinding_enabled: true,
            description: None,
        };

        assert_eq!(action.id(), "test-action");
        assert_eq!(action.title(), "Test Action");
        assert!(action.is_shell_command());
        assert!(!action.is_new_tab());
        assert!(!action.is_insert_text());
        assert!(!action.is_key_sequence());
        assert!(!action.is_split_pane());
        assert_eq!(action.prefix_char(), Some('G'));
        assert_eq!(action.normalized_prefix_char(), Some('g'));
    }

    #[test]
    fn test_split_pane_action() {
        let action = CustomActionConfig::SplitPane {
            id: "split-htop".to_string(),
            title: "Split and run htop".to_string(),
            direction: ActionSplitDirection::Vertical,
            command: Some("htop".to_string()),
            command_is_direct: true,
            focus_new_pane: true,
            delay_ms: 200,
            split_percent: 66,
            keybinding: Some("Ctrl+Shift+H".to_string()),
            prefix_char: None,
            keybinding_enabled: true,
            description: None,
        };

        assert_eq!(action.id(), "split-htop");
        assert_eq!(action.title(), "Split and run htop");
        assert!(action.is_split_pane());
        assert!(!action.is_shell_command());
        assert_eq!(action.keybinding(), Some("Ctrl+Shift+H"));
    }

    #[test]
    fn test_new_tab_action() {
        let action = CustomActionConfig::NewTab {
            id: "new-tab-lazygit".to_string(),
            title: "Open lazygit tab".to_string(),
            command: Some("lazygit".to_string()),
            keybinding: Some("Ctrl+Shift+G".to_string()),
            prefix_char: Some('g'),
            keybinding_enabled: true,
            description: None,
        };

        assert_eq!(action.id(), "new-tab-lazygit");
        assert_eq!(action.title(), "Open lazygit tab");
        assert!(action.is_new_tab());
        assert!(!action.is_shell_command());
        assert!(!action.is_split_pane());
        assert_eq!(action.keybinding(), Some("Ctrl+Shift+G"));
        assert_eq!(action.normalized_prefix_char(), Some('g'));
    }

    #[test]
    fn test_sequence_action_round_trip() {
        let action = CustomActionConfig::Sequence {
            id: "build-and-test".to_string(),
            title: "Build and Test".to_string(),
            keybinding: None,
            prefix_char: None,
            keybinding_enabled: true,
            description: None,
            steps: vec![
                SequenceStep {
                    action_id: "build".to_string(),
                    delay_ms: 0,
                    on_failure: SequenceStepBehavior::Abort,
                },
                SequenceStep {
                    action_id: "test".to_string(),
                    delay_ms: 500,
                    on_failure: SequenceStepBehavior::Continue,
                },
            ],
        };
        let yaml = serde_yaml_ng::to_string(&action).unwrap();
        let roundtrip: CustomActionConfig = serde_yaml_ng::from_str(&yaml).unwrap();
        assert_eq!(action, roundtrip);
        assert_eq!(action.id(), "build-and-test");
        assert_eq!(action.title(), "Build and Test");
    }

    #[test]
    fn test_condition_action_round_trip() {
        let action = CustomActionConfig::Condition {
            id: "check-main".to_string(),
            title: "Check Main Branch".to_string(),
            keybinding: None,
            prefix_char: None,
            keybinding_enabled: true,
            description: None,
            check: ConditionCheck::GitBranch {
                pattern: "main".to_string(),
            },
            on_true_id: Some("deploy".to_string()),
            on_false_id: None,
        };
        let yaml = serde_yaml_ng::to_string(&action).unwrap();
        let roundtrip: CustomActionConfig = serde_yaml_ng::from_str(&yaml).unwrap();
        assert_eq!(action, roundtrip);
        assert_eq!(action.id(), "check-main");
    }

    #[test]
    fn test_repeat_action_round_trip() {
        let action = CustomActionConfig::Repeat {
            id: "retry-deploy".to_string(),
            title: "Retry Deploy".to_string(),
            keybinding: None,
            prefix_char: None,
            keybinding_enabled: true,
            description: None,
            action_id: "deploy".to_string(),
            count: 3,
            delay_ms: 1000,
            stop_on_success: true,
            stop_on_failure: false,
        };
        let yaml = serde_yaml_ng::to_string(&action).unwrap();
        let roundtrip: CustomActionConfig = serde_yaml_ng::from_str(&yaml).unwrap();
        assert_eq!(action, roundtrip);
        assert_eq!(action.id(), "retry-deploy");
    }

    #[test]
    fn test_shell_command_capture_output_default_false() {
        let yaml = r#"
type: shell_command
id: test
title: Test
command: echo
"#;
        let action: CustomActionConfig = serde_yaml_ng::from_str(yaml).unwrap();
        if let CustomActionConfig::ShellCommand { capture_output, .. } = action {
            assert!(!capture_output);
        } else {
            panic!("expected ShellCommand");
        }
    }
}