arct-cli 0.2.2

Arc Academy Terminal - Learn shell commands interactively with AI-powered explanations
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
//! Arc Academy Terminal - CLI Entry Point

use anyhow::Result;
use clap::{Parser, Subcommand};
use std::path::PathBuf;

const VERSION: &str = env!("CARGO_PKG_VERSION");
const ABOUT: &str = "🎓 Arc Academy Terminal - Learn shell commands interactively";

#[derive(Parser)]
#[command(name = "arct")]
#[command(version = VERSION)]
#[command(about = ABOUT, long_about = None)]
#[command(author = "Arc Academy")]
struct Cli {
    /// Enable verbose logging
    #[arg(short, long, global = true)]
    verbose: bool,

    /// Config file path (defaults to ~/.config/arct/config.toml)
    #[arg(short, long, global = true)]
    config: Option<PathBuf>,

    #[command(subcommand)]
    command: Option<Commands>,
}

#[derive(Subcommand)]
enum Commands {
    /// Start the interactive TUI (default)
    #[command(visible_alias = "tui")]
    Start {
        /// Start with a specific theme
        #[arg(long)]
        theme: Option<String>,

        /// Working directory to start in
        #[arg(long)]
        dir: Option<PathBuf>,
    },

    /// Manage configuration
    Config {
        #[command(subcommand)]
        action: ConfigAction,
    },

    /// Quick command explanation (non-interactive)
    Explain {
        /// Command to explain
        command: String,
    },

    /// Show version information
    Version,

    /// Show configuration paths and system info
    Info,

    /// Manage telemetry data
    Telemetry {
        #[command(subcommand)]
        action: TelemetryAction,
    },
}

#[derive(Subcommand)]
enum ConfigAction {
    /// Show current configuration
    Show,

    /// Edit configuration file
    Edit,

    /// Reset configuration to defaults
    Reset {
        /// Skip confirmation
        #[arg(short, long)]
        yes: bool,
    },

    /// Get configuration file path
    Path,

    /// Generate default configuration
    Init {
        /// Overwrite existing config
        #[arg(short, long)]
        force: bool,
    },
}

#[derive(Subcommand)]
enum TelemetryAction {
    /// Show telemetry statistics
    Stats,

    /// Export all telemetry data as JSON
    Export {
        /// Output file (defaults to stdout)
        #[arg(short, long)]
        output: Option<PathBuf>,
    },

    /// Delete all telemetry data
    Delete {
        /// Skip confirmation
        #[arg(short, long)]
        yes: bool,
    },

    /// Show telemetry database path
    Path,
}

#[tokio::main]
async fn main() -> Result<()> {
    let cli = Cli::parse();

    // Initialize tracing based on verbosity
    let log_level = if cli.verbose { "debug" } else { "info" };
    tracing_subscriber::fmt()
        .with_env_filter(
            tracing_subscriber::EnvFilter::try_from_default_env()
                .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new(log_level)),
        )
        .init();

    // Load config if specified
    if let Some(config_path) = cli.config {
        tracing::info!("Using config from: {}", config_path.display());
        // TODO: Pass custom config path to app
    }

    match cli.command {
        None | Some(Commands::Start { .. }) => {
            // Default: run TUI
            run_tui(cli.command).await?;
        }
        Some(Commands::Config { action }) => {
            handle_config(action)?;
        }
        Some(Commands::Explain { command }) => {
            handle_explain(&command)?;
        }
        Some(Commands::Version) => {
            print_version();
        }
        Some(Commands::Info) => {
            print_info()?;
        }
        Some(Commands::Telemetry { action }) => {
            handle_telemetry(action)?;
        }
    }

    Ok(())
}

async fn run_tui(command: Option<Commands>) -> Result<()> {
    // Apply any start options
    if let Some(Commands::Start { theme, dir }) = command {
        if let Some(theme_name) = theme {
            tracing::info!("Starting with theme: {}", theme_name);
            // TODO: Pass theme to app
        }
        if let Some(working_dir) = dir {
            std::env::set_current_dir(&working_dir)?;
            tracing::info!("Starting in directory: {}", working_dir.display());
        }
    }

    // Run the TUI
    arct_tui::run().await?;

    Ok(())
}

fn handle_config(action: ConfigAction) -> Result<()> {
    match action {
        ConfigAction::Show => {
            let config = arct_config::Config::load()?;
            let toml_str = toml::to_string_pretty(&config)?;
            println!("{}", toml_str);
        }
        ConfigAction::Edit => {
            let config_path = arct_config::get_config_file_path()?;
            let editor = std::env::var("EDITOR").unwrap_or_else(|_| "vim".to_string());

            println!("Opening config in {}...", editor);
            std::process::Command::new(editor)
                .arg(&config_path)
                .status()?;
        }
        ConfigAction::Reset { yes } => {
            if !yes {
                print!("Reset configuration to defaults? [y/N] ");
                use std::io::{self, Write};
                io::stdout().flush()?;

                let mut input = String::new();
                io::stdin().read_line(&mut input)?;

                if !input.trim().eq_ignore_ascii_case("y") {
                    println!("Cancelled.");
                    return Ok(());
                }
            }

            let config = arct_config::Config::default();
            config.save()?;
            println!("✓ Configuration reset to defaults");
        }
        ConfigAction::Path => {
            let config_path = arct_config::get_config_file_path()?;
            println!("{}", config_path.display());
        }
        ConfigAction::Init { force } => {
            let config_path = arct_config::get_config_file_path()?;

            if config_path.exists() && !force {
                eprintln!("Config file already exists: {}", config_path.display());
                eprintln!("Use --force to overwrite");
                return Ok(());
            }

            let config = arct_config::Config::default();
            config.save()?;
            println!("✓ Created config file: {}", config_path.display());
        }
    }
    Ok(())
}

fn handle_explain(command_str: &str) -> Result<()> {
    use arct_core::{CommandAnalyzer, Educator};

    let analyzer = CommandAnalyzer::new();
    let mut educator = Educator::new();

    let cmd = analyzer.parse(command_str)?;
    let explanation = educator.explain(&cmd)?;

    println!("\n📚 Command: {}\n", cmd.program);
    println!("{}\n", explanation.summary);

    if !explanation.flag_explanations.is_empty() {
        println!("🔍 Flags:");
        for flag_exp in &explanation.flag_explanations {
            println!("  {} - {}", flag_exp.flag, flag_exp.description);
        }
        println!();
    }

    if !explanation.warnings.is_empty() {
        println!("⚠️  Warnings:");
        for warning in &explanation.warnings {
            println!("{} - {}", warning.severity, warning.message);
            if let Some(suggestion) = &warning.suggestion {
                println!("{}", suggestion);
            }
        }
        println!();
    }

    if !explanation.tips.is_empty() {
        println!("💡 Tips:");
        for tip in &explanation.tips {
            println!("{} - {}", tip.title, tip.content);
        }
        println!();
    }

    Ok(())
}

fn print_version() {
    println!("Arc Academy Terminal v{}", VERSION);
    println!();
    println!("🌐 arcacademy.sh");
    println!("📚 Learn shell commands interactively");
}

fn print_info() -> Result<()> {
    println!("Arc Academy Terminal - System Info");
    println!("==================================\n");

    println!("Version:  {}", VERSION);
    println!();

    // Config paths
    if let Ok(config_path) = arct_config::get_config_file_path() {
        println!("Config:   {}", config_path.display());
        println!("          {}", if config_path.exists() { "exists" } else { "not found" });
    }

    // Session paths
    if let Ok(session_path) = arct_tui::persistence::get_session_file_path() {
        println!("Session:  {}", session_path.display());
        println!("          {}", if session_path.exists() { "exists" } else { "not found" });
    }

    println!();

    // System info
    println!("OS:       {}", std::env::consts::OS);
    println!("Arch:     {}", std::env::consts::ARCH);

    if let Ok(shell) = std::env::var("SHELL") {
        println!("Shell:    {}", shell);
    }

    if let Ok(user) = std::env::var("USER").or_else(|_| std::env::var("USERNAME")) {
        println!("User:     {}", user);
    }

    if let Ok(home) = std::env::var("HOME") {
        println!("Home:     {}", home);
    }

    println!();
    println!("🌐 Website: https://arcacademy.sh");
    println!("📖 Docs:    https://docs.arcacademy.sh");
    println!("🐛 Issues:  https://github.com/arc-academy/terminal/issues");

    Ok(())
}

fn handle_telemetry(action: TelemetryAction) -> Result<()> {
    use arct_telemetry::Telemetry;

    match action {
        TelemetryAction::Stats => {
            // Load config to check if telemetry is enabled
            let config = arct_config::Config::load()?;

            if !config.telemetry.enabled {
                println!("⚠️  Telemetry is disabled");
                println!("Enable it in your config to collect usage statistics:");
                println!("  arct config edit");
                println!("  Set: telemetry.enabled = true");
                return Ok(());
            }

            let telemetry = Telemetry::new(true)?;
            let stats = telemetry.get_stats()?;

            println!("📊 Telemetry Statistics\n");
            println!("Sessions:  {}", stats.total_sessions);
            println!("Commands:  {}", stats.total_commands);
            println!("Errors:    {}", stats.total_errors);
            println!();

            if !stats.top_commands.is_empty() {
                println!("Top Commands:");
                for (cmd, count) in stats.top_commands.iter().take(10) {
                    println!("  {:20} {}", cmd, count);
                }
                println!();
            }

            if !stats.features_used.is_empty() {
                println!("Features Used:");
                for (feature, count) in stats.features_used.iter().take(10) {
                    println!("  {:20} {}", feature, count);
                }
                println!();
            }
        }
        TelemetryAction::Export { output } => {
            let telemetry = Telemetry::new(true)?;
            let data = telemetry.export_data()?;

            if let Some(output_path) = output {
                std::fs::write(&output_path, data)?;
                println!("✓ Telemetry data exported to: {}", output_path.display());
            } else {
                println!("{}", data);
            }
        }
        TelemetryAction::Delete { yes } => {
            if !yes {
                print!("Delete all telemetry data? This cannot be undone. [y/N] ");
                use std::io::{self, Write};
                io::stdout().flush()?;

                let mut input = String::new();
                io::stdin().read_line(&mut input)?;

                if !input.trim().eq_ignore_ascii_case("y") {
                    println!("Cancelled.");
                    return Ok(());
                }
            }

            let telemetry = Telemetry::new(true)?;
            telemetry.delete_all_data()?;
            println!("✓ All telemetry data deleted");
        }
        TelemetryAction::Path => {
            let path = arct_telemetry::get_telemetry_db_path()?;
            println!("{}", path.display());
        }
    }

    Ok(())
}