arct-config 0.2.2

Configuration management for Arc Academy Terminal
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
//! Configuration management for Arc Academy Terminal

use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use std::path::PathBuf;

/// Main configuration structure
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Config {
    /// General application settings
    #[serde(default)]
    pub general: GeneralConfig,

    /// Theme configuration
    #[serde(default)]
    pub theme: ThemeConfig,

    /// AI integration settings
    #[serde(default)]
    pub ai: AIConfig,

    /// Telemetry settings
    #[serde(default)]
    pub telemetry: TelemetryConfig,

    /// Shell settings
    #[serde(default)]
    pub shell: ShellConfig,

    /// Keybinding customization
    #[serde(default)]
    pub keybindings: KeybindingsConfig,
}

/// General application settings
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GeneralConfig {
    /// User's name for personalization
    #[serde(default)]
    pub user_name: Option<String>,

    /// Whether first-run setup is complete
    #[serde(default = "default_false")]
    pub setup_complete: bool,

    /// Default shell to use (bash, zsh, fish, etc.)
    #[serde(default = "default_shell")]
    pub shell: String,

    /// Command history limit
    #[serde(default = "default_history_limit")]
    pub history_limit: usize,

    /// Command timeout in seconds
    #[serde(default = "default_command_timeout")]
    pub command_timeout: u64,

    /// Enable auto-save for session
    #[serde(default = "default_true")]
    pub auto_save: bool,
}

/// Theme configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ThemeConfig {
    /// Default theme name
    #[serde(default = "default_theme")]
    pub default_theme: String,

    /// Enable ANSI colors
    #[serde(default = "default_true")]
    pub enable_colors: bool,

    /// Color depth (16, 256, or "true")
    #[serde(default = "default_color_depth")]
    pub color_depth: String,
}

/// AI integration settings
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AIConfig {
    /// Enable AI assistant
    #[serde(default = "default_false")]
    pub enabled: bool,

    /// AI provider (anthropic, openai, local, managed)
    #[serde(default = "default_ai_provider")]
    pub provider: String,

    /// API key (use env var for security)
    #[serde(default)]
    pub api_key: Option<String>,

    /// Model name
    #[serde(default)]
    pub model: Option<String>,

    /// Custom API endpoint (for local/self-hosted)
    #[serde(default)]
    pub endpoint: Option<String>,

    /// Max tokens per request
    #[serde(default = "default_max_tokens")]
    pub max_tokens: usize,
}

/// Telemetry settings
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TelemetryConfig {
    /// Enable telemetry (opt-in)
    #[serde(default = "default_false")]
    pub enabled: bool,

    /// Anonymous user ID
    #[serde(default)]
    pub user_id: Option<String>,

    /// Send usage statistics
    #[serde(default = "default_false")]
    pub usage_stats: bool,

    /// Send error reports
    #[serde(default = "default_false")]
    pub error_reports: bool,
}

/// Shell settings
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ShellConfig {
    /// Persistent environment variables
    #[serde(default)]
    pub environment: HashMap<String, String>,

    /// Persistent aliases
    #[serde(default)]
    pub aliases: HashMap<String, String>,

    /// Startup commands to run
    #[serde(default)]
    pub startup_commands: Vec<String>,
}

/// Keybinding customization
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KeybindingsConfig {
    /// Custom keybindings (key -> action)
    #[serde(default)]
    pub custom: HashMap<String, String>,
}

impl Config {
    /// Create a new configuration with defaults
    pub fn new() -> Self {
        Self::default()
    }

    /// Load configuration from disk
    pub fn load() -> Result<Self> {
        let config_path = get_config_file_path()?;

        if !config_path.exists() {
            // Create default config if it doesn't exist
            let config = Self::default();
            config.save()?;
            return Ok(config);
        }

        let config_str = fs::read_to_string(&config_path)
            .with_context(|| format!("Failed to read config file: {}", config_path.display()))?;

        let mut config: Config = toml::from_str(&config_str)
            .with_context(|| format!("Failed to parse config file: {}", config_path.display()))?;

        // Override with environment variables
        config.apply_env_overrides();

        Ok(config)
    }

    /// Save configuration to disk
    pub fn save(&self) -> Result<()> {
        let config_path = get_config_file_path()?;

        // Ensure config directory exists
        if let Some(parent) = config_path.parent() {
            fs::create_dir_all(parent)
                .with_context(|| format!("Failed to create config directory: {}", parent.display()))?;
        }

        let config_str = toml::to_string_pretty(self)
            .context("Failed to serialize config")?;

        fs::write(&config_path, config_str)
            .with_context(|| format!("Failed to write config file: {}", config_path.display()))?;

        Ok(())
    }

    /// Apply environment variable overrides
    fn apply_env_overrides(&mut self) {
        // AI API key from environment
        if let Ok(api_key) = std::env::var("ARCT_AI_API_KEY") {
            self.ai.api_key = Some(api_key);
        }

        // AI provider from environment
        if let Ok(provider) = std::env::var("ARCT_AI_PROVIDER") {
            self.ai.provider = provider;
        }

        // Telemetry opt-out
        if let Ok(telemetry) = std::env::var("ARCT_TELEMETRY") {
            self.telemetry.enabled = telemetry == "1" || telemetry.to_lowercase() == "true";
        }

        // Shell override
        if let Ok(shell) = std::env::var("ARCT_SHELL") {
            self.general.shell = shell;
        }
    }

    /// Get config file path
    pub fn config_path() -> Result<PathBuf> {
        get_config_file_path()
    }
}

impl Default for Config {
    fn default() -> Self {
        Self {
            general: GeneralConfig::default(),
            theme: ThemeConfig::default(),
            ai: AIConfig::default(),
            telemetry: TelemetryConfig::default(),
            shell: ShellConfig::default(),
            keybindings: KeybindingsConfig::default(),
        }
    }
}

impl Default for GeneralConfig {
    fn default() -> Self {
        Self {
            user_name: None,
            setup_complete: false,
            shell: default_shell(),
            history_limit: default_history_limit(),
            command_timeout: default_command_timeout(),
            auto_save: true,
        }
    }
}

impl Default for ThemeConfig {
    fn default() -> Self {
        Self {
            default_theme: default_theme(),
            enable_colors: true,
            color_depth: default_color_depth(),
        }
    }
}

impl Default for AIConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            provider: default_ai_provider(),
            api_key: None,
            model: None,
            endpoint: None,
            max_tokens: default_max_tokens(),
        }
    }
}

impl Default for TelemetryConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            user_id: None,
            usage_stats: false,
            error_reports: false,
        }
    }
}

impl Default for ShellConfig {
    fn default() -> Self {
        Self {
            environment: HashMap::new(),
            aliases: HashMap::new(),
            startup_commands: Vec::new(),
        }
    }
}

impl Default for KeybindingsConfig {
    fn default() -> Self {
        Self {
            custom: HashMap::new(),
        }
    }
}

/// Get the configuration file path (XDG-compliant)
pub fn get_config_file_path() -> Result<PathBuf> {
    let config_dir = dirs::config_dir()
        .context("Could not find config directory")?;

    let arct_config_dir = config_dir.join("arct");

    if !arct_config_dir.exists() {
        fs::create_dir_all(&arct_config_dir)
            .with_context(|| format!("Failed to create config directory: {}", arct_config_dir.display()))?;
    }

    Ok(arct_config_dir.join("config.toml"))
}

/// Generate a default configuration file as a string
pub fn generate_default_config() -> String {
    let config = Config::default();
    toml::to_string_pretty(&config).unwrap_or_else(|_| String::from("# Failed to generate config"))
}

// Default value functions
fn default_shell() -> String {
    std::env::var("SHELL")
        .unwrap_or_else(|_| "bash".to_string())
        .split('/')
        .last()
        .unwrap_or("bash")
        .to_string()
}

fn default_history_limit() -> usize {
    1000
}

fn default_command_timeout() -> u64 {
    5
}

fn default_theme() -> String {
    "Arc Academy Orange".to_string()
}

fn default_color_depth() -> String {
    "256".to_string()
}

fn default_ai_provider() -> String {
    "anthropic".to_string()
}

fn default_max_tokens() -> usize {
    4096
}

fn default_true() -> bool {
    true
}

fn default_false() -> bool {
    false
}

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

    #[test]
    fn test_default_config() {
        let config = Config::default();
        assert_eq!(config.general.history_limit, 1000);
        assert_eq!(config.theme.default_theme, "Arc Academy Orange");
        assert!(!config.ai.enabled);
        assert!(!config.telemetry.enabled);
    }

    #[test]
    fn test_serialize_config() {
        let config = Config::default();
        let toml_str = toml::to_string(&config).unwrap();
        assert!(toml_str.contains("[general]"));
        assert!(toml_str.contains("[theme]"));
    }

    #[test]
    fn test_deserialize_config() {
        let toml_str = r#"
            [general]
            shell = "zsh"
            history_limit = 500

            [theme]
            default_theme = "Arc Dark"
        "#;

        let config: Config = toml::from_str(toml_str).unwrap();
        assert_eq!(config.general.shell, "zsh");
        assert_eq!(config.general.history_limit, 500);
        assert_eq!(config.theme.default_theme, "Arc Dark");
    }
}