cargo-forge 0.1.5

An interactive Rust project generator with templates and common features
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
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
use crate::{Config, Generator, ProjectConfig, ProjectType};
use anyhow::{anyhow, Ok, Result};
use colored::*;
use indicatif::{ProgressBar, ProgressStyle};
use inquire::{Confirm, MultiSelect, Select, Text};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::time::Duration;

/// Context for project creation containing all user inputs
#[derive(Debug, Clone, Serialize)]
pub struct ProjectContext {
    pub name: String,
    pub project_type: ProjectType,
    pub features: Vec<String>,
    pub author: Option<String>,
    pub description: Option<String>,
    pub license: Option<String>,
    pub edition: String,
    pub target: Option<String>,
    pub esp32_chip: Option<String>,
}

impl ProjectContext {
    /// Build template context for Tera
    pub fn build_template_context(&self) -> HashMap<String, serde_json::Value> {
        let mut context = HashMap::new();
        context.insert("project_name".to_string(), serde_json::json!(self.name));
        context.insert(
            "project_type".to_string(),
            serde_json::json!(self.project_type.to_string()),
        );
        context.insert("features".to_string(), serde_json::json!(self.features));

        if let Some(author) = &self.author {
            context.insert("author".to_string(), serde_json::json!(author));
        }
        if let Some(description) = &self.description {
            context.insert("description".to_string(), serde_json::json!(description));
        }
        if let Some(license) = &self.license {
            context.insert("license".to_string(), serde_json::json!(license));
        }

        if let Some(target) = &self.target {
            context.insert("target".to_string(), serde_json::json!(target));
        }

        if let Some(esp32_chip) = &self.esp32_chip {
            context.insert("esp32_chip".to_string(), serde_json::json!(esp32_chip));
        }

        context.insert("edition".to_string(), serde_json::json!(self.edition));
        context
    }

    /// Convert to ProjectConfig for generator
    pub fn to_project_config(&self) -> ProjectConfig {
        ProjectConfig {
            name: self.name.clone(),
            project_type: self.project_type.to_string(),
            author: self.author.clone().unwrap_or_else(|| "Unknown".to_string()),
            description: self.description.clone(),
            features: self.features.clone(),
            target: self.target.clone(),
            esp32_chip: self.esp32_chip.clone(),
        }
    }
}

/// Configuration structure for saving user preferences
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ForgeConfig {
    pub default_author: Option<String>,
    pub default_license: Option<String>,
    pub preferred_project_types: Vec<String>,
    pub default_features: HashMap<String, Vec<String>>,
    pub edition: Option<String>,
}

impl Default for ForgeConfig {
    fn default() -> Self {
        Self {
            default_author: None,
            default_license: Some("MIT".to_string()),
            preferred_project_types: vec!["cli-tool".to_string()],
            default_features: HashMap::new(),
            edition: Some("2021".to_string()),
        }
    }
}

impl ForgeConfig {
    /// Load configuration from file
    pub fn load() -> Result<Self> {
        let config_path = Self::config_path()?;
        if config_path.exists() {
            let content = fs::read_to_string(&config_path)?;
            let config: ForgeConfig = serde_json::from_str(&content)?;
            Ok(config)
        } else {
            Ok(Self::default())
        }
    }

    /// Save configuration to file
    pub fn save(&self) -> Result<()> {
        let config_path = Self::config_path()?;
        if let Some(parent) = config_path.parent() {
            fs::create_dir_all(parent)?;
        }
        let content = serde_json::to_string_pretty(self)?;
        fs::write(&config_path, content)?;
        Ok(())
    }

    /// Get the default configuration file path
    pub fn config_path() -> Result<PathBuf> {
        let config_dir =
            dirs::config_dir().ok_or_else(|| anyhow!("Could not find config directory"))?;

        Ok(config_dir.join("cargo-forge").join("config.json"))
    }

    /// Load configuration from custom path
    pub fn load_from<P: AsRef<Path>>(path: P) -> Result<Self> {
        let content = fs::read_to_string(path)?;
        let config: ForgeConfig = serde_json::from_str(&content)?;
        Ok(config)
    }
}

pub struct Forge {
    base_path: PathBuf,
    config: Config,
}

impl Forge {
    pub fn new<P: AsRef<Path>>(base_path: P) -> Self {
        let config = Config::load_from_home().unwrap_or_else(|_| Config::new());
        Self {
            base_path: base_path.as_ref().to_path_buf(),
            config,
        }
    }

    pub fn run(&self) -> Result<()> {
        println!("{}", "Let's create your new Rust project.".bright_white());

        // Collect project context through interactive prompts
        let context = self.collect_project_context()?;

        // Create project with progress indicators
        self.create_project(context)?;

        Ok(())
    }

    pub fn run_interactive<R: Read>(&self, _reader: &mut R) -> Result<()> {
        // This method is kept for testing purposes
        // In production, use run() for the full interactive experience
        let mut input = String::new();
        _reader.read_to_string(&mut input)?;

        // Parse the input (simplified for testing)
        let lines: Vec<&str> = input.trim().split('\n').collect();
        if lines.len() >= 2 {
            let project_name = lines[1];
            let project_path = self.base_path.join(project_name);
            std::fs::create_dir_all(&project_path)?;
        }

        Ok(())
    }

    /// Collect all project information through interactive prompts
    fn collect_project_context(&self) -> Result<ProjectContext> {
        // Make a mutable copy of config for saving choices
        let mut config = self.config.clone();

        // Project name with validation
        let name = self.prompt_project_name()?;

        // Project type selection
        let project_type = self.prompt_project_type_interactive()?;

        let (target, esp32_chip) = if project_type == ProjectType::Embedded {
            self.prompt_embedded_target()?
        } else {
            (None, None)
        };

        // Feature selection based on project type
        let features = self.prompt_features(&project_type, target.clone())?;

        // Optional fields with config defaults
        let author = self.prompt_author_with_config(&mut config)?;
        let description = self.prompt_optional_field("Description", "A new Rust project")?;
        let license = self.prompt_license_with_config(&mut config)?;

        // Save config if any choices were remembered
        if config.remember_choices {
            let _ = config.save_to_home(); // Ignore errors for user experience
        }

        Ok(ProjectContext {
            name,
            project_type,
            features,
            author,
            description,
            license,
            edition: "2021".to_string(),
            target,
            esp32_chip,
        })
    }

    /// Prompt for Embedded Target selection
    fn prompt_embedded_target(&self) -> Result<(Option<String>, Option<String>)> {
        let targets = vec![
            "Cortex-M (ARM Microcontrollers)",
            "ESP32 (Espressif Microcontrollers)",
        ];

        let target = Select::new("Embedded Target : ", targets).prompt()?;

        if target.starts_with("ESP32") {
            let chip = crate::external_generators::interactive_esp32_chip_selection()?;
            Ok((Some("esp32".to_string()), Some(chip)))
        } else {
            Ok((None, None))
        }
    }

    /// Prompt for project name with validation
    fn prompt_project_name(&self) -> Result<String> {
        loop {
            let name = Text::new("Project name:")
                .with_placeholder("my-awesome-project")
                .with_help_message("Must be a valid Rust package name (lowercase, no spaces)")
                .prompt()?;

            // Validate manually
            if name.is_empty() {
                eprintln!("{}", "❌ Project name cannot be empty".red());
                continue;
            }
            if name.len() > 64 {
                eprintln!(
                    "{}",
                    "❌ Project name is too long (max 64 characters)".red()
                );
                continue;
            }
            if name != name.to_lowercase() {
                eprintln!("{}", "❌ Project name must be lowercase".red());
                continue;
            }
            if name.starts_with(|c: char| c.is_numeric()) {
                eprintln!("{}", "❌ Project name cannot start with a number".red());
                continue;
            }
            if !name
                .chars()
                .all(|c| c.is_alphanumeric() || c == '-' || c == '_')
            {
                eprintln!(
                    "{}",
                    "❌ Project name can only contain letters, numbers, '-', and '_'".red()
                );
                continue;
            }

            return Ok(name);
        }
    }

    /// Interactive project type selection
    fn prompt_project_type_interactive(&self) -> Result<ProjectType> {
        let options = vec![
            (
                "API Server",
                "RESTful API with Axum framework",
                ProjectType::ApiServer,
            ),
            (
                "CLI Tool",
                "Command-line application with Clap",
                ProjectType::CliTool,
            ),
            ("Library", "Reusable Rust library", ProjectType::Library),
            ("WASM App", "WebAssembly application", ProjectType::WasmApp),
            (
                "Game Engine",
                "Game development with Bevy",
                ProjectType::GameEngine,
            ),
            (
                "Embedded",
                "No-std embedded development",
                ProjectType::Embedded,
            ),
            (
                "Workspace",
                "Multi-crate workspace project",
                ProjectType::Workspace,
            ),
        ];

        let selection = Select::new(
            "Project type:",
            options
                .iter()
                .map(|(name, desc, _)| format!("{} - {}", name, desc))
                .collect(),
        )
        .with_help_message("Choose the type of project you want to create")
        .prompt()?;

        let project_type = options
            .iter()
            .find(|(name, desc, _)| format!("{} - {}", name, desc) == selection)
            .map(|(_, _, pt)| *pt)
            .ok_or_else(|| anyhow!("Invalid project type selection"))?;

        Ok(project_type)
    }

    /// Prompt for features based on project type
    fn prompt_features(
        &self,
        project_type: &ProjectType,
        target: Option<String>,
    ) -> Result<Vec<String>> {
        let available_features = match project_type {
            ProjectType::ApiServer => vec![
                ("axum", "Web framework", true),
                ("tokio", "Async runtime", true),
                ("serde", "Serialization", true),
                ("tower", "Middleware framework", true),
                ("sqlx", "SQL toolkit", false),
                ("jwt", "JWT authentication", false),
                ("cors", "CORS support", false),
                ("tracing", "Structured logging", false),
            ],
            ProjectType::CliTool => vec![
                ("clap", "CLI argument parsing", true),
                ("anyhow", "Error handling", true),
                ("env_logger", "Logging", true),
                ("tokio", "Async runtime", false),
                ("serde", "Serialization", false),
                ("indicatif", "Progress bars", false),
                ("colored", "Colored output", false),
            ],
            ProjectType::Library => vec![
                ("serde", "Serialization", false),
                ("thiserror", "Error types", false),
                ("async-trait", "Async traits", false),
                ("criterion", "Benchmarking", false),
            ],
            ProjectType::WasmApp => vec![
                ("wasm-bindgen", "JS bindings", true),
                ("web-sys", "Web APIs", true),
                ("js-sys", "JS APIs", true),
                ("wee_alloc", "Small allocator", false),
                ("console_error_panic_hook", "Better panic messages", false),
            ],
            ProjectType::GameEngine => vec![
                ("bevy", "Game engine framework", true),
                ("audio", "Audio support", false),
                ("networking", "Multiplayer networking", false),
                ("physics", "Physics simulation", false),
                ("ui", "UI framework", false),
            ],
            ProjectType::Embedded => {
                // Handle different Embedded Targets
                match target {
                    Some(target_str) if target_str == "esp32" => {
                        return Ok(Vec::new());
                    }
                    _ => {
                        // Show Cortex-M specific features
                        vec![
                            ("cortex-m", "ARM Cortex-M support", true),
                            ("cortex-m-rt", "Runtime support", true),
                            ("panic-halt", "Halt on panic", true),
                            ("panic-rtt", "RTT panic messages", false),
                            ("rtt", "Real-time transfer debugging", false),
                            ("semihosting", "Semihosting debug output", false),
                            ("stm32f4", "STM32F4 HAL", false),
                            ("stm32f1", "STM32F1 HAL", false),
                            ("rp2040", "Raspberry Pi Pico support", false),
                        ]
                    }
                }
            }
            ProjectType::Workspace => vec![
                ("tokio", "Async runtime", true),
                ("serde", "Serialization", true),
                ("anyhow", "Error handling", true),
                ("database", "Database support", false),
                ("web", "Web framework", false),
                ("clap", "CLI support", false),
                ("testing", "Advanced testing", false),
            ],
        };

        let _default_features: Vec<String> = available_features
            .iter()
            .filter(|(_, _, default)| *default)
            .map(|(name, _, _)| name.to_string())
            .collect();

        let options: Vec<String> = available_features
            .iter()
            .map(|(name, desc, _)| format!("{} - {}", name, desc))
            .collect();

        let default_indices: Vec<usize> = available_features
            .iter()
            .enumerate()
            .filter(|(_, (_, _, default))| *default)
            .map(|(i, _)| i)
            .collect();

        let selections = MultiSelect::new("Select features:", options)
            .with_default(&default_indices)
            .with_help_message("Space to select/deselect, Enter to confirm")
            .prompt()?;

        let features: Vec<String> = selections
            .iter()
            .filter_map(|selection| {
                available_features
                    .iter()
                    .find(|(name, desc, _)| format!("{} - {}", name, desc) == *selection)
                    .map(|(name, _, _)| name.to_string())
            })
            .collect();

        Ok(features)
    }

    /// Prompt for optional fields
    fn prompt_optional_field(&self, field_name: &str, placeholder: &str) -> Result<Option<String>> {
        let include = Confirm::new(&format!("Include {}?", field_name.to_lowercase()))
            .with_default(false)
            .prompt()?;

        if include {
            let value = Text::new(&format!("{}:", field_name))
                .with_placeholder(placeholder)
                .prompt()?;
            Ok(Some(value))
        } else {
            Ok(None)
        }
    }

    /// Prompt for license selection
    fn prompt_license(&self) -> Result<Option<String>> {
        let include_license = Confirm::new("Include license?")
            .with_default(true)
            .prompt()?;

        if include_license {
            let licenses = vec![
                "MIT",
                "Apache-2.0",
                "GPL-3.0",
                "BSD-3-Clause",
                "Unlicense",
                "Other",
            ];
            let license = Select::new("License:", licenses).prompt()?;

            if license == "Other" {
                let custom = Text::new("Custom license:")
                    .with_placeholder("AGPL-3.0")
                    .prompt()?;
                Ok(Some(custom))
            } else {
                Ok(Some(license.to_string()))
            }
        } else {
            Ok(None)
        }
    }

    /// Prompt for author with config defaults and remember choice functionality
    fn prompt_author_with_config(&self, config: &mut Config) -> Result<Option<String>> {
        // Use config default if available
        let default_author = config.default_author.as_deref();

        let include = if default_author.is_some() {
            // If we have a config default, ask if they want to use it or change it
            let use_default =
                Confirm::new(&format!("Use saved author '{}'?", default_author.unwrap()))
                    .with_default(true)
                    .prompt()?;

            if use_default {
                return Ok(config.default_author.clone());
            } else {
                true // They want to change it, so include author field
            }
        } else {
            // No default, ask if they want to include author
            Confirm::new("Include author?")
                .with_default(false)
                .prompt()?
        };

        if include {
            let author = Text::new("Author:")
                .with_placeholder("your-name")
                .prompt()?;

            // Ask if they want to remember this choice
            if config.remember_choices {
                let remember = Confirm::new("Remember this choice for future projects?")
                    .with_default(true)
                    .prompt()?;

                if remember {
                    config.remember_choice("author", &author);
                }
            }

            Ok(Some(author))
        } else {
            Ok(None)
        }
    }

    /// Prompt for license with config defaults and remember choice functionality
    fn prompt_license_with_config(&self, config: &mut Config) -> Result<Option<String>> {
        // Use config default if available
        let default_license = config.default_license.as_deref();

        let include_license = if default_license.is_some() {
            // If we have a config default, ask if they want to use it or change it
            let use_default = Confirm::new(&format!(
                "Use saved license '{}'?",
                default_license.unwrap()
            ))
            .with_default(true)
            .prompt()?;

            if use_default {
                return Ok(config.default_license.clone());
            } else {
                true // They want to change it, so include license selection
            }
        } else {
            // No default, ask if they want to include license
            Confirm::new("Include license?")
                .with_default(true)
                .prompt()?
        };

        if include_license {
            let licenses = vec![
                "MIT",
                "Apache-2.0",
                "GPL-3.0",
                "BSD-3-Clause",
                "Unlicense",
                "Other",
            ];
            let license = Select::new("License:", licenses).prompt()?;

            let final_license = if license == "Other" {
                let custom = Text::new("Custom license:")
                    .with_placeholder("AGPL-3.0")
                    .prompt()?;
                custom
            } else {
                license.to_string()
            };

            // Ask if they want to remember this choice
            if config.remember_choices {
                let remember = Confirm::new("Remember this choice for future projects?")
                    .with_default(true)
                    .prompt()?;

                if remember {
                    config.remember_choice("license", &final_license);
                }
            }

            Ok(Some(final_license))
        } else {
            Ok(None)
        }
    }

    /// Create the project with progress indicators
    fn create_project(&self, context: ProjectContext) -> Result<()> {
        // Special handling for ESP32 projects - don't create directory structure first
        if let Some(target) = &context.target {
            if target == "esp32" {
                println!("{}", "🔨 Creating your ESP32 project...".bright_yellow());

                let pb = ProgressBar::new(100);
                pb.set_style(
                    ProgressStyle::default_bar()
                        .template("{prefix:.bold.dim} {bar:40.cyan/blue} {percent}% {msg}")
                        .unwrap()
                        .progress_chars("█▉▊▋▌▍▎▏ "),
                );
                pb.set_prefix("Progress");

                pb.set_message("Generating ESP32 project files...");
                pb.set_position(40);

                // For ESP32, use parent directory and let esp-generate create the project directory
                let config = context.to_project_config();
                let generator = Generator::new();
                generator.generate(&config, &self.base_path)?; // Use base_path, not project_path

                pb.set_position(100);
                pb.finish_and_clear();

                println!(
                    "{} {}",
                    "".bright_green().bold(),
                    "ESP32 project created successfully!".bright_green()
                );
                self.show_next_steps(&context, false)?;
                return Ok(());
            }
        }

        // For non-ESP32 projects, continue with normal flow
        let project_path = self.base_path.join(&context.name);

        // Check if directory already exists (only for non-ESP32 projects)
        if project_path.exists() {
            return Err(anyhow!(
                "Project directory already exists: {}",
                context.name
            ));
        }

        println!("{}", "🔨 Creating your project...".bright_yellow());

        // Progress bar for project generation
        let pb = ProgressBar::new(100);
        pb.set_style(
            ProgressStyle::default_bar()
                .template("{prefix:.bold.dim} {bar:40.cyan/blue} {percent}% {msg}")
                .unwrap()
                .progress_chars("█▉▊▋▌▍▎▏ "),
        );
        pb.set_prefix("Progress");

        // Initialize project structure
        pb.set_message("Creating project directory...");
        std::fs::create_dir_all(&project_path)?;
        pb.set_position(20);
        std::thread::sleep(Duration::from_millis(100));

        // Generate project using generator
        pb.set_message("Generating project files...");
        let config = context.to_project_config();
        let generator = Generator::new();

        // Simulate progress during generation
        pb.set_position(40);
        std::thread::sleep(Duration::from_millis(100));

        generator.generate(&config, &project_path)?;
        pb.set_position(80);

        pb.set_message("Finalizing project setup...");
        std::thread::sleep(Duration::from_millis(100));
        pb.set_position(100);
        pb.finish_and_clear();

        // Enhanced success message
        println!(
            "{} {}",
            "".bright_green().bold(),
            "Project created successfully!".bright_green()
        );
        self.show_next_steps(&context, false)?;
        Ok(())
    }

    pub fn prompt_project_type<R: Read>(&self, reader: &mut R) -> Result<ProjectType> {
        let mut input = String::new();
        reader.read_to_string(&mut input)?;

        let choice = input.trim();
        match choice {
            "1" => Ok(ProjectType::ApiServer),
            "2" => Ok(ProjectType::CliTool),
            "3" => Ok(ProjectType::Library),
            "4" => Ok(ProjectType::WasmApp),
            _ => Err(anyhow!("Invalid project type selection")),
        }
    }

    pub fn validate_project_name(&self, name: &str) -> Result<()> {
        if name.is_empty() {
            return Err(anyhow!("Project name cannot be empty"));
        }

        // Check length
        if name.len() > 64 {
            return Err(anyhow!("Project name is too long (max 64 characters)"));
        }

        // Check for reserved names
        let reserved_names = [
            "test", "main", "build", "cargo", "rust", "src", "target", "bin", "lib",
        ];
        if reserved_names.contains(&name) {
            return Err(anyhow!("'{}' is a reserved name", name));
        }

        // Check for invalid characters and patterns
        if name.contains(' ') {
            return Err(anyhow!("Project name cannot contain spaces"));
        }

        if name.contains('/') || name.contains('\\') {
            return Err(anyhow!("Project name cannot contain slashes"));
        }

        // Must be lowercase
        if name != name.to_lowercase() {
            return Err(anyhow!("Project name must be lowercase"));
        }

        // Cannot start with a number
        if name.starts_with(|c: char| c.is_numeric()) {
            return Err(anyhow!("Project name cannot start with a number"));
        }

        // Cannot start or end with dash/underscore
        if name.starts_with('-') || name.starts_with('_') {
            return Err(anyhow!("Project name cannot start with '-' or '_'"));
        }

        if name.ends_with('-') || name.ends_with('_') {
            return Err(anyhow!("Project name cannot end with '-' or '_'"));
        }

        // Check for valid characters (alphanumeric, dash, underscore)
        if !name
            .chars()
            .all(|c| c.is_alphanumeric() || c == '-' || c == '_')
        {
            return Err(anyhow!(
                "Project name can only contain letters, numbers, '-', and '_'"
            ));
        }

        // Check for double dashes or underscores
        if name.contains("--") || name.contains("__") {
            return Err(anyhow!(
                "Project name cannot contain consecutive dashes or underscores"
            ));
        }

        Ok(())
    }

    /// Run in non-interactive mode with defaults
    pub fn run_non_interactive(
        &self,
        name: Option<String>,
        project_type: Option<String>,
        author: Option<String>,
        description: Option<String>,
        from_config: Option<PathBuf>,
    ) -> Result<()> {
        println!("{}", "🤖 Non-interactive mode".bright_blue().bold());

        let config = if let Some(config_path) = from_config {
            ForgeConfig::load_from(config_path)?
        } else {
            ForgeConfig::load()?
        };

        let project_name = name.unwrap_or_else(|| "my-project".to_string());

        // Validate project name before doing anything else
        self.validate_project_name(&project_name)?;

        let project_type_str = project_type.unwrap_or_else(|| "cli-tool".to_string());
        let project_type = self.parse_project_type(&project_type_str)?;

        let context = ProjectContext {
            name: project_name,
            project_type,
            features: config
                .default_features
                .get(&project_type_str)
                .cloned()
                .unwrap_or_default(),
            author: author.or(config.default_author),
            description,
            license: config.default_license,
            edition: config.edition.unwrap_or_else(|| "2021".to_string()),
            target: None,
            esp32_chip: None,
        };

        self.create_project(context)?;
        Ok(())
    }

    /// Run with command line arguments
    pub fn run_with_args(
        &self,
        name: Option<String>,
        project_type: Option<String>,
        author: Option<String>,
        description: Option<String>,
    ) -> Result<()> {
        let project_name = name.ok_or_else(|| anyhow!("Project name is required"))?;

        // Validate project name before doing anything else
        self.validate_project_name(&project_name)?;

        let project_type_str = project_type.ok_or_else(|| anyhow!("Project type is required"))?;
        let project_type = self.parse_project_type(&project_type_str)?;

        let context = ProjectContext {
            name: project_name,
            project_type,
            features: vec![], // Default features
            author,
            description,
            license: Some("MIT".to_string()),
            edition: "2021".to_string(),
            target: None,
            esp32_chip: None,
        };

        self.create_project(context)?;
        Ok(())
    }

    /// Run from configuration file
    pub fn run_from_config(
        &self,
        config_path: PathBuf,
        name: Option<String>,
        project_type: Option<String>,
        author: Option<String>,
        description: Option<String>,
    ) -> Result<()> {
        println!("{}", "📁 Loading configuration...".bright_cyan());

        let config = ForgeConfig::load_from(config_path)?;

        let project_name = name.unwrap_or_else(|| "my-project".to_string());

        // Validate project name before doing anything else
        self.validate_project_name(&project_name)?;

        let project_type_str = project_type
            .or_else(|| config.preferred_project_types.first().cloned())
            .unwrap_or_else(|| "cli-tool".to_string());
        let project_type = self.parse_project_type(&project_type_str)?;

        let context = ProjectContext {
            name: project_name,
            project_type,
            features: config
                .default_features
                .get(&project_type_str)
                .cloned()
                .unwrap_or_default(),
            author: author.or(config.default_author),
            description,
            license: config.default_license,
            edition: config.edition.unwrap_or_else(|| "2021".to_string()),
            target: None,
            esp32_chip: None,
        };

        self.create_project(context)?;
        Ok(())
    }

    /// Run in dry-run mode
    pub fn run_dry_run(
        &self,
        name: Option<String>,
        project_type: Option<String>,
        author: Option<String>,
        description: Option<String>,
        non_interactive: bool,
        from_config: Option<PathBuf>,
    ) -> Result<()> {
        if non_interactive {
            let config = if let Some(config_path) = from_config {
                ForgeConfig::load_from(config_path)?
            } else {
                ForgeConfig::load()?
            };

            let project_name = name.unwrap_or_else(|| "my-project".to_string());

            // Validate project name before doing anything else
            self.validate_project_name(&project_name)?;

            let project_type_str = project_type.unwrap_or_else(|| "cli-tool".to_string());
            let project_type = self.parse_project_type(&project_type_str)?;

            let context = ProjectContext {
                name: project_name,
                project_type,
                features: config
                    .default_features
                    .get(&project_type_str)
                    .cloned()
                    .unwrap_or_default(),
                author: author.or(config.default_author),
                description,
                license: config.default_license,
                edition: config.edition.unwrap_or_else(|| "2021".to_string()),
                target: None,
                esp32_chip: None,
            };

            self.preview_project(&context)
        } else {
            let context = self.collect_project_context()?;
            self.preview_project(&context)
        }
    }

    /// Initialize project in current directory (non-interactive)
    pub fn run_init_non_interactive(
        &self,
        project_type: Option<String>,
        from_config: Option<PathBuf>,
    ) -> Result<()> {
        println!(
            "{}",
            "🤖 Initializing in current directory (non-interactive)"
                .bright_blue()
                .bold()
        );

        let config = if let Some(config_path) = from_config {
            ForgeConfig::load_from(config_path)?
        } else {
            ForgeConfig::load()?
        };

        let current_dir = std::env::current_dir()?;
        let project_name = current_dir
            .file_name()
            .and_then(|name| name.to_str())
            .unwrap_or("my-project")
            .to_string();

        let project_type_str = project_type.unwrap_or_else(|| "cli-tool".to_string());
        let project_type = self.parse_project_type(&project_type_str)?;

        let context = ProjectContext {
            name: project_name,
            project_type,
            features: config
                .default_features
                .get(&project_type_str)
                .cloned()
                .unwrap_or_default(),
            author: config.default_author,
            description: None,
            license: config.default_license,
            edition: config.edition.unwrap_or_else(|| "2021".to_string()),
            target: None,
            esp32_chip: None,
        };

        self.init_project_in_current_dir(context)?;
        Ok(())
    }

    /// Initialize with regular interactive prompts
    pub fn run_init(&self, project_type: Option<String>) -> Result<()> {
        println!(
            "{}",
            "🔨 Initializing project in current directory"
                .bright_cyan()
                .bold()
        );

        let current_dir = std::env::current_dir()?;
        let project_name = current_dir
            .file_name()
            .and_then(|name| name.to_str())
            .unwrap_or("my-project")
            .to_string();

        let project_type = if let Some(pt) = project_type {
            self.parse_project_type(&pt)?
        } else {
            self.prompt_project_type_interactive()?
        };

        let features = self.prompt_features(&project_type, None)?;
        let author = self.prompt_optional_field("Author", "your-name")?;
        let description = self.prompt_optional_field("Description", "A new Rust project")?;
        let license = self.prompt_license()?;

        let context = ProjectContext {
            name: project_name,
            project_type,
            features,
            author,
            description,
            license,
            edition: "2021".to_string(),
            target: None,
            esp32_chip: None,
        };

        self.init_project_in_current_dir(context)?;
        Ok(())
    }

    /// Initialize from config file
    pub fn run_init_from_config(
        &self,
        config_path: PathBuf,
        project_type: Option<String>,
    ) -> Result<()> {
        println!("{}", "📁 Initializing from configuration...".bright_cyan());

        let config = ForgeConfig::load_from(config_path)?;

        let current_dir = std::env::current_dir()?;
        let project_name = current_dir
            .file_name()
            .and_then(|name| name.to_str())
            .unwrap_or("my-project")
            .to_string();

        let project_type_str = project_type
            .or_else(|| config.preferred_project_types.first().cloned())
            .unwrap_or_else(|| "cli-tool".to_string());
        let project_type = self.parse_project_type(&project_type_str)?;

        let context = ProjectContext {
            name: project_name,
            project_type,
            features: config
                .default_features
                .get(&project_type_str)
                .cloned()
                .unwrap_or_default(),
            author: config.default_author,
            description: None,
            license: config.default_license,
            edition: config.edition.unwrap_or_else(|| "2021".to_string()),
            target: None,
            esp32_chip: None,
        };

        self.init_project_in_current_dir(context)?;
        Ok(())
    }

    /// Dry run for init command
    pub fn run_init_dry_run(
        &self,
        project_type: Option<String>,
        non_interactive: bool,
        from_config: Option<PathBuf>,
    ) -> Result<()> {
        let current_dir = std::env::current_dir()?;
        let project_name = current_dir
            .file_name()
            .and_then(|name| name.to_str())
            .unwrap_or("my-project")
            .to_string();

        if non_interactive {
            let config = if let Some(config_path) = from_config {
                ForgeConfig::load_from(config_path)?
            } else {
                ForgeConfig::load()?
            };

            let project_type_str = project_type.unwrap_or_else(|| "cli-tool".to_string());
            let project_type = self.parse_project_type(&project_type_str)?;

            let context = ProjectContext {
                name: project_name,
                project_type,
                features: config
                    .default_features
                    .get(&project_type_str)
                    .cloned()
                    .unwrap_or_default(),
                author: config.default_author,
                description: None,
                license: config.default_license,
                edition: config.edition.unwrap_or_else(|| "2021".to_string()),
                target: None,
                esp32_chip: None,
            };

            self.preview_init(&context)
        } else {
            let project_type = if let Some(pt) = project_type {
                self.parse_project_type(&pt)?
            } else {
                self.prompt_project_type_interactive()?
            };

            let features = self.prompt_features(&project_type, None)?;
            let author = self.prompt_optional_field("Author", "your-name")?;
            let description = self.prompt_optional_field("Description", "A new Rust project")?;
            let license = self.prompt_license()?;

            let context = ProjectContext {
                name: project_name,
                project_type,
                features,
                author,
                description,
                license,
                edition: "2021".to_string(),
                target: None,
                esp32_chip: None,
            };

            self.preview_init(&context)
        }
    }

    /// Helper method to parse project type string
    fn parse_project_type(&self, project_type_str: &str) -> Result<ProjectType> {
        match project_type_str.to_lowercase().as_str() {
            "api-server" => Ok(ProjectType::ApiServer),
            "cli-tool" => Ok(ProjectType::CliTool),
            "library" => Ok(ProjectType::Library),
            "wasm-app" => Ok(ProjectType::WasmApp),
            "game-engine" => Ok(ProjectType::GameEngine),
            "embedded" => Ok(ProjectType::Embedded),
            "workspace" => Ok(ProjectType::Workspace),
            _ => Err(anyhow!("Invalid project type: {}", project_type_str)),
        }
    }

    /// Preview project structure without creating files
    fn preview_project(&self, context: &ProjectContext) -> Result<()> {
        println!("\n{}", "📋 Project Preview".bright_white().bold());
        println!("{}", "".repeat(50).bright_black());

        println!(
            "{} {}",
            "📦 Name:".bright_cyan(),
            context.name.bright_white()
        );
        println!(
            "{} {}",
            "🏗️  Type:".bright_cyan(),
            context.project_type.to_string().bright_white()
        );

        if let Some(author) = &context.author {
            println!("{} {}", "👤 Author:".bright_cyan(), author.bright_white());
        }

        if let Some(description) = &context.description {
            println!(
                "{} {}",
                "📝 Description:".bright_cyan(),
                description.bright_white()
            );
        }

        if let Some(license) = &context.license {
            println!(
                "{} {}",
                "⚖️  License:".bright_cyan(),
                license.bright_white()
            );
        }

        println!(
            "{} {}",
            "📅 Edition:".bright_cyan(),
            context.edition.bright_white()
        );

        if !context.features.is_empty() {
            println!(
                "{} {}",
                "🎯 Features:".bright_cyan(),
                context.features.join(", ").bright_white()
            );
        }

        println!("\n{}", "📁 Directory Structure:".bright_white().bold());
        self.preview_directory_structure(context);

        println!(
            "\n{}",
            "Next steps (if this were real):".bright_green().bold()
        );
        println!("  {} cd {}", "".bright_cyan(), context.name);
        println!("  {} cargo build", "".bright_cyan());
        println!("  {} cargo run\n", "".bright_cyan());

        Ok(())
    }

    /// Preview init structure
    fn preview_init(&self, context: &ProjectContext) -> Result<()> {
        println!("\n{}", "📋 Initialization Preview".bright_white().bold());
        println!("{}", "".repeat(50).bright_black());

        println!(
            "{} {}",
            "📦 Name:".bright_cyan(),
            context.name.bright_white()
        );
        println!(
            "{} {}",
            "🏗️  Type:".bright_cyan(),
            context.project_type.to_string().bright_white()
        );
        println!(
            "{} {}",
            "📁 Location:".bright_cyan(),
            "Current directory".bright_white()
        );

        if let Some(author) = &context.author {
            println!("{} {}", "👤 Author:".bright_cyan(), author.bright_white());
        }

        if let Some(license) = &context.license {
            println!(
                "{} {}",
                "⚖️  License:".bright_cyan(),
                license.bright_white()
            );
        }

        if !context.features.is_empty() {
            println!(
                "{} {}",
                "🎯 Features:".bright_cyan(),
                context.features.join(", ").bright_white()
            );
        }

        println!("\n{}", "📁 Files to be created:".bright_white().bold());
        self.preview_directory_structure(context);

        println!(
            "\n{}",
            "Next steps (if this were real):".bright_green().bold()
        );
        println!("  {} cargo build", "".bright_cyan());
        println!("  {} cargo run\n", "".bright_cyan());

        Ok(())
    }

    /// Preview directory structure
    fn preview_directory_structure(&self, context: &ProjectContext) {
        println!("  {}/", context.name.bright_yellow());
        println!("  ├── {}", "Cargo.toml".bright_green());
        println!("  ├── {}", "README.md".bright_green());

        if context.license.is_some() {
            println!("  ├── {}", "LICENSE".bright_green());
        }

        println!("  ├── {}/ ", "src".bright_blue());

        match context.project_type {
            ProjectType::Library => {
                println!("  │   └── {}", "lib.rs".bright_green());
            }
            _ => {
                println!("  │   └── {}", "main.rs".bright_green());
            }
        }

        if context.features.contains(&"testing".to_string()) {
            println!("  ├── {}/ ", "tests".bright_blue());
            println!("  │   └── {}", "integration_tests.rs".bright_green());
        }

        if context.project_type == ProjectType::WasmApp {
            println!("  └── {}", "index.html".bright_green());
        }

        if context.project_type == ProjectType::GameEngine {
            println!("  └── {}/ ", "assets".bright_blue());
            println!("      ├── {}/ ", "models".bright_blue());
            println!("      ├── {}/ ", "shaders".bright_blue());
            println!("      ├── {}/ ", "sounds".bright_blue());
            println!("      └── {}/ ", "textures".bright_blue());
        }
    }

    /// Initialize project in current directory
    fn init_project_in_current_dir(&self, context: ProjectContext) -> Result<()> {
        let current_dir = std::env::current_dir()?;

        println!("\n{}", "Creating project files...".bright_yellow());

        let pb = ProgressBar::new(100);
        pb.set_style(
            ProgressStyle::default_bar()
                .template("{prefix:.bold.dim} {bar:40.cyan/blue} {percent}% {msg}")
                .unwrap()
                .progress_chars("##-"),
        );
        pb.set_prefix("Progress");

        pb.set_message("Generating project files...");
        let config = context.to_project_config();
        let generator = Generator::new();

        pb.set_position(50);
        generator.generate(&config, &current_dir)?;

        pb.set_position(100);
        pb.finish_and_clear();

        println!(
            "\n{} {}",
            "".bright_green().bold(),
            "Project initialized successfully!".bright_green()
        );
        self.show_next_steps(&context, true)?;

        Ok(())
    }

    /// Enhanced next steps with better formatting
    fn show_next_steps(&self, context: &ProjectContext, is_init: bool) -> Result<()> {
        println!("\n{}", "🎉 Project Setup Complete!".bright_green().bold());
        println!("{}", "".repeat(50).bright_black());

        println!("\n{}", "📋 Project Summary:".bright_white().bold());
        println!(
            "  {} {}",
            "Name:".bright_cyan(),
            context.name.bright_white()
        );
        println!(
            "  {} {}",
            "Type:".bright_cyan(),
            context.project_type.to_string().bright_white()
        );
        if !context.features.is_empty() {
            println!(
                "  {} {}",
                "Features:".bright_cyan(),
                context.features.join(", ").bright_white()
            );
        }

        println!("\n{}", "🚀 Next Steps:".bright_white().bold());

        if !is_init {
            println!(
                "  {} cd {}",
                "1.".bright_yellow(),
                context.name.bright_white()
            );
        }

        let step_num = if is_init { 1 } else { 2 };
        println!("  {} cargo build", format!("{}.", step_num).bright_yellow());
        println!(
            "  {} cargo run",
            format!("{}.", step_num + 1).bright_yellow()
        );

        if context.features.contains(&"testing".to_string()) {
            println!(
                "  {} cargo test",
                format!("{}.", step_num + 2).bright_yellow()
            );
        }

        match context.project_type {
            ProjectType::ApiServer => {
                println!("\n{}", "💡 API Server Tips:".bright_blue().bold());
                println!("  • Edit src/main.rs to define your API routes");
                println!("  • Run with: cargo run");
                println!("  • Test endpoints at: http://localhost:3000");
            }
            ProjectType::CliTool => {
                println!("\n{}", "💡 CLI Tool Tips:".bright_blue().bold());
                println!("  • Edit src/main.rs to define your CLI commands");
                println!("  • Build release version: cargo build --release");
                println!("  • Install globally: cargo install --path .");
            }
            ProjectType::Library => {
                println!("\n{}", "💡 Library Tips:".bright_blue().bold());
                println!("  • Edit src/lib.rs to define your public API");
                println!("  • Publish to crates.io: cargo publish");
                println!("  • Generate docs: cargo doc --open");
            }
            ProjectType::WasmApp => {
                println!("\n{}", "💡 WASM App Tips:".bright_blue().bold());
                println!("  • Build WASM: wasm-pack build --target web");
                println!("  • Serve locally: python -m http.server 8000");
                println!("  • Open: http://localhost:8000");
            }
            ProjectType::GameEngine => {
                println!("\n{}", "💡 Game Development Tips:".bright_blue().bold());
                println!("  • Add assets to the assets/ directory");
                println!("  • Edit src/main.rs to create your game systems");
                println!("  • Run with: cargo run");
            }
            ProjectType::Embedded => {
                println!("\n{}", "💡 Embedded Tips:".bright_blue().bold());
                println!("  • Configure your target in .cargo/config.toml");
                println!("  • Flash to device: cargo embed");
                println!("  • Debug with RTT: cargo embed --release");
            }
            ProjectType::Workspace => {
                println!("\n{}", "💡 Workspace Tips:".bright_blue().bold());
                println!("  • Add new crates: cargo new crates/new-crate");
                println!("  • Build all: cargo build");
                println!("  • Test all: cargo test");
            }
        }

        println!("\n{}", "📚 Resources:".bright_white().bold());
        println!("  • Rust Book: https://doc.rust-lang.org/book/");
        println!("  • Cargo Guide: https://doc.rust-lang.org/cargo/");
        println!("  • Crates.io: https://crates.io/");

        Ok(())
    }
}