git-worktree-manager 0.0.31

CLI tool integrating git worktree with AI coding assistants
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
/// Configuration management for git-worktree-manager.
///
/// Supports multiple AI coding assistants with customizable commands.
/// Configuration stored in ~/.config/git-worktree-manager/config.json.
use std::collections::HashMap;
use std::path::PathBuf;

use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::constants::{
    home_dir_or_fallback, launch_method_aliases, LaunchMethod, MAX_SESSION_NAME_LENGTH,
};
use crate::error::{CwError, Result};

/// Typed configuration structure matching the JSON schema.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Config {
    pub ai_tool: AiToolConfig,
    pub launch: LaunchConfig,
    pub git: GitConfig,
    pub update: UpdateConfig,
    pub shell_completion: ShellCompletionConfig,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AiToolConfig {
    pub command: String,
    pub args: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LaunchConfig {
    pub method: Option<String>,
    pub tmux_session_prefix: String,
    pub wezterm_ready_timeout: f64,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct GitConfig {
    // default_base_branch removed — auto-detected per repo via git::detect_default_branch()
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UpdateConfig {
    pub auto_check: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ShellCompletionConfig {
    pub prompted: bool,
    pub installed: bool,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            ai_tool: AiToolConfig {
                command: "claude".to_string(),
                args: Vec::new(),
            },
            launch: LaunchConfig {
                method: None,
                tmux_session_prefix: "gw".to_string(),
                wezterm_ready_timeout: 5.0,
            },
            git: GitConfig {},
            update: UpdateConfig { auto_check: true },
            shell_completion: ShellCompletionConfig {
                prompted: false,
                installed: false,
            },
        }
    }
}

/// AI tool presets: preset name -> command parts.
pub fn ai_tool_presets() -> HashMap<&'static str, Vec<&'static str>> {
    HashMap::from([
        ("no-op", vec![]),
        ("claude", vec!["claude"]),
        (
            "claude-yolo",
            vec!["claude", "--dangerously-skip-permissions"],
        ),
        ("claude-remote", vec!["claude", "/remote-control"]),
        (
            "claude-yolo-remote",
            vec![
                "claude",
                "--dangerously-skip-permissions",
                "/remote-control",
            ],
        ),
        ("codex", vec!["codex"]),
        (
            "codex-yolo",
            vec!["codex", "--dangerously-bypass-approvals-and-sandbox"],
        ),
    ])
}

/// AI tool resume presets.
pub fn ai_tool_resume_presets() -> HashMap<&'static str, Vec<&'static str>> {
    HashMap::from([
        ("claude", vec!["claude", "--continue"]),
        (
            "claude-yolo",
            vec!["claude", "--dangerously-skip-permissions", "--continue"],
        ),
        (
            "claude-remote",
            vec!["claude", "--continue", "/remote-control"],
        ),
        (
            "claude-yolo-remote",
            vec![
                "claude",
                "--dangerously-skip-permissions",
                "--continue",
                "/remote-control",
            ],
        ),
        ("codex", vec!["codex", "resume", "--last"]),
        (
            "codex-yolo",
            vec![
                "codex",
                "resume",
                "--dangerously-bypass-approvals-and-sandbox",
                "--last",
            ],
        ),
    ])
}

/// Merge preset configuration.
#[derive(Debug)]
pub struct MergePreset {
    pub base_override: Option<Vec<&'static str>>,
    pub flags: Vec<&'static str>,
    pub prompt_position: PromptPosition,
}

#[derive(Debug)]
pub enum PromptPosition {
    End,
    Index(usize),
}

/// AI tool merge presets.
pub fn ai_tool_merge_presets() -> HashMap<&'static str, MergePreset> {
    HashMap::from([
        (
            "claude",
            MergePreset {
                base_override: None,
                flags: vec!["--print", "--tools=default"],
                prompt_position: PromptPosition::End,
            },
        ),
        (
            "claude-yolo",
            MergePreset {
                base_override: None,
                flags: vec!["--print", "--tools=default"],
                prompt_position: PromptPosition::End,
            },
        ),
        (
            "claude-remote",
            MergePreset {
                base_override: Some(vec!["claude"]),
                flags: vec!["--print", "--tools=default"],
                prompt_position: PromptPosition::End,
            },
        ),
        (
            "claude-yolo-remote",
            MergePreset {
                base_override: Some(vec!["claude", "--dangerously-skip-permissions"]),
                flags: vec!["--print", "--tools=default"],
                prompt_position: PromptPosition::End,
            },
        ),
        (
            "codex",
            MergePreset {
                base_override: None,
                flags: vec!["--non-interactive"],
                prompt_position: PromptPosition::End,
            },
        ),
        (
            "codex-yolo",
            MergePreset {
                base_override: None,
                flags: vec!["--non-interactive"],
                prompt_position: PromptPosition::End,
            },
        ),
    ])
}

/// Set of Claude-based preset names.
pub fn claude_preset_names() -> Vec<&'static str> {
    ai_tool_presets()
        .iter()
        .filter(|(_, v)| v.first().map(|&s| s == "claude").unwrap_or(false))
        .map(|(&k, _)| k)
        .collect()
}

// ---------------------------------------------------------------------------
// Config file I/O
// ---------------------------------------------------------------------------

/// Get the path to the configuration file.
pub fn get_config_path() -> PathBuf {
    let home = home_dir_or_fallback();
    home.join(".config")
        .join("git-worktree-manager")
        .join("config.json")
}

/// Deep merge: override takes precedence, nested dicts merged recursively.
fn deep_merge(base: Value, over: Value) -> Value {
    match (base, over) {
        (Value::Object(mut base_map), Value::Object(over_map)) => {
            for (key, over_val) in over_map {
                let merged = if let Some(base_val) = base_map.remove(&key) {
                    deep_merge(base_val, over_val)
                } else {
                    over_val
                };
                base_map.insert(key, merged);
            }
            Value::Object(base_map)
        }
        (_, over) => over,
    }
}

/// Get the path to the legacy Python configuration file.
fn get_legacy_config_path() -> PathBuf {
    let home = home_dir_or_fallback();
    home.join(".config")
        .join("claude-worktree")
        .join("config.json")
}

/// Load configuration from file, deep-merged with defaults.
/// Falls back to legacy Python config path if the new path doesn't exist.
pub fn load_config() -> Result<Config> {
    let config_path = get_config_path();

    let config_path = if config_path.exists() {
        config_path
    } else {
        let legacy = get_legacy_config_path();
        if legacy.exists() {
            legacy
        } else {
            return Ok(Config::default());
        }
    };

    let content = std::fs::read_to_string(&config_path).map_err(|e| {
        CwError::Config(format!(
            "Failed to load config from {}: {}",
            config_path.display(),
            e
        ))
    })?;

    let file_value: Value = serde_json::from_str(&content).map_err(|e| {
        CwError::Config(format!(
            "Failed to parse config from {}: {}",
            config_path.display(),
            e
        ))
    })?;

    let default_value = serde_json::to_value(Config::default())?;
    let merged = deep_merge(default_value, file_value);

    serde_json::from_value(merged).map_err(|e| {
        CwError::Config(format!(
            "Failed to deserialize config from {}: {}",
            config_path.display(),
            e
        ))
    })
}

/// Save configuration to file.
pub fn save_config(config: &Config) -> Result<()> {
    let config_path = get_config_path();
    if let Some(parent) = config_path.parent() {
        std::fs::create_dir_all(parent)?;
    }

    let content = serde_json::to_string_pretty(config)?;
    std::fs::write(&config_path, content).map_err(|e| {
        CwError::Config(format!(
            "Failed to save config to {}: {}",
            config_path.display(),
            e
        ))
    })
}

/// Get the AI tool command to execute.
///
/// Priority: CW_AI_TOOL env > config file > default ("claude").
pub fn get_ai_tool_command() -> Result<Vec<String>> {
    // Check environment variable first
    if let Ok(env_tool) = std::env::var("CW_AI_TOOL") {
        if env_tool.trim().is_empty() {
            return Ok(Vec::new());
        }
        return Ok(env_tool.split_whitespace().map(String::from).collect());
    }

    let config = load_config()?;
    let command = &config.ai_tool.command;
    let args = &config.ai_tool.args;

    let presets = ai_tool_presets();
    if let Some(base_cmd) = presets.get(command.as_str()) {
        let mut cmd: Vec<String> = base_cmd.iter().map(|s| s.to_string()).collect();
        cmd.extend(args.iter().cloned());
        return Ok(cmd);
    }

    if command.trim().is_empty() {
        return Ok(Vec::new());
    }

    let mut cmd = vec![command.clone()];
    cmd.extend(args.iter().cloned());
    Ok(cmd)
}

/// Get the AI tool resume command.
pub fn get_ai_tool_resume_command() -> Result<Vec<String>> {
    if let Ok(env_tool) = std::env::var("CW_AI_TOOL") {
        if env_tool.trim().is_empty() {
            return Ok(Vec::new());
        }
        let mut parts: Vec<String> = env_tool.split_whitespace().map(String::from).collect();
        parts.push("--resume".to_string());
        return Ok(parts);
    }

    let config = load_config()?;
    let command = &config.ai_tool.command;
    let args = &config.ai_tool.args;

    if command.trim().is_empty() {
        return Ok(Vec::new());
    }

    let resume_presets = ai_tool_resume_presets();
    if let Some(resume_cmd) = resume_presets.get(command.as_str()) {
        let mut cmd: Vec<String> = resume_cmd.iter().map(|s| s.to_string()).collect();
        cmd.extend(args.iter().cloned());
        return Ok(cmd);
    }

    let presets = ai_tool_presets();
    if let Some(base_cmd) = presets.get(command.as_str()) {
        if base_cmd.is_empty() {
            return Ok(Vec::new());
        }
        let mut cmd: Vec<String> = base_cmd.iter().map(|s| s.to_string()).collect();
        cmd.extend(args.iter().cloned());
        cmd.push("--resume".to_string());
        return Ok(cmd);
    }

    let mut cmd = vec![command.clone()];
    cmd.extend(args.iter().cloned());
    cmd.push("--resume".to_string());
    Ok(cmd)
}

/// Get the AI tool merge command.
pub fn get_ai_tool_merge_command(prompt: &str) -> Result<Vec<String>> {
    if let Ok(env_tool) = std::env::var("CW_AI_TOOL") {
        if env_tool.trim().is_empty() {
            return Ok(Vec::new());
        }
        let mut parts: Vec<String> = env_tool.split_whitespace().map(String::from).collect();
        parts.push(prompt.to_string());
        return Ok(parts);
    }

    let config = load_config()?;
    let command = &config.ai_tool.command;
    let args = &config.ai_tool.args;

    if command.trim().is_empty() {
        return Ok(Vec::new());
    }

    let merge_presets = ai_tool_merge_presets();
    if let Some(preset) = merge_presets.get(command.as_str()) {
        let base_cmd: Vec<String> = if let Some(ref base_override) = preset.base_override {
            base_override.iter().map(|s| s.to_string()).collect()
        } else {
            let presets = ai_tool_presets();
            presets
                .get(command.as_str())
                .map(|v| v.iter().map(|s| s.to_string()).collect())
                .unwrap_or_else(|| vec![command.clone()])
        };

        let mut cmd_parts = base_cmd;
        cmd_parts.extend(args.iter().cloned());
        cmd_parts.extend(preset.flags.iter().map(|s| s.to_string()));

        match preset.prompt_position {
            PromptPosition::End => cmd_parts.push(prompt.to_string()),
            PromptPosition::Index(i) => cmd_parts.insert(i, prompt.to_string()),
        }

        return Ok(cmd_parts);
    }

    let presets = ai_tool_presets();
    if let Some(base_cmd) = presets.get(command.as_str()) {
        if base_cmd.is_empty() {
            return Ok(Vec::new());
        }
        let mut cmd: Vec<String> = base_cmd.iter().map(|s| s.to_string()).collect();
        cmd.extend(args.iter().cloned());
        cmd.push(prompt.to_string());
        return Ok(cmd);
    }

    let mut cmd = vec![command.clone()];
    cmd.extend(args.iter().cloned());
    cmd.push(prompt.to_string());
    Ok(cmd)
}

/// Get the AI tool command with an initial prompt for interactive delegation.
///
/// Appends the prompt as a positional argument so the AI tool starts in interactive mode
/// with the given task. For Claude Code: `claude "<prompt>"` starts interactive with initial prompt.
pub fn get_ai_tool_delegate_command(prompt: &str) -> Result<Vec<String>> {
    let mut cmd = get_ai_tool_command()?;
    if cmd.is_empty() {
        return Ok(cmd);
    }
    cmd.push(prompt.to_string());
    Ok(cmd)
}

/// Check if the currently configured AI tool is Claude-based.
pub fn is_claude_tool() -> Result<bool> {
    if let Ok(env_tool) = std::env::var("CW_AI_TOOL") {
        let first_word = env_tool.split_whitespace().next().unwrap_or("");
        return Ok(first_word == "claude");
    }
    let config = load_config()?;
    Ok(claude_preset_names().contains(&config.ai_tool.command.as_str()))
}

/// Set the AI tool command in configuration.
pub fn set_ai_tool(tool: &str, args: Option<Vec<String>>) -> Result<()> {
    let mut config = load_config()?;
    config.ai_tool.command = tool.to_string();
    config.ai_tool.args = args.unwrap_or_default();
    save_config(&config)
}

/// Use a predefined AI tool preset.
pub fn use_preset(preset_name: &str) -> Result<()> {
    let presets = ai_tool_presets();
    if !presets.contains_key(preset_name) {
        let available: Vec<&str> = presets.keys().copied().collect();
        return Err(CwError::Config(format!(
            "Unknown preset: {}. Available: {}",
            preset_name,
            available.join(", ")
        )));
    }
    set_ai_tool(preset_name, None)
}

/// Reset configuration to defaults.
pub fn reset_config() -> Result<()> {
    save_config(&Config::default())
}

/// Resolve a launch method value (possibly an alias) to its display name.
pub fn resolve_launch_display_name(method: &str) -> String {
    let aliases = launch_method_aliases();
    let canonical = aliases.get(method).copied().unwrap_or(method);
    LaunchMethod::from_str_opt(canonical)
        .map(|m| format!("{} ({})", m.display_name(), method))
        .unwrap_or_else(|| method.to_string())
}

/// All known configuration keys with descriptions.
pub const CONFIG_KEYS: &[(&str, &str)] = &[
    (
        "ai_tool.command",
        "AI tool command name (e.g., claude, codex)",
    ),
    ("ai_tool.args", "Additional arguments passed to AI tool"),
    (
        "launch.method",
        "Terminal launch method (foreground, tmux, wezterm, ...)",
    ),
    (
        "launch.tmux_session_prefix",
        "Prefix for tmux session names",
    ),
    (
        "launch.wezterm_ready_timeout",
        "Timeout (seconds) waiting for WezTerm",
    ),
    (
        "update.auto_check",
        "Automatically check for updates on startup",
    ),
    (
        "shell_completion.prompted",
        "Whether shell completion setup was prompted",
    ),
    (
        "shell_completion.installed",
        "Whether shell completion is installed",
    ),
];

/// List all configuration keys with their current values and descriptions.
pub fn list_config() -> Result<()> {
    use console::style;

    let config = load_config()?;
    let json = serde_json::to_value(&config)?;

    println!();
    println!(
        "  {:<35} {:<25} {}",
        style("KEY").dim(),
        style("VALUE").dim(),
        style("DESCRIPTION").dim(),
    );
    println!("  {}", style("─".repeat(90)).dim());

    for (key, desc) in CONFIG_KEYS {
        let keys: Vec<&str> = key.split('.').collect();
        let mut current = &json;
        let mut found = true;
        for &k in &keys {
            match current.get(k) {
                Some(v) => current = v,
                None => {
                    found = false;
                    break;
                }
            }
        }

        let value_str = if !found {
            style("(unset)".to_string()).dim().to_string()
        } else {
            let raw = match current {
                serde_json::Value::String(s) => s.clone(),
                serde_json::Value::Bool(b) => b.to_string(),
                serde_json::Value::Number(n) => n.to_string(),
                serde_json::Value::Null => "null".to_string(),
                serde_json::Value::Array(a) => {
                    if a.is_empty() {
                        "[]".to_string()
                    } else {
                        serde_json::to_string(a).unwrap_or_default()
                    }
                }
                other => serde_json::to_string(other).unwrap_or_default(),
            };
            // Show display name for launch.method
            if *key == "launch.method" && raw != "null" {
                resolve_launch_display_name(&raw)
            } else {
                raw
            }
        };

        println!(
            "  {:<35} {:<25} {}",
            style(key).bold(),
            value_str,
            style(desc).dim(),
        );
    }
    println!();

    Ok(())
}

/// Get a configuration value by dot-separated key path.
pub fn get_config_value(key_path: &str) -> Result<()> {
    let config = load_config()?;
    let json = serde_json::to_value(&config)?;

    let keys: Vec<&str> = key_path.split('.').collect();
    let mut current = &json;
    for &key in &keys {
        current = current
            .get(key)
            .ok_or_else(|| CwError::Config(format!("Unknown config key: {}", key_path)))?;
    }

    match current {
        serde_json::Value::String(s) => println!("{}", s),
        serde_json::Value::Bool(b) => println!("{}", b),
        serde_json::Value::Number(n) => println!("{}", n),
        serde_json::Value::Null => println!("null"),
        other => println!(
            "{}",
            serde_json::to_string_pretty(other).unwrap_or_default()
        ),
    }

    Ok(())
}

/// Set a configuration value by dot-separated key path.
///
/// Special handling:
/// - `ai_tool <preset>` — sets command + args from preset (e.g., `ai_tool claude-yolo`)
/// - `launch.method <alias>` — resolves alias (e.g., `w-t` → `wezterm-tab`)
pub fn set_config_value(key_path: &str, value: &str) -> Result<()> {
    // Shortcut: "ai_tool <preset_name>" applies the preset
    if key_path == "ai_tool" {
        let presets = ai_tool_presets();
        if presets.contains_key(value) {
            return use_preset(value);
        }
        // Not a preset — treat as raw command name
        return set_ai_tool(value, None);
    }

    // Shortcut: resolve launch method aliases
    if key_path == "launch.method" {
        let aliases = launch_method_aliases();
        let canonical = aliases.get(value).copied().unwrap_or(value);
        // Validate
        if value != "null"
            && LaunchMethod::from_str_opt(canonical).is_none()
            && LaunchMethod::from_str_opt(value).is_none()
        {
            return Err(CwError::Config(format!(
                "Unknown launch method: '{}'. Use 'gw config list-presets' or 'gw --help' for options.",
                value
            )));
        }
    }

    let mut config = load_config()?;
    let mut json = serde_json::to_value(&config)?;

    let keys: Vec<&str> = key_path.split('.').collect();

    // Convert string boolean values
    let json_value: Value = match value.to_lowercase().as_str() {
        "true" => Value::Bool(true),
        "false" => Value::Bool(false),
        _ => {
            // Try to parse as number
            if let Ok(n) = value.parse::<f64>() {
                serde_json::Number::from_f64(n)
                    .map(Value::Number)
                    .unwrap_or(Value::String(value.to_string()))
            } else {
                Value::String(value.to_string())
            }
        }
    };

    // Navigate to parent and set value
    let mut current = &mut json;
    for &key in &keys[..keys.len() - 1] {
        if !current.is_object() {
            return Err(CwError::Config(format!(
                "Invalid config path: {}",
                key_path
            )));
        }
        current = current
            .as_object_mut()
            .ok_or_else(|| CwError::Config(format!("Invalid config path: {}", key_path)))?
            .entry(key)
            .or_insert(Value::Object(serde_json::Map::new()));
    }

    if let Some(obj) = current.as_object_mut() {
        obj.insert(keys[keys.len() - 1].to_string(), json_value);
    } else {
        return Err(CwError::Config(format!(
            "Invalid config path: {}",
            key_path
        )));
    }

    // Deserialize back to Config and save
    config = serde_json::from_value(json)
        .map_err(|e| CwError::Config(format!("Invalid config value: {}", e)))?;
    save_config(&config)
}

/// Get a formatted string of the current configuration.
pub fn show_config() -> Result<String> {
    let config = load_config()?;
    let mut lines = Vec::new();

    lines.push("Current configuration:".to_string());
    lines.push(String::new());
    lines.push(format!("  AI Tool: {}", config.ai_tool.command));

    if !config.ai_tool.args.is_empty() {
        lines.push(format!("    Args: {}", config.ai_tool.args.join(" ")));
    }

    let cmd = get_ai_tool_command()?;
    lines.push(format!("    Effective command: {}", cmd.join(" ")));
    lines.push(String::new());

    if let Some(ref method) = config.launch.method {
        let display = resolve_launch_display_name(method);
        lines.push(format!("  Launch method: {}", display));
    } else {
        lines.push("  Launch method: Foreground (default)".to_string());
    }

    // Show auto-detected default branch for current repo
    let detected = crate::git::detect_default_branch(None);
    lines.push(format!(
        "  Default base branch: {} (auto-detected)",
        detected,
    ));
    lines.push(String::new());
    lines.push(format!("Config file: {}", get_config_path().display()));

    Ok(lines.join("\n"))
}

/// Get a formatted list of available presets.
pub fn list_presets() -> String {
    let presets = ai_tool_presets();
    let mut lines = vec!["Available AI tool presets:".to_string(), String::new()];

    let mut preset_names: Vec<&str> = presets.keys().copied().collect();
    preset_names.sort();

    for name in preset_names {
        let cmd = presets[name].join(" ");
        lines.push(format!("  {:<20} -> {}", name, cmd));
    }

    lines.join("\n")
}

// ---------------------------------------------------------------------------
// Shell completion prompt
// ---------------------------------------------------------------------------

/// Check if shell integration (gw-cd) is already installed in the user's profile.
fn is_shell_integration_installed() -> bool {
    let home = home_dir_or_fallback();
    let shell_env = std::env::var("SHELL").unwrap_or_default();

    let profile_path = if shell_env.contains("zsh") {
        home.join(".zshrc")
    } else if shell_env.contains("bash") {
        home.join(".bashrc")
    } else if shell_env.contains("fish") {
        home.join(".config").join("fish").join("config.fish")
    } else {
        return false;
    };

    if let Ok(content) = std::fs::read_to_string(&profile_path) {
        content.contains("gw _shell-function") || content.contains("gw-cd")
    } else {
        false
    }
}

/// Prompt user to set up shell integration on first run.
///
/// Shows a one-time hint if:
/// - Shell integration is not already installed
/// - User has not been prompted before
///
/// Updates `shell_completion.prompted` in config after showing.
pub fn prompt_shell_completion_setup() {
    let config = match load_config() {
        Ok(c) => c,
        Err(_) => return,
    };

    if config.shell_completion.prompted || config.shell_completion.installed {
        return;
    }

    if is_shell_integration_installed() {
        // Already installed — mark both flags and skip
        let mut config = config;
        config.shell_completion.prompted = true;
        config.shell_completion.installed = true;
        let _ = save_config(&config);
        return;
    }

    // Show one-time hint
    eprintln!(
        "\n{} Shell integration (gw-cd + tab completion) is not set up.",
        console::style("Tip:").cyan().bold()
    );
    eprintln!(
        "     Run {} to enable directory navigation and completions.\n",
        console::style("gw shell-setup").cyan()
    );

    // Mark as prompted
    let mut config = config;
    config.shell_completion.prompted = true;
    let _ = save_config(&config);
}

// ---------------------------------------------------------------------------
// Launch method configuration
// ---------------------------------------------------------------------------

/// Resolve launch method alias to full name.
pub fn resolve_launch_alias(value: &str) -> String {
    let deprecated: HashMap<&str, &str> =
        HashMap::from([("bg", "detach"), ("background", "detach")]);
    let aliases = launch_method_aliases();

    // Handle session name suffix (e.g., "t:mysession")
    if let Some((prefix, suffix)) = value.split_once(':') {
        let resolved_prefix = if let Some(&new) = deprecated.get(prefix) {
            eprintln!(
                "Warning: '{}' is deprecated. Use '{}' instead.",
                prefix, new
            );
            new.to_string()
        } else {
            aliases
                .get(prefix)
                .map(|s| s.to_string())
                .unwrap_or_else(|| prefix.to_string())
        };
        return format!("{}:{}", resolved_prefix, suffix);
    }

    if let Some(&new) = deprecated.get(value) {
        eprintln!("Warning: '{}' is deprecated. Use '{}' instead.", value, new);
        return new.to_string();
    }

    aliases
        .get(value)
        .map(|s| s.to_string())
        .unwrap_or_else(|| value.to_string())
}

/// Parse --term option value.
///
/// Returns (LaunchMethod, optional_session_name).
pub fn parse_term_option(term_value: Option<&str>) -> Result<(LaunchMethod, Option<String>)> {
    let term_value = match term_value {
        Some(v) => v,
        None => return Ok((get_default_launch_method()?, None)),
    };

    let resolved = resolve_launch_alias(term_value);

    if let Some((method_str, session_name)) = resolved.split_once(':') {
        let method = LaunchMethod::from_str_opt(method_str)
            .ok_or_else(|| CwError::Config(format!("Invalid launch method: {}", method_str)))?;

        if matches!(method, LaunchMethod::Tmux | LaunchMethod::Zellij) {
            if session_name.len() > MAX_SESSION_NAME_LENGTH {
                return Err(CwError::Config(format!(
                    "Session name too long (max {} chars): {}",
                    MAX_SESSION_NAME_LENGTH, session_name
                )));
            }
            return Ok((method, Some(session_name.to_string())));
        } else {
            return Err(CwError::Config(format!(
                "Session name not supported for {}",
                method_str
            )));
        }
    }

    let method = LaunchMethod::from_str_opt(&resolved)
        .ok_or_else(|| CwError::Config(format!("Invalid launch method: {}", term_value)))?;
    Ok((method, None))
}

/// Get default launch method from config or environment.
pub fn get_default_launch_method() -> Result<LaunchMethod> {
    // 1. Environment variable
    if let Ok(env_val) = std::env::var("CW_LAUNCH_METHOD") {
        let resolved = resolve_launch_alias(&env_val);
        if let Some(method) = LaunchMethod::from_str_opt(&resolved) {
            return Ok(method);
        }
    }

    // 2. Config file
    let config = load_config()?;
    if let Some(ref method) = config.launch.method {
        let resolved = resolve_launch_alias(method);
        if let Some(m) = LaunchMethod::from_str_opt(&resolved) {
            return Ok(m);
        }
    }

    Ok(LaunchMethod::Foreground)
}

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

    #[test]
    fn test_default_config() {
        let config = Config::default();
        assert_eq!(config.ai_tool.command, "claude");
        assert!(config.ai_tool.args.is_empty());
        assert!(config.update.auto_check);
    }

    #[test]
    fn test_resolve_launch_alias() {
        assert_eq!(resolve_launch_alias("fg"), "foreground");
        assert_eq!(resolve_launch_alias("t"), "tmux");
        assert_eq!(resolve_launch_alias("z-t"), "zellij-tab");
        assert_eq!(resolve_launch_alias("t:mywork"), "tmux:mywork");
        assert_eq!(resolve_launch_alias("foreground"), "foreground");
    }

    #[test]
    fn test_parse_term_option() {
        let (method, session) = parse_term_option(Some("t")).unwrap();
        assert_eq!(method, LaunchMethod::Tmux);
        assert!(session.is_none());

        let (method, session) = parse_term_option(Some("t:mywork")).unwrap();
        assert_eq!(method, LaunchMethod::Tmux);
        assert_eq!(session.unwrap(), "mywork");

        let (method, session) = parse_term_option(Some("i-t")).unwrap();
        assert_eq!(method, LaunchMethod::ItermTab);
        assert!(session.is_none());
    }

    #[test]
    fn test_preset_names() {
        let presets = ai_tool_presets();
        assert!(presets.contains_key("claude"));
        assert!(presets.contains_key("no-op"));
        assert!(presets.contains_key("codex"));
        assert_eq!(presets["no-op"].len(), 0);
        assert_eq!(presets["claude"], vec!["claude"]);
    }

    #[test]
    fn test_list_presets_format() {
        let output = list_presets();
        assert!(output.contains("Available AI tool presets:"));
        assert!(output.contains("claude"));
        assert!(output.contains("no-op"));
    }
}