jarvy 0.0.5

Jarvy is a fast, cross-platform CLI that installs and manages developer tools across macOS and Linux.
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
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs::File;
use std::io::Write;
use std::path::PathBuf;
use std::{fs, process};

use crate::roles::definition::{RoleAssignment, RolesConfig};
use crate::team::Extends;
use crate::telemetry;
use crate::tools::{Os, current_os};

/// Default timeout for hooks in seconds (5 minutes)
pub const DEFAULT_HOOK_TIMEOUT: u64 = 300;

// ============================================================================
// Environment Variable Configuration
// ============================================================================

/// Environment variable value - can be simple string or complex with options
#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(untagged)]
pub enum EnvValue {
    /// Complex value with additional options
    Complex {
        /// The value of the environment variable (supports template expansion)
        value: String,
        /// Description for documentation
        #[serde(default)]
        description: Option<String>,
        /// Whether to append to existing PATH-like variables
        #[serde(default)]
        append: bool,
        /// Whether this is per-tool (prefixed with tool name context)
        #[serde(default)]
        per_tool: bool,
    },
    /// Simple string value (supports template expansion)
    Simple(String),
}

impl EnvValue {
    /// Get the raw value string
    pub fn value(&self) -> &str {
        match self {
            EnvValue::Complex { value, .. } => value,
            EnvValue::Simple(s) => s,
        }
    }

    /// Check if this should append to existing values
    #[allow(dead_code)] // Public API for env value manipulation
    pub fn should_append(&self) -> bool {
        match self {
            EnvValue::Complex { append, .. } => *append,
            EnvValue::Simple(_) => false,
        }
    }
}

/// Secret variable configuration
#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(untagged)]
pub enum SecretValue {
    /// Load secret from a file
    FromFile {
        /// Path to file containing the secret
        from_file: String,
    },
    /// Prompt for secret (with optional default env var to check)
    Prompt {
        /// Environment variable to check before prompting
        #[serde(default)]
        env: Option<String>,
        /// Whether this secret is required
        #[serde(default = "default_true")]
        required: bool,
        /// Description shown when prompting
        #[serde(default)]
        description: Option<String>,
    },
    /// Simple prompt marker (just the variable name)
    Simple(String),
}

fn default_true() -> bool {
    true
}

/// Settings for environment variable generation
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct EnvSettings {
    /// Target shell for rc file updates (bash, zsh, fish)
    #[serde(default)]
    pub shell: Option<String>,
    /// Whether to update shell rc files
    #[serde(default)]
    pub update_rc: bool,
    /// Whether to generate .env file
    #[serde(default = "default_true")]
    pub generate_dotenv: bool,
    /// Path for .env file (default: ./.env)
    #[serde(default = "default_dotenv_path")]
    pub dotenv_path: PathBuf,
    /// Whether to add .env to .gitignore
    #[serde(default)]
    pub add_to_gitignore: bool,
    /// Backup rc files before modification
    #[serde(default = "default_true")]
    pub backup_rc: bool,
}

fn default_dotenv_path() -> PathBuf {
    PathBuf::from(".env")
}

impl Default for EnvSettings {
    fn default() -> Self {
        Self {
            shell: None,
            update_rc: false,
            generate_dotenv: true,
            dotenv_path: default_dotenv_path(),
            add_to_gitignore: false,
            backup_rc: true,
        }
    }
}

/// Environment configuration section in jarvy.toml
#[derive(Deserialize, Serialize, Debug, Clone, Default)]
pub struct EnvConfig {
    /// Regular environment variables
    #[serde(default)]
    pub vars: HashMap<String, EnvValue>,
    /// Secret variables (prompted or loaded from file)
    #[serde(default)]
    pub secrets: HashMap<String, SecretValue>,
    /// Settings for env generation
    #[serde(default)]
    pub config: EnvSettings,
    /// Per-tool environment variables
    #[serde(flatten)]
    pub tool_env: HashMap<String, ToolEnvConfig>,
}

/// Per-tool environment variables
#[derive(Deserialize, Serialize, Debug, Clone, Default)]
pub struct ToolEnvConfig {
    /// Environment variables specific to this tool
    #[serde(default)]
    pub vars: HashMap<String, EnvValue>,
}

/// Configuration for a single hook
#[derive(Deserialize, Serialize, Debug, Clone, Default)]
pub struct ToolHooks {
    /// Script to run after this tool is installed
    #[serde(default)]
    pub post_install: Option<String>,
}

/// Settings for hook execution
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct HookSettings {
    /// Shell to use for running hooks (bash, zsh, sh, powershell)
    #[serde(default = "default_shell")]
    pub shell: String,
    /// Timeout in seconds for each hook (default: 300 = 5 minutes)
    #[serde(default = "default_timeout")]
    pub timeout: u64,
    /// Whether to continue setup if a hook fails
    #[serde(default)]
    pub continue_on_error: bool,
}

fn default_shell() -> String {
    #[cfg(windows)]
    {
        "powershell".to_string()
    }
    #[cfg(not(windows))]
    {
        std::env::var("SHELL").unwrap_or_else(|_| "/bin/sh".to_string())
    }
}

fn default_timeout() -> u64 {
    DEFAULT_HOOK_TIMEOUT
}

impl Default for HookSettings {
    fn default() -> Self {
        Self {
            shell: default_shell(),
            timeout: DEFAULT_HOOK_TIMEOUT,
            continue_on_error: false,
        }
    }
}

// ============================================================================
// Services Configuration
// ============================================================================

/// Services configuration section in jarvy.toml
#[derive(Deserialize, Serialize, Debug, Clone, Default)]
pub struct ServicesConfig {
    /// Whether services feature is enabled
    #[serde(default)]
    pub enabled: bool,
    /// Whether to auto-start services during jarvy setup
    #[serde(default)]
    pub auto_start: bool,
    /// Override path to docker-compose.yml (relative to project root)
    #[serde(default)]
    pub compose_file: Option<PathBuf>,
    /// Override path to Tiltfile (relative to project root)
    #[serde(default)]
    pub tilt_file: Option<PathBuf>,
    /// Whether to auto-start services in CI mode (default: false)
    #[serde(default)]
    pub start_in_ci: bool,
}

impl ServicesConfig {
    /// Returns true if services should be started during setup
    pub fn should_auto_start(&self, is_ci: bool) -> bool {
        if !self.enabled {
            return false;
        }
        if is_ci && !self.start_in_ci {
            return false;
        }
        self.auto_start
    }
}

// ============================================================================
// Hooks Configuration
// ============================================================================

#[derive(Deserialize, Serialize, Debug, Clone, Default)]
pub struct HooksConfig {
    /// Script to run before any tool installation
    #[serde(default)]
    pub pre_setup: Option<String>,
    /// Script to run after all tools are installed
    #[serde(default)]
    pub post_setup: Option<String>,
    /// Hook settings (shell, timeout, etc.)
    #[serde(default)]
    pub config: HookSettings,
    /// Per-tool hooks, keyed by tool name
    #[serde(flatten)]
    pub tool_hooks: HashMap<String, ToolHooks>,
}

#[derive(Deserialize)]
pub struct Config {
    /// Parent configs to extend (URL or local path)
    #[serde(default)]
    #[allow(dead_code)] // Used during config inheritance resolution
    pub extends: Option<Extends>,
    /// Role assignment for this config (single or multiple roles)
    /// Use `role = "name"` for single role or `role = ["a", "b"]` for multiple
    #[serde(default)]
    pub role: Option<RoleAssignment>,
    #[serde(rename = "provisioner")]
    tools: HashMap<String, ToolConfig>,
    #[serde(default)]
    privileges: Option<PrivilegeConfig>,
    /// Hooks configuration section
    #[serde(default)]
    pub hooks: HooksConfig,
    /// Environment variables configuration
    #[serde(default)]
    pub env: EnvConfig,
    /// Services configuration (docker-compose, tilt)
    #[serde(default)]
    pub services: ServicesConfig,
    /// Role definitions section
    #[serde(default, rename = "roles")]
    pub roles_config: RolesConfig,
    /// Network/proxy configuration
    #[serde(default)]
    #[allow(dead_code)] // Used for proxy configuration in corporate environments
    pub network: crate::network::NetworkConfig,
    /// npm package configuration
    #[serde(default)]
    pub npm: Option<crate::packages::NpmConfig>,
    /// pip package configuration
    #[serde(default)]
    pub pip: Option<crate::packages::PipConfig>,
    /// cargo binary configuration
    #[serde(default)]
    pub cargo: Option<crate::packages::CargoConfig>,
    /// Git configuration
    #[serde(default)]
    pub git: Option<crate::git::GitConfig>,
    /// Drift detection configuration
    #[serde(default)]
    pub drift: Option<crate::drift::DriftConfig>,
    /// Telemetry/OTEL configuration (project-level override for security audit)
    #[serde(default)]
    pub telemetry: Option<crate::telemetry::TelemetryConfig>,
    /// Custom project commands for interactive menu
    #[serde(default)]
    #[allow(dead_code)] // Read by interactive module via direct TOML parsing
    pub commands: CommandsConfig,
    /// Workspace configuration for monorepo support
    #[serde(default)]
    #[allow(dead_code)] // Used by workspace module for config inheritance
    pub workspace: Option<crate::workspace::WorkspaceConfig>,
}

/// Custom project commands that override the interactive menu defaults.
///
/// # Example
/// ```toml
/// [commands]
/// run = "npm start"
/// test = "npm test"
/// setup = "jarvy setup"
/// ```
#[derive(Deserialize, Serialize, Debug, Clone, Default)]
pub struct CommandsConfig {
    /// Command to run the project (default: "cargo run")
    #[serde(default)]
    pub run: Option<String>,
    /// Command to test the project (default: "cargo test")
    #[serde(default)]
    pub test: Option<String>,
    /// Command to set up the dev environment (default: "jarvy setup")
    #[serde(default)]
    pub setup: Option<String>,
}

#[derive(Deserialize, Debug, Default)]
pub struct PrivilegeConfig {
    // Global default; if None, a sensible per-OS default is used
    #[serde(default)]
    pub use_sudo: Option<bool>,
    // Per-OS overrides, e.g., { linux = true, macos = false }
    #[serde(default)]
    pub per_os: HashMap<Os, bool>,
}

impl PrivilegeConfig {
    // Sensible defaults if nothing specified
    fn default_for(_os: Os) -> Option<bool> {
        // Returning None indicates: auto-detect per operation
        None
    }

    pub fn effective_for(&self, os: Os) -> Option<bool> {
        if let Some(v) = self.per_os.get(&os) {
            Some(*v)
        } else if let Some(global) = self.use_sudo {
            Some(global)
        } else {
            Self::default_for(os)
        }
    }
}

#[derive(Deserialize, Serialize, Debug)]
#[serde(untagged)]
pub enum ToolConfig {
    Detailed {
        version: String,
        version_manager: Option<bool>,
        use_sudo: Option<bool>,
    },
    Simple(String),
}

/// Build a Tool from config, returning (key, tool) with minimal cloning.
/// This helper consolidates tool construction logic and reduces redundant clones.
fn build_tool_entry(name: &str, config: &ToolConfig) -> (String, Tool) {
    let name_owned = name.to_string();
    let (version, version_manager, use_sudo) = match config {
        ToolConfig::Detailed {
            version,
            version_manager,
            use_sudo,
        } => (version.clone(), version_manager.unwrap_or(true), *use_sudo),
        ToolConfig::Simple(version) => (version.clone(), true, None),
    };

    let tool = Tool {
        name: name_owned.clone(),
        version,
        version_manager,
        use_sudo,
    };

    (name_owned, tool)
}

impl Config {
    pub fn new(config_path: &str) -> Self {
        let config_content = match fs::read_to_string(config_path) {
            Ok(content) => content,
            Err(e) => {
                telemetry::config_parse_error(config_path, &e.to_string());
                println!("Failed to read config file at: {}", config_path);
                process::exit(crate::error_codes::CONFIG_ERROR);
            }
        };

        match toml::from_str::<Config>(&config_content) {
            Ok(config) => {
                // Emit telemetry on successful load
                telemetry::config_loaded(
                    config_path,
                    config.tools.len(),
                    config.has_hooks(),
                    config.has_env(),
                    config.services.enabled,
                );
                config
            }
            Err(e) => {
                telemetry::config_parse_error(config_path, &e.to_string());
                println!("Failed to parse config file: {}", e);
                process::exit(crate::error_codes::CONFIG_ERROR);
            }
        }
    }

    /// Load the config at `config_path`, walking up to find a workspace root and
    /// merging inherited sections from the root config when present.
    ///
    /// When the current directory is inside a workspace member, sections listed
    /// in the root's `[workspace] inherit = [...]` are merged in (member wins
    /// on conflict; for `provisioner`, individual tools merge tool-by-tool).
    ///
    /// Falls back to plain `Config::new(config_path)` semantics when no
    /// workspace root is discovered.
    pub fn new_with_workspace(config_path: &str) -> Self {
        let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
        let Some(ctx) = crate::workspace::find_workspace_root(&cwd) else {
            return Self::new(config_path);
        };

        // If the active config_path IS the root config, plain load is fine.
        let abs_config_path =
            std::fs::canonicalize(config_path).unwrap_or_else(|_| PathBuf::from(config_path));
        let abs_root =
            std::fs::canonicalize(&ctx.root_config).unwrap_or_else(|_| ctx.root_config.clone());
        if abs_config_path == abs_root {
            return Self::new(config_path);
        }

        // We are in a member. Read root + member as toml::Value, merge, then
        // deserialize. This avoids re-implementing every Config field merge.
        let root_text = match fs::read_to_string(&ctx.root_config) {
            Ok(s) => s,
            Err(e) => {
                tracing::warn!(
                    event = "workspace.root_read_failed",
                    path = %ctx.root_config.display(),
                    error = %e,
                );
                return Self::new(config_path);
            }
        };
        let member_text = match fs::read_to_string(config_path) {
            Ok(s) => s,
            Err(e) => {
                telemetry::config_parse_error(config_path, &e.to_string());
                println!("Failed to read config file at: {}", config_path);
                process::exit(crate::error_codes::CONFIG_ERROR);
            }
        };

        let root_value = match toml::from_str::<toml::Value>(&root_text) {
            Ok(v) => v,
            Err(e) => {
                tracing::warn!(
                    event = "workspace.root_parse_failed",
                    path = %ctx.root_config.display(),
                    error = %e,
                );
                return Self::new(config_path);
            }
        };
        let member_value = match toml::from_str::<toml::Value>(&member_text) {
            Ok(v) => v,
            Err(e) => {
                telemetry::config_parse_error(config_path, &e.to_string());
                println!("Failed to parse config file: {}", e);
                process::exit(crate::error_codes::CONFIG_ERROR);
            }
        };

        let merged =
            crate::workspace::merge_configs(&root_value, &member_value, &ctx.workspace.inherit);

        match merged.try_into::<Config>() {
            Ok(config) => {
                tracing::info!(
                    event = "workspace.config_merged",
                    member = ctx.current_member.as_deref().unwrap_or(""),
                    inherit_count = ctx.workspace.inherit.len(),
                );
                telemetry::config_loaded(
                    config_path,
                    config.tools.len(),
                    config.has_hooks(),
                    config.has_env(),
                    config.services.enabled,
                );
                config
            }
            Err(e) => {
                telemetry::config_parse_error(config_path, &e.to_string());
                println!("Failed to parse merged workspace config: {}", e);
                process::exit(crate::error_codes::CONFIG_ERROR);
            }
        }
    }

    pub fn get_tool_configs(&self) -> HashMap<String, Tool> {
        self.tools
            .iter()
            .map(|(name, config)| build_tool_entry(name, config))
            .collect()
    }

    // Returns whether sudo should be used on the current OS; None => auto-detect per op
    pub fn use_sudo(&self) -> Option<bool> {
        let os = current_os();
        self.privileges
            .as_ref()
            .map(|p| p.effective_for(os))
            .unwrap_or_else(|| PrivilegeConfig::default_for(os))
    }

    /// Get the hooks configuration
    pub fn get_hooks(&self) -> &HooksConfig {
        &self.hooks
    }

    /// Get hooks for a specific tool
    pub fn get_tool_hooks(&self, tool_name: &str) -> Option<&ToolHooks> {
        self.hooks.tool_hooks.get(tool_name)
    }

    /// Check if any hooks are configured
    pub fn has_hooks(&self) -> bool {
        self.hooks.pre_setup.is_some()
            || self.hooks.post_setup.is_some()
            || self
                .hooks
                .tool_hooks
                .values()
                .any(|h| h.post_install.is_some())
    }

    /// Get the environment configuration
    pub fn get_env(&self) -> &EnvConfig {
        &self.env
    }

    /// Get environment variables for a specific tool
    #[allow(dead_code)] // Public API for tool-specific environment access
    pub fn get_tool_env(&self, tool_name: &str) -> Option<&ToolEnvConfig> {
        self.env.tool_env.get(tool_name)
    }

    /// Check if any environment variables are configured
    pub fn has_env(&self) -> bool {
        !self.env.vars.is_empty()
            || !self.env.secrets.is_empty()
            || self.env.tool_env.values().any(|t| !t.vars.is_empty())
    }

    /// Get the roles configuration
    pub fn get_roles_config(&self) -> &RolesConfig {
        &self.roles_config
    }

    /// Check if any roles are defined
    pub fn has_roles(&self) -> bool {
        !self.roles_config.roles.is_empty()
    }

    /// Get assigned role(s) if any
    pub fn get_assigned_roles(&self) -> Option<Vec<&str>> {
        self.role.as_ref().map(|r| r.as_vec())
    }

    /// Check if a role is assigned
    #[allow(dead_code)] // Public API for role configuration access
    pub fn has_assigned_role(&self) -> bool {
        self.role.as_ref().map(|r| !r.is_empty()).unwrap_or(false)
    }

    /// Get the packages configuration for npm/pip/cargo
    pub fn get_packages_config(&self) -> crate::packages::PackagesConfig {
        crate::packages::PackagesConfig {
            npm: self.npm.clone(),
            pip: self.pip.clone(),
            cargo: self.cargo.clone(),
            gem: None,
            go: None,
        }
    }

    /// Check if any packages are configured
    pub fn has_packages(&self) -> bool {
        self.npm.is_some() || self.pip.is_some() || self.cargo.is_some()
    }

    /// Get the git configuration
    pub fn get_git(&self) -> Option<&crate::git::GitConfig> {
        self.git.as_ref()
    }

    /// Check if git configuration is present
    pub fn has_git(&self) -> bool {
        self.git.is_some()
    }

    /// Get tool configs with roles applied
    /// This merges role tools with directly configured tools
    /// Direct tools override role tools
    #[allow(dead_code)] // Public API for role-based tool configuration
    pub fn get_tool_configs_with_roles(&self) -> HashMap<String, Tool> {
        use crate::roles::resolver::RoleResolver;

        let mut result = HashMap::new();

        // If roles are assigned, resolve and add those tools first
        if let Some(role_assignment) = &self.role {
            let role_names = role_assignment.as_vec();
            if !role_names.is_empty() && self.has_roles() {
                let mut resolver = RoleResolver::new(&self.roles_config);
                if let Ok(resolved) = resolver.resolve_multiple(&role_names) {
                    for (name, tool) in resolved.tools {
                        result.insert(
                            name.clone(),
                            Tool {
                                name,
                                version: tool.version,
                                version_manager: tool.version_manager,
                                use_sudo: tool.use_sudo,
                            },
                        );
                    }
                }
            }
        }

        // Direct tools override role tools - use helper for minimal cloning
        for (name, config) in &self.tools {
            let (key, tool) = build_tool_entry(name, config);
            result.insert(key, tool);
        }

        result
    }

    /// Get tool configs with an optional CLI role override
    /// If role_override is Some, it temporarily replaces the config's role assignment
    /// This is used by the --role flag in the setup command
    pub fn get_tool_configs_with_role_override(
        &self,
        role_override: Option<&str>,
    ) -> HashMap<String, Tool> {
        use crate::roles::resolver::RoleResolver;

        let mut result = HashMap::new();

        // Determine which role(s) to use: CLI override takes precedence
        // Avoid cloning self.role by computing role_names directly
        let role_names: Vec<&str> = match (role_override, &self.role) {
            (Some(name), _) => vec![name],
            (None, Some(assignment)) => assignment.as_vec(),
            (None, None) => vec![],
        };

        // If roles are assigned, resolve and add those tools first
        if !role_names.is_empty() && self.has_roles() {
            let mut resolver = RoleResolver::new(&self.roles_config);
            if let Ok(resolved) = resolver.resolve_multiple(&role_names) {
                for (name, tool) in resolved.tools {
                    // Move name into Tool.name, only clone for HashMap key
                    result.insert(
                        name.clone(),
                        Tool {
                            name,
                            version: tool.version,
                            version_manager: tool.version_manager,
                            use_sudo: tool.use_sudo,
                        },
                    );
                }
            }
        }

        // Direct tools override role tools - use helper for minimal cloning
        for (name, config) in &self.tools {
            let (key, tool) = build_tool_entry(name, config);
            result.insert(key, tool);
        }

        result
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Tool {
    pub name: String,
    pub version: String,
    pub version_manager: bool,
    pub use_sudo: Option<bool>, // carry per-tool override
}

pub fn create_default_config() {
    let default_config = r#"
[privileges]
use_sudo = true

[privileges.per_os]
linux = true
macos = false
windows = false

[provisioner]
git = "latest"
docker = "latest"

# Hook configuration (optional)
# [hooks]
# pre_setup = "echo 'Starting Jarvy setup...'"
# post_setup = "echo 'Setup complete!'"
#
# [hooks.config]
# shell = "zsh"           # or "bash", "sh", "powershell"
# timeout = 300           # seconds (default: 5 minutes)
# continue_on_error = false
#
# [hooks.node]
# post_install = "npm install -g yarn"

# Environment variables (optional)
# [env.vars]
# MY_VAR = "simple_value"
# PROJECT_ROOT = "$PWD"
# NODE_PATH = { value = "$HOME/.node/bin", append = true }
#
# [env.secrets]
# API_KEY = { env = "MY_API_KEY", required = true }
# DB_PASSWORD = { from_file = "~/.secrets/db_pass" }
#
# [env.config]
# generate_dotenv = true
# dotenv_path = ".env"
# update_rc = false
# add_to_gitignore = true
"#;
    let mut file = match File::create("jarvy.toml") {
        Ok(f) => f,
        Err(e) => {
            eprintln!("Could not create jarvy.toml: {e}");
            return;
        }
    };
    if let Err(e) = file.write_all(default_config.as_bytes()) {
        eprintln!("Could not write to jarvy.toml: {e}");
        return;
    }
    println!("Created jarvy.toml with default configuration");
}

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

    #[test]
    fn test_hooks_config_parsing() {
        let toml_str = r#"
[provisioner]
git = "latest"

[hooks]
pre_setup = "echo 'Starting setup'"
post_setup = "echo 'Done'"

[hooks.config]
shell = "zsh"
timeout = 120
continue_on_error = true

[hooks.node]
post_install = "npm install -g yarn"
"#;
        let config: Config = toml::from_str(toml_str).expect("Failed to parse config");

        assert_eq!(
            config.hooks.pre_setup,
            Some("echo 'Starting setup'".to_string())
        );
        assert_eq!(config.hooks.post_setup, Some("echo 'Done'".to_string()));
        assert_eq!(config.hooks.config.shell, "zsh");
        assert_eq!(config.hooks.config.timeout, 120);
        assert!(config.hooks.config.continue_on_error);

        let node_hooks = config
            .get_tool_hooks("node")
            .expect("node hooks should exist");
        assert_eq!(
            node_hooks.post_install,
            Some("npm install -g yarn".to_string())
        );
    }

    #[test]
    fn test_hooks_config_defaults() {
        let toml_str = r#"
[provisioner]
git = "latest"
"#;
        let config: Config = toml::from_str(toml_str).expect("Failed to parse config");

        assert!(config.hooks.pre_setup.is_none());
        assert!(config.hooks.post_setup.is_none());
        assert_eq!(config.hooks.config.timeout, DEFAULT_HOOK_TIMEOUT);
        assert!(!config.hooks.config.continue_on_error);
        assert!(!config.has_hooks());
    }

    #[test]
    fn test_has_hooks() {
        let toml_str = r#"
[provisioner]
git = "latest"

[hooks]
pre_setup = "echo 'hi'"
"#;
        let config: Config = toml::from_str(toml_str).expect("Failed to parse config");
        assert!(config.has_hooks());
    }

    #[test]
    fn test_hook_settings_default_shell() {
        let settings = HookSettings::default();
        // Should be the value of SHELL env var or /bin/sh on Unix, powershell on Windows
        #[cfg(not(windows))]
        {
            assert!(!settings.shell.is_empty());
        }
        #[cfg(windows)]
        {
            assert_eq!(settings.shell, "powershell");
        }
        assert_eq!(settings.timeout, DEFAULT_HOOK_TIMEOUT);
        assert!(!settings.continue_on_error);
    }

    #[test]
    fn test_env_config_parsing_simple() {
        let toml_str = r#"
[provisioner]
git = "latest"

[env.vars]
MY_VAR = "simple_value"
PROJECT_ROOT = "$PWD"
"#;
        let config: Config = toml::from_str(toml_str).expect("Failed to parse config");

        assert_eq!(config.env.vars.len(), 2);
        assert!(config.has_env());

        let my_var = config.env.vars.get("MY_VAR").expect("MY_VAR should exist");
        assert_eq!(my_var.value(), "simple_value");
        assert!(!my_var.should_append());
    }

    #[test]
    fn test_env_config_parsing_complex() {
        let toml_str = r#"
[provisioner]
git = "latest"

[env.vars]
NODE_PATH = { value = "$HOME/.node/bin", append = true, description = "Node binaries" }
SIMPLE = "just_a_value"

[env.config]
generate_dotenv = true
dotenv_path = ".env.local"
update_rc = true
add_to_gitignore = true
"#;
        let config: Config = toml::from_str(toml_str).expect("Failed to parse config");

        let node_path = config
            .env
            .vars
            .get("NODE_PATH")
            .expect("NODE_PATH should exist");
        assert_eq!(node_path.value(), "$HOME/.node/bin");
        assert!(node_path.should_append());

        assert!(config.env.config.generate_dotenv);
        assert_eq!(config.env.config.dotenv_path, PathBuf::from(".env.local"));
        assert!(config.env.config.update_rc);
        assert!(config.env.config.add_to_gitignore);
    }

    #[test]
    fn test_env_config_secrets() {
        let toml_str = r#"
[provisioner]
git = "latest"

[env.secrets]
API_KEY = { env = "MY_API_KEY", required = true }
DB_PASSWORD = { from_file = "~/.secrets/db_pass" }
OPTIONAL_KEY = { required = false, description = "Optional API key" }
"#;
        let config: Config = toml::from_str(toml_str).expect("Failed to parse config");

        assert_eq!(config.env.secrets.len(), 3);
        assert!(config.has_env());
    }

    #[test]
    fn test_env_config_defaults() {
        let toml_str = r#"
[provisioner]
git = "latest"
"#;
        let config: Config = toml::from_str(toml_str).expect("Failed to parse config");

        assert!(config.env.vars.is_empty());
        assert!(config.env.secrets.is_empty());
        assert!(config.env.config.generate_dotenv);
        assert_eq!(config.env.config.dotenv_path, PathBuf::from(".env"));
        assert!(!config.env.config.update_rc);
        assert!(!config.has_env());
    }

    #[test]
    fn test_env_settings_default() {
        let settings = EnvSettings::default();
        assert!(settings.shell.is_none());
        assert!(!settings.update_rc);
        assert!(settings.generate_dotenv);
        assert_eq!(settings.dotenv_path, PathBuf::from(".env"));
        assert!(!settings.add_to_gitignore);
        assert!(settings.backup_rc);
    }

    #[test]
    fn test_services_config_defaults() {
        let toml_str = r#"
[provisioner]
git = "latest"
"#;
        let config: Config = toml::from_str(toml_str).expect("Failed to parse config");

        assert!(!config.services.enabled);
        assert!(!config.services.auto_start);
        assert!(config.services.compose_file.is_none());
        assert!(config.services.tilt_file.is_none());
        assert!(!config.services.start_in_ci);
    }

    #[test]
    fn test_services_config_parsing() {
        let toml_str = r#"
[provisioner]
git = "latest"

[services]
enabled = true
auto_start = true
compose_file = "docker/docker-compose.yml"
start_in_ci = false
"#;
        let config: Config = toml::from_str(toml_str).expect("Failed to parse config");

        assert!(config.services.enabled);
        assert!(config.services.auto_start);
        assert_eq!(
            config.services.compose_file,
            Some(PathBuf::from("docker/docker-compose.yml"))
        );
        assert!(!config.services.start_in_ci);
    }

    #[test]
    fn test_services_should_auto_start() {
        // Test disabled services
        let disabled = ServicesConfig {
            enabled: false,
            auto_start: true,
            ..Default::default()
        };
        assert!(!disabled.should_auto_start(false));
        assert!(!disabled.should_auto_start(true));

        // Test enabled with auto_start off
        let no_auto = ServicesConfig {
            enabled: true,
            auto_start: false,
            ..Default::default()
        };
        assert!(!no_auto.should_auto_start(false));
        assert!(!no_auto.should_auto_start(true));

        // Test enabled with auto_start on, CI off
        let auto_no_ci = ServicesConfig {
            enabled: true,
            auto_start: true,
            start_in_ci: false,
            ..Default::default()
        };
        assert!(auto_no_ci.should_auto_start(false)); // not in CI
        assert!(!auto_no_ci.should_auto_start(true)); // in CI, start_in_ci is false

        // Test enabled with auto_start and start_in_ci on
        let auto_with_ci = ServicesConfig {
            enabled: true,
            auto_start: true,
            start_in_ci: true,
            ..Default::default()
        };
        assert!(auto_with_ci.should_auto_start(false));
        assert!(auto_with_ci.should_auto_start(true));
    }
}