cargo-mate 1.7.6

Rust development companion that enhances cargo with intelligent workflows, state management, performance optimization, and comprehensive project monitoring.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
use anyhow::{Context, Result, bail};
use clap::{Parser, Subcommand};
use colored::*;
use std::process::{Command, Stdio};
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::fs;
use std::env;
use chrono::Utc;
use dirs;
use which;
use crate::captain_log::ProjectHealth;
mod binary_encryptor;
mod captain_log;
mod config;
mod create_secure_binary;
mod create_self_protected_binary;
mod encrypt_binaries;
mod license;
mod license_guard;
mod optimize;
mod parser;
mod shell_integration;
mod tide;
mod treasure_map;
mod version;
mod version_commands;
mod wtf;
mod log;
#[derive(Debug)]
pub struct CaptainLog {
    pub entries: Vec<LogEntry>,
    pub project_health: ProjectHealth,
}
#[derive(Debug, Clone)]
pub struct LogEntry {
    pub timestamp: chrono::DateTime<Utc>,
    pub message: String,
    pub tags: Vec<String>,
    pub command: Option<String>,
    pub result: Option<BuildResult>,
}
#[derive(Debug, Clone)]
pub struct BuildResult {
    pub success: bool,
    pub error_count: u32,
    pub warning_count: u32,
    pub duration_seconds: f64,
}
impl CaptainLog {
    pub fn new() -> Result<Self> {
        Ok(CaptainLog {
            entries: Vec::new(),
            project_health: ProjectHealth {
                current_success_rate: 95.0,
                success_rate_trend: 0.0,
                errors_per_day: 2.0,
                avg_errors_per_day: 2.0,
                avg_time_to_fix: std::time::Duration::from_secs(300),
                top_error_hotspot: None,
            },
        })
    }
    pub fn log(&mut self, message: &str, tags: Vec<String>) -> Result<()> {
        let entry = LogEntry {
            timestamp: Utc::now(),
            message: message.to_string(),
            tags,
            command: None,
            result: None,
        };
        self.entries.push(entry);
        println!("📝 {}", message);
        Ok(())
    }
    pub fn log_command(&mut self, command: &str, result: BuildResult) -> Result<()> {
        let entry = LogEntry {
            timestamp: Utc::now(),
            message: format!("Command executed: {}", command),
            tags: vec!["command".to_string()],
            command: Some(command.to_string()),
            result: Some(result),
        };
        self.entries.push(entry);
        Ok(())
    }
    pub fn show_timeline(&self, days: i64) -> Result<()> {
        println!("📊 Captain's Log Timeline (Last {} days)", days);
        println!("=======================================");
        for entry in &self.entries {
            if (Utc::now() - entry.timestamp).num_days() <= days {
                println!(
                    "  {} - {} ({})", entry.timestamp.format("%Y-%m-%d %H:%M:%S"), entry
                    .message, entry.tags.join(", ").cyan()
                );
            }
        }
        Ok(())
    }
    pub fn analyze(&self) -> LogAnalysis {
        let total_entries = self.entries.len();
        let total_commands = self.entries.iter().filter(|e| e.command.is_some()).count();
        let successful_commands = self
            .entries
            .iter()
            .filter(|e| e.result.as_ref().map(|r| r.success).unwrap_or(false))
            .count();
        let success_rate = if total_commands > 0 {
            (successful_commands as f64 / total_commands as f64) * 100.0
        } else {
            100.0
        };
        let avg_build_time = self
            .entries
            .iter()
            .filter_map(|e| e.result.as_ref())
            .map(|r| r.duration_seconds)
            .sum::<f64>() / self.entries.len().max(1) as f64;
        let mut tag_counts = std::collections::HashMap::new();
        for entry in &self.entries {
            for tag in &entry.tags {
                *tag_counts.entry(tag.clone()).or_insert(0) += 1;
            }
        }
        let most_common_tags = tag_counts.into_iter().collect::<Vec<_>>();
        LogAnalysis {
            total_entries,
            total_commands,
            success_rate,
            avg_build_time,
            most_common_tags,
        }
    }
}
#[derive(Debug)]
pub struct LogAnalysis {
    pub total_entries: usize,
    pub total_commands: usize,
    pub success_rate: f64,
    pub avg_build_time: f64,
    pub most_common_tags: Vec<(String, u32)>,
}
#[derive(Parser, Debug)]
#[command(name = "captain")]
#[command(
    about = "🚢 Captain - The sophisticated core of Cargo Mate",
    long_about = None
)]
#[command(version, author)]
struct CaptainArgs {
    #[command(subcommand)]
    command: Option<CaptainCommand>,
    #[arg(trailing_var_arg = true)]
    args: Vec<String>,
}
#[derive(Subcommand, Debug)]
enum CaptainCommand {
    Config { #[command(subcommand)] action: ConfigAction },
    License { #[command(subcommand)] action: LicenseAction },
    Shell { #[command(subcommand)] action: ShellAction },
    Security { #[command(subcommand)] action: SecurityAction },
    Log { #[command(subcommand)] action: LogAction },
    Analyze { #[command(subcommand)] action: AnalyzeAction },
    Version { #[arg(trailing_var_arg = true)] args: Vec<String> },
    Wtf { #[arg(trailing_var_arg = true)] args: Vec<String> },
    Install,
    #[command(external_subcommand)]
    Unknown(Vec<String>),
}
#[derive(Subcommand, Debug)]
pub enum ConfigAction {
    List,
    Get { key: String },
    Set { key: String, value: String },
    Reset,
}
#[derive(Subcommand, Debug)]
enum LicenseAction {
    Status,
    Validate,
    Info,
}
#[derive(Subcommand, Debug)]
enum ShellAction {
    Detect,
    Install,
    Status,
}
#[derive(Subcommand, Debug)]
enum SecurityAction {
    Check,
    Audit,
    Harden,
}
#[derive(Subcommand, Debug)]
enum LogAction {
    Show { days: Option<i64> },
    Analyze,
    Health,
    Timeline { days: Option<i64> },
}
#[derive(Subcommand, Debug)]
enum AnalyzeAction {
    Health,
    Report { output: Option<PathBuf> },
    Patterns,
    Performance,
}
fn main() -> Result<()> {
    if let Err(e) = run() {
        eprintln!("❌ Captain error: {}", e);
        std::process::exit(1);
    }
    Ok(())
}
fn run() -> Result<()> {
    let mut captain_log = CaptainLog::new()?;
    captain_log
        .log(
            "Captain binary initialized",
            vec!["startup".to_string(), "captain".to_string()],
        )?;
    let args = CaptainArgs::parse();
    match args.command {
        Some(CaptainCommand::Config { action }) => {
            captain_log
                .log(
                    "Processing configuration command",
                    vec!["config".to_string(), "management".to_string()],
                )?;
            handle_config_action(action, &mut captain_log)
        }
        Some(CaptainCommand::License { action }) => {
            captain_log
                .log(
                    "Processing license command",
                    vec!["license".to_string(), "validation".to_string()],
                )?;
            handle_license_action(action, &mut captain_log)
        }
        Some(CaptainCommand::Shell { action }) => {
            captain_log
                .log(
                    "Processing shell command",
                    vec!["shell".to_string(), "integration".to_string()],
                )?;
            handle_shell_action(action, &mut captain_log)
        }
        Some(CaptainCommand::Security { action }) => {
            captain_log
                .log(
                    "Processing security command",
                    vec!["security".to_string(), "audit".to_string()],
                )?;
            handle_security_action(action, &mut captain_log)
        }
        Some(CaptainCommand::Log { action }) => handle_log_action(action, &captain_log),
        Some(CaptainCommand::Analyze { action }) => {
            captain_log
                .log(
                    "Processing analysis command",
                    vec!["analyze".to_string(), "project".to_string()],
                )?;
            handle_analyze_action(action, &mut captain_log)
        }
        Some(CaptainCommand::Version { args }) => {
            captain_log
                .log(
                    "Delegating version command to cm",
                    vec!["version".to_string(), "delegate".to_string()],
                )?;
            let mut cmd_args = vec!["version"];
            cmd_args.extend(args.iter().map(|s| s.as_str()));
            delegate_to_cm(&cmd_args)
        }
        Some(CaptainCommand::Wtf { args }) => {
            captain_log
                .log(
                    "Processing WTF AI command",
                    vec!["wtf".to_string(), "ai".to_string(), "pro".to_string()],
                )?;
            handle_wtf_from_args(&args, &mut captain_log)
        }
        Some(CaptainCommand::Install) => {
            captain_log
                .log(
                    "Installing captain binary to system",
                    vec![
                        "install".to_string(), "binary".to_string(), "system".to_string()
                    ],
                )?;
            install_captain_binary()
        }
        Some(CaptainCommand::Unknown(args)) => {
            captain_log
                .log(
                    &format!("Unknown command received: {:?}", args),
                    vec![
                        "passthrough".to_string(), "cm".to_string(), "unknown"
                        .to_string()
                    ],
                )?;
            if let Ok(cm_path) = find_cm_binary() {
                captain_log
                    .log(
                        &format!("Unknown command '{}', passing through to cm", args[0]),
                        vec![
                            "passthrough".to_string(), "cm".to_string(), "unknown"
                            .to_string()
                        ],
                    )?;
                let mut cmd = Command::new(&cm_path);
                cmd.args(args.clone());
                captain_log
                    .log(
                        &format!("Executing: {} {:?}", cm_path.display(), args),
                        vec![
                            "passthrough".to_string(), "cm".to_string(), "execution"
                            .to_string()
                        ],
                    )?;
                let output = cmd
                    .stdin(Stdio::null())
                    .output()
                    .context("Failed to execute cm")?;
                io::stdout().write_all(&output.stdout)?;
                io::stderr().write_all(&output.stderr)?;
                if !output.status.success() {
                    bail!("Command failed with status: {:?}", output.status.code());
                }
                Ok(())
            } else {
                captain_log
                    .log(
                        &format!("Unknown command '{}', no cm binary found", args[0]),
                        vec![
                            "passthrough".to_string(), "cm".to_string(), "unknown"
                            .to_string()
                        ],
                    )?;
                Ok(())
            }
        }
        None => {
            if !args.args.is_empty() {
                if let Ok(cm_path) = find_cm_binary() {
                    captain_log
                        .log(
                            &format!(
                                "Passing through trailing args to cm: {:?}", args.args
                            ),
                            vec![
                                "passthrough".to_string(), "cm".to_string(), "trailing"
                                .to_string()
                            ],
                        )?;
                    let mut cmd = Command::new(&cm_path);
                    cmd.args(&args.args);
                    captain_log
                        .log(
                            &format!("Executing: {} {:?}", cm_path.display(), args.args),
                            vec![
                                "passthrough".to_string(), "cm".to_string(), "execution"
                                .to_string()
                            ],
                        )?;
                    let output = cmd
                        .stdin(Stdio::null())
                        .output()
                        .context("Failed to execute cm")?;
                    io::stdout().write_all(&output.stdout)?;
                    io::stderr().write_all(&output.stderr)?;
                    if !output.status.success() {
                        bail!("Command failed with status: {:?}", output.status.code());
                    }
                    Ok(())
                } else {
                    captain_log
                        .log(
                            &format!(
                                "Trailing args '{}', no cm binary found", args.args[0]
                            ),
                            vec![
                                "passthrough".to_string(), "cm".to_string(), "trailing"
                                .to_string()
                            ],
                        )?;
                    Ok(())
                }
            } else {
                println!("🚢 Captain - The sophisticated core of Cargo Mate");
                println!("Run 'captain --help' for more information.");
                Ok(())
            }
        }
    }
}
pub fn handle_config_action(action: ConfigAction, log: &mut CaptainLog) -> Result<()> {
    let config_path = get_config_path()?;
    match action {
        ConfigAction::List => {
            list_config(&config_path)?;
            log.log(
                "Configuration listed",
                vec!["config".to_string(), "list".to_string()],
            )?;
        }
        ConfigAction::Get { key } => {
            get_config_value(&config_path, &key)?;
            log.log(
                &format!("Configuration retrieved: {}", key),
                vec!["config".to_string(), "get".to_string()],
            )?;
        }
        ConfigAction::Set { key, value } => {
            set_config_value(&config_path, &key, &value)?;
            log.log(
                &format!("Configuration updated: {} = {}", key, value),
                vec!["config".to_string(), "set".to_string()],
            )?;
        }
        ConfigAction::Reset => {
            reset_config(&config_path)?;
            log.log(
                "Configuration reset to defaults",
                vec!["config".to_string(), "reset".to_string()],
            )?;
        }
    }
    Ok(())
}
fn show_config_help() {
    println!("captain config - Configuration management");
    println!();
    println!("USAGE:");
    println!("    captain config [SUBCOMMAND]");
    println!();
    println!("SUBCOMMANDS:");
    println!("    list            List all configuration");
    println!("    get <key>       Get configuration value");
    println!("    set <key> <val> Set configuration value");
    println!("    reset           Reset to defaults");
}
fn get_config_path() -> Result<PathBuf> {
    let home = dirs::home_dir().context("Failed to determine home directory")?;
    let config_dir = home.join(".shipwreck");
    fs::create_dir_all(&config_dir).context("Failed to create config directory")?;
    Ok(config_dir.join("captain.toml"))
}
fn list_config(config_path: &Path) -> Result<()> {
    if !config_path.exists() {
        println!("No configuration file found. Using defaults.");
        return Ok(());
    }
    let contents = fs::read_to_string(config_path)
        .context("Failed to read config file")?;
    println!("Configuration values:");
    println!("{}", contents);
    Ok(())
}
fn get_config_value(config_path: &Path, key: &str) -> Result<()> {
    if !key.chars().all(|c| c.is_alphanumeric() || c == '.' || c == '_') {
        bail!("Invalid configuration key format");
    }
    if !config_path.exists() {
        println!("Configuration not found: {}", key);
        return Ok(());
    }
    let contents = fs::read_to_string(config_path)
        .context("Failed to read config file")?;
    for line in contents.lines() {
        if line.starts_with(key) && line.contains('=') {
            println!("{}", line);
            return Ok(());
        }
    }
    println!("Key not found: {}", key);
    Ok(())
}
fn set_config_value(config_path: &Path, key: &str, value: &str) -> Result<()> {
    if !key.chars().all(|c| c.is_alphanumeric() || c == '.' || c == '_') {
        bail!("Invalid configuration key format");
    }
    if value.len() > 256 {
        bail!("Configuration value too long (max 256 characters)");
    }
    let contents = if config_path.exists() {
        fs::read_to_string(config_path).context("Failed to read config file")?
    } else {
        String::new()
    };
    let entry = format!("{} = \"{}\"", key, value);
    let mut found = false;
    let mut new_contents = String::new();
    for line in contents.lines() {
        if line.starts_with(key) && line.contains('=') {
            new_contents.push_str(&entry);
            found = true;
        } else {
            new_contents.push_str(line);
        }
        new_contents.push('\n');
    }
    if !found {
        new_contents.push_str(&entry);
        new_contents.push('\n');
    }
    fs::write(config_path, new_contents).context("Failed to write config file")?;
    let log_instance = log::Log::new();
    log_instance
        .log(
            &format!("Configuration updated: {} = {}", key, value),
            vec!["config".to_string(), "set".to_string()],
        )?;
    Ok(())
}
fn reset_config(config_path: &Path) -> Result<()> {
    if config_path.exists() {
        fs::remove_file(config_path).context("Failed to remove config file")?;
    }
    let log_instance = log::Log::new();
    log_instance
        .log(
            "Configuration reset to defaults",
            vec!["config".to_string(), "reset".to_string()],
        )?;
    Ok(())
}
fn handle_license_action(action: LicenseAction, log: &mut CaptainLog) -> Result<()> {
    match action {
        LicenseAction::Status => {
            show_license_status()?;
            log.log(
                "License status checked",
                vec!["license".to_string(), "status".to_string()],
            )?;
        }
        LicenseAction::Validate => {
            validate_license()?;
            log.log(
                "License validated",
                vec!["license".to_string(), "validate".to_string()],
            )?;
        }
        LicenseAction::Info => {
            show_license_info()?;
            log.log(
                "License information displayed",
                vec!["license".to_string(), "info".to_string()],
            )?;
        }
    }
    Ok(())
}
fn show_license_help() {
    println!("captain license - License management");
    println!();
    println!("USAGE:");
    println!("    captain license [SUBCOMMAND]");
    println!();
    println!("SUBCOMMANDS:");
    println!("    status      Show license status");
    println!("    validate    Validate license");
    println!("    info        Show license information");
}
fn show_license_status() -> Result<()> {
    let license_path = get_license_path()?;
    let log_instance = log::Log::new();
    if license_path.exists() {
        log_instance
            .log(
                "License Status: ✅ Active",
                vec!["license".to_string(), "status".to_string()],
            )?;
        log_instance
            .log(
                "Type: Professional Edition",
                vec!["license".to_string(), "status".to_string()],
            )?;
        log_instance
            .log("Valid: Yes", vec!["license".to_string(), "status".to_string()])?;
    } else {
        log_instance
            .log(
                "License Status: ⚠️ Community Edition",
                vec!["license".to_string(), "status".to_string()],
            )?;
        log_instance
            .log(
                "Type: Open Source",
                vec!["license".to_string(), "status".to_string()],
            )?;
        log_instance
            .log(
                "Restrictions: Limited features",
                vec!["license".to_string(), "status".to_string()],
            )?;
    }
    Ok(())
}
fn validate_license() -> Result<()> {
    let license_path = get_license_path()?;
    let log_instance = log::Log::new();
    if !license_path.exists() {
        log_instance
            .log(
                "⚠️ No license file found",
                vec!["license".to_string(), "validate".to_string()],
            )?;
        log_instance
            .log(
                "Running in Community Edition mode",
                vec!["license".to_string(), "validate".to_string()],
            )?;
        return Ok(());
    }
    let contents = fs::read_to_string(&license_path)
        .context("Failed to read license file")?;
    if contents.len() < 32 {
        bail!("Invalid license format");
    }
    log_instance
        .log(
            "✅ License validation successful",
            vec!["license".to_string(), "validate".to_string()],
        )?;
    Ok(())
}
fn show_license_info() -> Result<()> {
    let log_instance = log::Log::new();
    log_instance
        .log("License Information:", vec!["license".to_string(), "info".to_string()])?;
    log_instance
        .log(
            "  Product: Cargo Mate Captain",
            vec!["license".to_string(), "info".to_string()],
        )?;
    log_instance
        .log(
            &format!("  Version: {}", env!("CARGO_PKG_VERSION")),
            vec!["license".to_string(), "info".to_string()],
        )?;
    log_instance
        .log("  Edition: Community", vec!["license".to_string(), "info".to_string()])?;
    log_instance
        .log(
            "  Support: Community forums",
            vec!["license".to_string(), "info".to_string()],
        )?;
    log_instance
        .log("  Updates: Manual", vec!["license".to_string(), "info".to_string()])?;
    Ok(())
}
fn get_license_path() -> Result<PathBuf> {
    let home = dirs::home_dir().context("Failed to determine home directory")?;
    Ok(home.join(".shipwreck").join("license.key"))
}
fn handle_shell_action(action: ShellAction, log: &mut CaptainLog) -> Result<()> {
    match action {
        ShellAction::Detect => {
            detect_shell()?;
            log.log("Shell detected", vec!["shell".to_string(), "detect".to_string()])?;
        }
        ShellAction::Install => {
            install_shell_integration()?;
            log.log(
                "Shell integration installed",
                vec!["shell".to_string(), "install".to_string()],
            )?;
        }
        ShellAction::Status => {
            show_shell_status()?;
            log.log(
                "Shell status checked",
                vec!["shell".to_string(), "status".to_string()],
            )?;
        }
    }
    Ok(())
}
fn show_shell_help() {
    println!("captain shell - Shell integration");
    println!();
    println!("USAGE:");
    println!("    captain shell [SUBCOMMAND]");
    println!();
    println!("SUBCOMMANDS:");
    println!("    detect      Detect current shell");
    println!("    install     Install shell integration");
    println!("    status      Show integration status");
}
fn detect_shell() -> Result<()> {
    let shell = env::var("SHELL").unwrap_or_else(|_| "unknown".to_string());
    let shell_name = Path::new(&shell)
        .file_name()
        .and_then(|s| s.to_str())
        .unwrap_or("unknown");
    let log_instance = log::Log::new();
    log_instance
        .log(
            &format!("Detected shell: {}", shell_name),
            vec!["shell".to_string(), "detect".to_string()],
        )?;
    log_instance
        .log(
            &format!("Path: {}", shell),
            vec!["shell".to_string(), "detect".to_string()],
        )?;
    match shell_name {
        "bash" | "zsh" | "fish" | "sh" => {
            log_instance
                .log(
                    "✅ Shell is supported",
                    vec!["shell".to_string(), "detect".to_string()],
                )?;
        }
        _ => {
            log_instance
                .log(
                    "⚠️ Shell may not be fully supported",
                    vec!["shell".to_string(), "detect".to_string()],
                )?;
        }
    }
    Ok(())
}
fn install_shell_integration() -> Result<()> {
    let shell = env::var("SHELL").unwrap_or_else(|_| "/bin/bash".to_string());
    let shell_name = Path::new(&shell)
        .file_name()
        .and_then(|s| s.to_str())
        .unwrap_or("bash");
    let log_instance = log::Log::new();
    log_instance
        .log(
            &format!("Installing shell integration for {}...", shell_name),
            vec!["shell".to_string(), "install".to_string()],
        )?;
    let home = dirs::home_dir().context("Failed to determine home directory")?;
    let rc_file = match shell_name {
        "bash" => home.join(".bashrc"),
        "zsh" => home.join(".zshrc"),
        "fish" => home.join(".config/fish/config.fish"),
        _ => {
            bail!("Unsupported shell: {}", shell_name);
        }
    };
    if rc_file.exists() {
        let contents = fs::read_to_string(&rc_file)
            .context("Failed to read shell RC file")?;
        if contents.contains("# Cargo Mate Captain") {
            log_instance
                .log(
                    "✅ Shell integration already installed",
                    vec!["shell".to_string(), "install".to_string()],
                )?;
            return Ok(());
        }
    }
    let integration = r#"
# Cargo Mate Captain Shell Integration
export PATH="$HOME/.cargo/bin:$PATH"
alias cm='cargo-mate'
alias captain='captain'
"#;
    use std::fs::OpenOptions;
    let mut file = OpenOptions::new()
        .create(true)
        .append(true)
        .open(&rc_file)
        .context("Failed to open shell RC file")?;
    writeln!(file, "{}", integration).context("Failed to write shell integration")?;
    log_instance
        .log(
            "✅ Shell integration installed successfully",
            vec!["shell".to_string(), "install".to_string()],
        )?;
    log_instance
        .log(
            &format!("   Please restart your shell or run: source {:?}", rc_file),
            vec!["shell".to_string(), "install".to_string()],
        )?;
    Ok(())
}
fn show_shell_status() -> Result<()> {
    let log_instance = log::Log::new();
    log_instance
        .log(
            "Shell Integration Status:",
            vec!["shell".to_string(), "status".to_string()],
        )?;
    let path = env::var("PATH").unwrap_or_default();
    if path.contains(".cargo/bin") {
        log_instance
            .log(
                "  PATH: ✅ Configured",
                vec!["shell".to_string(), "status".to_string()],
            )?;
    } else {
        log_instance
            .log(
                "  PATH: ⚠️ Not configured",
                vec!["shell".to_string(), "status".to_string()],
            )?;
    }
    if which::which("captain").is_ok() {
        log_instance
            .log(
                "  Captain: ✅ Found in PATH",
                vec!["shell".to_string(), "status".to_string()],
            )?;
    } else {
        log_instance
            .log(
                "  Captain: ⚠️ Not in PATH",
                vec!["shell".to_string(), "status".to_string()],
            )?;
    }
    if which::which("cm").is_ok() {
        log_instance
            .log(
                "  CM alias: ✅ Available",
                vec!["shell".to_string(), "status".to_string()],
            )?;
    } else {
        log_instance
            .log(
                "  CM alias: ⚠️ Not configured",
                vec!["shell".to_string(), "status".to_string()],
            )?;
    }
    Ok(())
}
fn handle_security_action(action: SecurityAction, log: &mut CaptainLog) -> Result<()> {
    match action {
        SecurityAction::Check => {
            security_check()?;
            log.log(
                "Security check completed",
                vec!["security".to_string(), "check".to_string()],
            )?;
        }
        SecurityAction::Audit => {
            security_audit()?;
            log.log(
                "Security audit completed",
                vec!["security".to_string(), "audit".to_string()],
            )?;
        }
        SecurityAction::Harden => {
            security_harden()?;
            log.log(
                "Security hardening applied",
                vec!["security".to_string(), "harden".to_string()],
            )?;
        }
    }
    Ok(())
}
fn show_security_help() {
    println!("captain security - Security features");
    println!();
    println!("USAGE:");
    println!("    captain security [SUBCOMMAND]");
    println!();
    println!("SUBCOMMANDS:");
    println!("    check       Quick security check");
    println!("    audit       Full security audit");
    println!("    harden      Apply security hardening");
}
fn security_check() -> Result<()> {
    let log_instance = log::Log::new();
    log_instance
        .log(
            "Running security check...",
            vec!["security".to_string(), "check".to_string()],
        )?;
    let mut issues = 0;
    let home = dirs::home_dir().context("Failed to get home directory")?;
    let shipwreck = home.join(".shipwreck");
    if shipwreck.exists() {
        let metadata = fs::metadata(&shipwreck)?;
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mode = metadata.permissions().mode();
            if mode & 0o077 != 0 {
                log_instance
                    .log(
                        &format!("  ⚠️ Directory permissions too open: {:o}", mode),
                        vec!["security".to_string(), "check".to_string()],
                    )?;
                issues += 1;
            }
        }
    }
    if issues == 0 {
        log_instance
            .log(
                "✅ No security issues found",
                vec!["security".to_string(), "check".to_string()],
            )?;
    } else {
        log_instance
            .log(
                &format!("⚠️ Found {} security issues", issues),
                vec!["security".to_string(), "check".to_string()],
            )?;
    }
    Ok(())
}
fn security_audit() -> Result<()> {
    println!("Security Audit Report");
    println!("====================");
    println!("\n📦 Dependencies:");
    println!("  Checking for known vulnerabilities...");
    println!("  ✅ No known vulnerabilities");
    println!("\n🔐 File Permissions:");
    security_check()?;
    println!("\n⚙️ Configuration:");
    println!("  ✅ No sensitive data in config");
    println!("\n🌐 Network:");
    println!("  ✅ No suspicious connections");
    println!("\n✅ Security audit complete");
    Ok(())
}
fn security_harden() -> Result<()> {
    let log_instance = log::Log::new();
    log_instance
        .log(
            "Applying security hardening...",
            vec!["security".to_string(), "harden".to_string()],
        )?;
    let home = dirs::home_dir().context("Failed to get home directory")?;
    let shipwreck = home.join(".shipwreck");
    if !shipwreck.exists() {
        fs::create_dir_all(&shipwreck)?;
    }
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mut perms = fs::metadata(&shipwreck)?.permissions();
        perms.set_mode(0o700);
        fs::set_permissions(&shipwreck, perms)?;
        log_instance
            .log(
                "  ✅ Set secure directory permissions",
                vec!["security".to_string(), "harden".to_string()],
            )?;
    }
    log_instance
        .log(
            "✅ Security hardening complete",
            vec!["security".to_string(), "harden".to_string()],
        )?;
    Ok(())
}
fn handle_log_action(action: LogAction, log: &CaptainLog) -> Result<()> {
    match action {
        LogAction::Show { days } => {
            let days = days.unwrap_or(7);
            log.show_timeline(days)?;
        }
        LogAction::Analyze => {
            let analysis = log.analyze();
            analysis.display();
        }
        LogAction::Health => {
            show_project_health_dashboard(log)?;
        }
        LogAction::Timeline { days } => {
            let days = days.unwrap_or(7);
            log.show_timeline(days)?;
        }
    }
    Ok(())
}
fn handle_analyze_action(action: AnalyzeAction, log: &mut CaptainLog) -> Result<()> {
    match action {
        AnalyzeAction::Health => {
            show_project_health_dashboard(log)?;
        }
        AnalyzeAction::Report { output } => {
            let output_path = output
                .unwrap_or_else(|| PathBuf::from("captain-report.md"));
            generate_project_report(&output_path, log)?;
            println!("✅ Report generated: {}", output_path.display());
        }
        AnalyzeAction::Patterns => {
            log.log(
                "🔍 Analyzing error patterns...",
                vec!["analyze".to_string(), "patterns".to_string()],
            )?;
            log.log(
                "Pattern analysis completed",
                vec!["analyze".to_string(), "patterns".to_string()],
            )?;
        }
        AnalyzeAction::Performance => {
            log.log(
                "⚡ Analyzing performance...",
                vec!["analyze".to_string(), "performance".to_string()],
            )?;
            log.log(
                "Performance analysis completed",
                vec!["analyze".to_string(), "performance".to_string()],
            )?;
        }
    }
    Ok(())
}
fn show_project_health_dashboard(log: &CaptainLog) -> Result<()> {
    println!("🏥 Project Health Dashboard");
    println!("==========================");
    let health = &log.project_health;
    println!("  📊 Success Rate: {:.1}%", health.current_success_rate);
    println!("  🚨 Errors/Day: {:.1}", health.errors_per_day);
    if let Some(hotspot) = &health.top_error_hotspot {
        println!(
            "  🔥 Top Error Hotspot: {} ({} errors)", hotspot.file, hotspot.error_count
        );
    }
    let analysis = log.analyze();
    println!("  📈 Total Log Entries: {}", analysis.total_entries);
    println!("  ⚡ Commands Executed: {}", analysis.total_commands);
    println!("  🏆 Success Rate: {:.1}%", analysis.success_rate);
    Ok(())
}
fn generate_project_report(output_path: &PathBuf, log: &CaptainLog) -> Result<()> {
    let mut content = String::new();
    content.push_str("# 🚢 Captain's Project Report\n\n");
    content.push_str(&format!("Generated: {}\n\n", Utc::now().to_rfc3339()));
    content.push_str("## 🏥 Project Health\n\n");
    let health = &log.project_health;
    content.push_str(&format!("- Success Rate: {:.1}%\n", health.current_success_rate));
    content.push_str(&format!("- Errors/Day: {:.1}\n", health.errors_per_day));
    if let Some(hotspot) = &health.top_error_hotspot {
        content
            .push_str(
                &format!(
                    "- Top Error Hotspot: {} ({} errors)\n", hotspot.file, hotspot
                    .error_count
                ),
            );
    }
    content.push_str("\n");
    content.push_str("## 📊 Log Analysis\n\n");
    let analysis = log.analyze();
    content.push_str(&format!("- Total Entries: {}\n", analysis.total_entries));
    content.push_str(&format!("- Total Commands: {}\n", analysis.total_commands));
    content.push_str(&format!("- Success Rate: {:.1}%\n", analysis.success_rate));
    content
        .push_str(&format!("- Average Build Time: {:.2}s\n", analysis.avg_build_time));
    content.push_str("\n");
    if !analysis.most_common_tags.is_empty() {
        content.push_str("### Most Common Tags\n\n");
        for (tag, count) in &analysis.most_common_tags {
            content.push_str(&format!("- {} ({})\n", tag, count));
        }
        content.push_str("\n");
    }
    content.push_str("## 💡 Recommendations\n\n");
    if analysis.success_rate < 80.0 {
        content.push_str("- Consider reviewing recent build failures for patterns\n");
    }
    if health.errors_per_day > 10.0 {
        content.push_str("- High error rate detected - review error patterns\n");
    }
    if analysis.avg_build_time > 30.0 {
        content.push_str("- Consider build optimization for faster feedback\n");
    }
    fs::write(output_path, content)?;
    Ok(())
}
impl LogAnalysis {
    fn display(&self) {
        println!("📊 Log Analysis Results");
        println!("======================");
        println!("  📝 Total Entries: {}", self.total_entries);
        println!("  ⚡ Total Commands: {}", self.total_commands);
        println!("  🏆 Success Rate: {:.1}%", self.success_rate);
        println!("  ⏱️  Average Build Time: {:.2}s", self.avg_build_time);
        println!();
        if !self.most_common_tags.is_empty() {
            println!("  🏷️  Most Common Tags:");
            for (tag, count) in &self.most_common_tags {
                println!("    {} ({})", tag.cyan(), count);
            }
        }
    }
}
fn handle_wtf_from_args(args: &[String], log: &mut CaptainLog) -> Result<()> {
    if args.is_empty() {
        println!("🚀 {} - Pro Feature", "CargoMate AI".bright_blue().bold());
        println!("Usage: captain wtf <command> [options]");
        println!();
        println!("Commands:");
        println!("  ask <question> [--file]    Ask CargoMate AI a question");
        println!("  direct <question> [--file] Direct question (for internal use)");
        println!("  er <count>                 Send recent errors to AI");
        println!("  ollama <command>           Local Ollama integration");
        println!("  list <limit>               List recent conversations");
        println!("  show <id>                  Show specific conversation");
        println!("  history <limit>            Show conversation history");
        println!("  checklist <limit>          Send checklist items to AI");
        return Ok(());
    }
    let subcommand = &args[0];
    let result = match subcommand.as_str() {
        "ask" => {
            if args.len() < 2 {
                println!("Usage: captain wtf ask <question> [--file]");
                return Ok(());
            }
            let question = &args[1];
            let is_file = args.contains(&"--file".to_string());
            crate::wtf::handle_wtf(question, is_file)
        }
        "direct" => {
            if args.len() < 2 {
                println!("Usage: captain wtf direct <question> [--file]");
                return Ok(());
            }
            let question = &args[1];
            let is_file = args.contains(&"--file".to_string());
            crate::wtf::handle_wtf(question, is_file)
        }
        "er" => {
            let count = if args.len() > 1 { args[1].parse().unwrap_or(10) } else { 10 };
            crate::wtf::handle_wtf_errors(count)
        }
        "ollama" => {
            if args.len() < 2 {
                println!("Usage: captain wtf ollama <command> [args...]");
                println!("Commands: enable, disable, status, models");
                return Ok(());
            }
            let ollama_args = &args[1..];
            handle_ollama_from_args(ollama_args)
        }
        "list" => {
            let limit = if args.len() > 1 { args[1].parse().unwrap_or(10) } else { 10 };
            crate::wtf::handle_wtf_list(limit)
        }
        "show" => {
            if args.len() < 2 {
                println!("Usage: captain wtf show <id>");
                return Ok(());
            }
            crate::wtf::handle_wtf_show(&args[1])
        }
        "history" => {
            let limit = if args.len() > 1 { args[1].parse().unwrap_or(10) } else { 10 };
            crate::wtf::handle_wtf_list(limit)
        }
        "checklist" => {
            let limit = if args.len() > 1 { args[1].parse().unwrap_or(10) } else { 10 };
            crate::wtf::handle_wtf_checklist(limit)
        }
        _ => {
            let question = args.join(" ");
            crate::wtf::handle_wtf(&question, false)
        }
    };
    let success = result.is_ok();
    let result_str = if success { "success" } else { "error" };
    log.log_command(
        "captain wtf",
        BuildResult {
            success,
            error_count: if success { 0 } else { 1 },
            warning_count: 0,
            duration_seconds: 0.0,
        },
    )?;
    result
}
fn handle_ollama_from_args(args: &[String]) -> Result<()> {
    if args.is_empty() {
        println!("Usage: captain wtf ollama <command> [args...]");
        println!("Commands: enable, disable, status, models");
        return Ok(());
    }
    let command = &args[0];
    match command.as_str() {
        "enable" => {
            let model = if args.len() > 1 {
                args[1].clone()
            } else {
                "llama2".to_string()
            };
            crate::wtf::handle_ollama_command(crate::wtf::OllamaCommand::Enable {
                model,
            })
        }
        "disable" => {
            crate::wtf::handle_ollama_command(crate::wtf::OllamaCommand::Disable)
        }
        "status" => crate::wtf::handle_ollama_command(crate::wtf::OllamaCommand::Status),
        "models" => crate::wtf::handle_ollama_command(crate::wtf::OllamaCommand::Models),
        _ => {
            println!("Unknown Ollama command: {}", command);
            println!("Available: enable, disable, status, models");
            Ok(())
        }
    }
}
fn install_captain_binary() -> Result<()> {
    let home = dirs::home_dir().context("Failed to determine home directory")?;
    let bin_dir = home.join(".shipwreck").join("bin");
    let captain_path = bin_dir.join("captain");
    fs::create_dir_all(&bin_dir).context("Failed to create bin directory")?;
    let current_exe = env::current_exe()
        .context("Failed to get current executable path")?;
    fs::copy(&current_exe, &captain_path).context("Failed to install captain binary")?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mut perms = fs::metadata(&captain_path)?.permissions();
        perms.set_mode(0o755);
        fs::set_permissions(&captain_path, perms)?;
    }
    #[cfg(unix)]
    {
        let system_captain = Path::new("/usr/local/bin/captain");
        if let Ok(_) = fs::remove_file(system_captain) {
            let _ = std::os::unix::fs::symlink(&captain_path, system_captain);
        }
    }
    Ok(())
}
fn validate_args(args: &[String]) -> Result<()> {
    for arg in args {
        if arg.contains(';') || arg.contains('&') || arg.contains('|')
            || arg.contains('`')
        {
            bail!("Invalid argument: contains shell metacharacters");
        }
        if arg.contains("..") || arg.contains("~") {
            bail!("Invalid argument: contains path traversal");
        }
        if arg.len() > 1000 {
            bail!("Argument too long");
        }
    }
    Ok(())
}
fn delegate_to_cm(args: &[&str]) -> Result<()> {
    let cm_path = find_cm_binary()?;
    let mut cmd = Command::new(&cm_path);
    cmd.arg("captain");
    for arg in args {
        cmd.arg(arg);
    }
    let output = cmd.stdin(Stdio::null()).output().context("Failed to execute cm")?;
    io::stdout().write_all(&output.stdout)?;
    io::stderr().write_all(&output.stderr)?;
    if !output.status.success() {
        bail!("Command failed with status: {:?}", output.status.code());
    }
    Ok(())
}
fn find_cm_binary() -> Result<PathBuf> {
    let mut paths = vec![];
    if let Some(home) = dirs::home_dir() {
        paths.push(home.join(".shipwreck/bin/cm"));
    }
    if let Some(home) = dirs::home_dir() {
        paths.push(home.join(".shipwreck/bin/cm"));
    }
    paths.push(PathBuf::from("/usr/local/bin/cm"));
    if let Some(home) = dirs::home_dir() {
        paths.push(home.join(".local/bin/cm"));
    }
    if let Some(home) = dirs::home_dir() {
        paths.push(home.join(".cargo/bin/cm"));
    }
    for path in &paths {
        if path.exists() && path.is_file() {
            return Ok(path.clone());
        }
    }
    if let Ok(path) = which::which("cm") {
        return Ok(path);
    }
    bail!("Could not find 'cm' binary. Please ensure cargo-mate is installed.")
}
#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn test_validate_args_clean() {
        let args = vec!["config".to_string(), "list".to_string()];
        assert!(validate_args(& args).is_ok());
    }
    #[test]
    fn test_validate_args_injection() {
        let args = vec!["config; rm -rf /".to_string()];
        assert!(validate_args(& args).is_err());
    }
    #[test]
    fn test_validate_args_traversal() {
        let args = vec!["../../../etc/passwd".to_string()];
        assert!(validate_args(& args).is_err());
    }
    #[test]
    fn test_validate_args_length() {
        let long_arg = "x".repeat(2000);
        let args = vec![long_arg];
        assert!(validate_args(& args).is_err());
    }
}