bevy-agent 0.1.0

AI-powered Bevy game development assistant with GPT/Claude integration
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
//! Command-line interface for Bevy AI
//! 
//! This module provides a comprehensive CLI for interacting with the Bevy AI system.
//! It supports game creation, feature addition, code improvement, debugging, and project management.

use crate::{
    ai::BevyAIAgent,
    config::{AIConfig, ModelType},
    error::{BevyAIError, Result},
    game_templates::{TemplateManager, TemplateContext},
    project::{Project, ProjectManager},
    utils::{build_utils, config_utils},
};
use clap::{Parser, Subcommand, ValueEnum};
use std::path::PathBuf;
use tracing::{error, info, warn};

/// Bevy AI Agent - AI-powered Bevy game development assistant
#[derive(Parser)]
#[command(name = "bevy-agent")]
#[command(about = "AI-powered Bevy game prototyping assistant with GPT/Claude integration")]
#[command(version = crate::VERSION)]
pub struct Cli {
    /// The command to execute
    #[command(subcommand)]
    pub command: Commands,
    
    /// Enable verbose logging
    #[arg(short, long, global = true)]
    pub verbose: bool,
    
    /// Configuration file path
    #[arg(short, long, global = true)]
    pub config: Option<PathBuf>,
}

/// Available CLI commands
#[derive(Subcommand)]
pub enum Commands {
    /// Generate a new game prototype from natural language description
    Create {
        /// Describe the game you want to create
        description: String,
        
        /// AI model to use (gpt-4, claude-3-opus, etc.)
        #[arg(long)]
        model: Option<ModelType>,
        
        /// Project name (defaults to generated name)
        #[arg(long)]
        name: Option<String>,
        
        /// Output directory
        #[arg(long, short)]
        output: Option<PathBuf>,
        
        /// Use a specific template
        #[arg(long)]
        template: Option<String>,
        
        /// Don't create a new directory, use current directory
        #[arg(long)]
        in_place: bool,
    },
    
    /// Add features to existing prototype
    Add {
        /// Describe what to add to the game
        feature: String,
        
        /// AI model to use
        #[arg(long)]
        model: Option<ModelType>,
        
        /// Project directory (defaults to current directory)
        #[arg(long, short)]
        project: Option<PathBuf>,
    },
    
    /// Refactor or improve existing code
    Improve {
        /// What to improve (performance, readability, features)
        aspect: ImprovementAspect,
        
        /// AI model to use
        #[arg(long)]
        model: Option<ModelType>,
        
        /// Specific file to improve (defaults to main.rs)
        #[arg(long)]
        file: Option<PathBuf>,
        
        /// Project directory (defaults to current directory)
        #[arg(long, short)]
        project: Option<PathBuf>,
    },
    
    /// Ask AI to explain the current codebase
    Explain {
        /// AI model to use
        #[arg(long)]
        model: Option<ModelType>,
        
        /// Specific file to explain (defaults to main.rs)
        #[arg(long)]
        file: Option<PathBuf>,
        
        /// Project directory (defaults to current directory)
        #[arg(long, short)]
        project: Option<PathBuf>,
    },
    
    /// Debug code issues with AI assistance
    Debug {
        /// Error message or description of the issue
        error: String,
        
        /// AI model to use
        #[arg(long)]
        model: Option<ModelType>,
        
        /// Specific file with the issue (defaults to main.rs)
        #[arg(long)]
        file: Option<PathBuf>,
        
        /// Project directory (defaults to current directory)
        #[arg(long, short)]
        project: Option<PathBuf>,
    },
    
    /// Initialize a new Bevy project with AI agent support
    Init {
        /// Project name
        name: String,
        
        /// Project description
        #[arg(long, short)]
        description: Option<String>,
        
        /// Output directory
        #[arg(long, short)]
        output: Option<PathBuf>,
        
        /// Use a specific template
        #[arg(long)]
        template: Option<String>,
    },
    
    /// Configure AI API keys and settings
    Config {
        /// OpenAI API key
        #[arg(long)]
        openai_key: Option<String>,
        
        /// Anthropic API key
        #[arg(long)]
        anthropic_key: Option<String>,
        
        /// Google API key
        #[arg(long)]
        google_key: Option<String>,
        
        /// Default AI model
        #[arg(long)]
        default_model: Option<ModelType>,
        
        /// Show current configuration
        #[arg(long)]
        show: bool,
        
        /// Validate configuration
        #[arg(long)]
        validate: bool,
    },
    
    /// Build operations
    Build {
        /// Build operation to perform
        #[command(subcommand)]
        operation: BuildOperation,
    },
    
    /// Project management commands
    Project {
        /// Project operation to perform
        #[command(subcommand)]
        operation: ProjectOperation,
    },
    
    /// Template management commands
    Template {
        /// Template operation to perform
        #[command(subcommand)]
        operation: TemplateOperation,
    },
}

/// Build and development operations
#[derive(Subcommand)]
pub enum BuildOperation {
    /// Build the current prototype
    Build {
        /// Project directory (defaults to current directory)
        #[arg(long, short)]
        project: Option<PathBuf>,
        
        /// Release build
        #[arg(long)]
        release: bool,
    },
    
    /// Run the current prototype
    Run {
        /// Project directory (defaults to current directory)
        #[arg(long, short)]
        project: Option<PathBuf>,
        
        /// Release build
        #[arg(long)]
        release: bool,
        
        /// Additional arguments to pass to the program
        #[arg(last = true)]
        args: Vec<String>,
    },
    
    /// Check code for errors
    Check {
        /// Project directory (defaults to current directory)
        #[arg(long, short)]
        project: Option<PathBuf>,
    },
    
    /// Run clippy lints
    Clippy {
        /// Project directory (defaults to current directory)
        #[arg(long, short)]
        project: Option<PathBuf>,
    },
    
    /// Format code
    Format {
        /// Project directory (defaults to current directory)
        #[arg(long, short)]
        project: Option<PathBuf>,
    },
    
    /// Run tests
    Test {
        /// Project directory (defaults to current directory)
        #[arg(long, short)]
        project: Option<PathBuf>,
    },
}

/// Project management operations
#[derive(Subcommand)]
pub enum ProjectOperation {
    /// Show project information
    Info {
        /// Project directory (defaults to current directory)
        #[arg(long, short)]
        project: Option<PathBuf>,
    },
    
    /// Show project statistics
    Stats {
        /// Project directory (defaults to current directory)
        #[arg(long, short)]
        project: Option<PathBuf>,
    },
    
    /// Show conversation history
    History {
        /// Project directory (defaults to current directory)
        #[arg(long, short)]
        project: Option<PathBuf>,
        
        /// Number of recent conversations to show
        #[arg(long, default_value = "10")]
        limit: usize,
    },
    
    /// Export project data
    Export {
        /// Output file path
        output: PathBuf,
        
        /// Project directory (defaults to current directory)
        #[arg(long, short)]
        project: Option<PathBuf>,
        
        /// Export format
        #[arg(long, default_value = "json")]
        format: ExportFormat,
    },
    
    /// Clean generated files
    Clean {
        /// Project directory (defaults to current directory)
        #[arg(long, short)]
        project: Option<PathBuf>,
        
        /// Also clean Cargo build artifacts
        #[arg(long)]
        cargo: bool,
    },
}

/// Template management operations
#[derive(Subcommand)]
pub enum TemplateOperation {
    /// List available templates
    List,
    
    /// Show template details
    Show {
        /// Template name
        name: String,
    },
    
    /// Create a new custom template
    Create {
        /// Template name
        name: String,
        
        /// Template description
        description: String,
        
        /// Template file path
        file: PathBuf,
    },
    
    /// Apply a template to current project
    Apply {
        /// Template name
        name: String,
        
        /// Project directory (defaults to current directory)
        #[arg(long, short)]
        project: Option<PathBuf>,
    },
}

/// Aspects of code that can be improved
#[derive(ValueEnum, Clone, Debug)]
pub enum ImprovementAspect {
    /// Improve code performance and efficiency
    Performance,
    /// Improve code readability and maintainability
    Readability,
    /// Add or improve features
    Features,
    /// Improve code structure and organization
    Structure,
    /// Add or improve tests
    Testing,
    /// Add or improve documentation
    Documentation,
    /// Improve security aspects
    Security,
    /// Improve overall efficiency
    Efficiency,
}

/// Export formats for project data
#[derive(ValueEnum, Clone, Debug)]
pub enum ExportFormat {
    /// JSON format
    Json,
    /// YAML format
    Yaml,
    /// TOML format
    Toml,
    /// Markdown format
    Markdown,
}

impl std::fmt::Display for ImprovementAspect {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ImprovementAspect::Performance => write!(f, "performance"),
            ImprovementAspect::Readability => write!(f, "readability"),
            ImprovementAspect::Features => write!(f, "features"),
            ImprovementAspect::Structure => write!(f, "structure"),
            ImprovementAspect::Testing => write!(f, "testing"),
            ImprovementAspect::Documentation => write!(f, "documentation"),
            ImprovementAspect::Security => write!(f, "security"),
            ImprovementAspect::Efficiency => write!(f, "efficiency"),
        }
    }
}

/// Main CLI handler
pub struct CliHandler {
    config: AIConfig,
    agent: Option<BevyAIAgent>,
}

impl CliHandler {
    /// Create a new CLI handler
    pub async fn new(config_path: Option<PathBuf>) -> Result<Self> {
        let config = if let Some(path) = config_path {
            AIConfig::from_file(path)?
        } else {
            AIConfig::load_or_create()?
        };
        
        let agent = BevyAIAgent::new(config.clone()).await.ok();
        
        Ok(Self { config, agent })
    }
    
    /// Handle CLI commands
    pub async fn handle(&mut self, cli: Cli) -> Result<()> {
        // Initialize logging
        if cli.verbose {
            tracing_subscriber::fmt()
                .with_env_filter("bevy_agent=debug")
                .init();
        } else {
            tracing_subscriber::fmt()
                .with_env_filter("bevy_agent=info")
                .init();
        }
        
        match cli.command {
            Commands::Create { description, model, name, output, template, in_place } => {
                self.handle_create(description, model, name, output, template, in_place).await
            }
            Commands::Add { feature, model, project } => {
                self.handle_add(feature, model, project).await
            }
            Commands::Improve { aspect, model, file, project } => {
                self.handle_improve(aspect, model, file, project).await
            }
            Commands::Explain { model, file, project } => {
                self.handle_explain(model, file, project).await
            }
            Commands::Debug { error, model, file, project } => {
                self.handle_debug(error, model, file, project).await
            }
            Commands::Init { name, description, output, template } => {
                self.handle_init(name, description, output, template).await
            }
            Commands::Config { openai_key, anthropic_key, google_key, default_model, show, validate } => {
                self.handle_config(openai_key, anthropic_key, google_key, default_model, show, validate).await
            }
            Commands::Build { operation } => {
                self.handle_build_operation(operation).await
            }
            Commands::Project { operation } => {
                self.handle_project_operation(operation).await
            }
            Commands::Template { operation } => {
                self.handle_template_operation(operation).await
            }
        }
    }
    
    async fn handle_create(
        &mut self,
        description: String,
        _model: Option<ModelType>,
        name: Option<String>,
        output: Option<PathBuf>,
        template: Option<String>,
        in_place: bool,
    ) -> Result<()> {
        let agent = self.agent.as_ref()
            .ok_or_else(|| BevyAIError::ai_api("No AI agent available. Please configure API keys.".to_string()))?;
        
        let project_name = name.unwrap_or_else(|| self.generate_project_name(&description));
        let project_path = if in_place {
            std::env::current_dir()?
        } else {
            output.unwrap_or_else(|| std::env::current_dir().unwrap().join(&project_name))
        };
        
        info!("Creating game '{}' from description: {}", project_name, description);
        
        if let Some(template_name) = template {
            // Use template-based generation
            let template_manager = TemplateManager::new()?;
            let context = TemplateContext::new(project_name.clone(), description.clone());
            let code = template_manager.generate(&template_name, &context)?;
            
            // Create project structure manually
            let mut project_manager = ProjectManager::new(&project_path);
            project_manager.init(&project_name, &description).await?;
            
            // Write generated code
            std::fs::write(project_path.join("src/main.rs"), code)?;
        } else {
            // Use AI generation
            let mut project = Project::init(project_path.clone(), &project_name, &description, agent.clone()).await?;
            let response = project.generate_game(&description).await?;
            
            info!("Game '{}' created successfully!", project_name);
            info!("Project location: {}", project_path.display());
            info!("To run: cd {} && cargo run", project_path.display());
            
            if let Some(tokens) = response.tokens_used {
                info!("Tokens used: {}", tokens);
            }
        }
        
        Ok(())
    }
    
    async fn handle_add(&mut self, feature: String, _model: Option<ModelType>, project: Option<PathBuf>) -> Result<()> {
        let agent = self.agent.as_ref()
            .ok_or_else(|| BevyAIError::ai_api("No AI agent available. Please configure API keys.".to_string()))?;
        
        let project_path = project.unwrap_or_else(|| std::env::current_dir().unwrap());
        
        info!("Adding feature: {}", feature);
        
        let mut project = Project::new(project_path, agent.clone()).await?;
        let response = project.add_feature(&feature).await?;
        
        info!("Feature added successfully!");
        
        if let Some(tokens) = response.tokens_used {
            info!("Tokens used: {}", tokens);
        }
        
        Ok(())
    }
    
    async fn handle_improve(
        &mut self,
        aspect: ImprovementAspect,
        _model: Option<ModelType>,
        file: Option<PathBuf>,
        project: Option<PathBuf>,
    ) -> Result<()> {
        let agent = self.agent.as_ref()
            .ok_or_else(|| BevyAIError::ai_api("No AI agent available. Please configure API keys.".to_string()))?;
        
        let project_path = project.unwrap_or_else(|| std::env::current_dir().unwrap());
        let file_path = file.unwrap_or_else(|| project_path.join("src/main.rs"));
        
        if !file_path.exists() {
            return Err(BevyAIError::file_operation("read", &file_path.display().to_string()));
        }
        
        let code = std::fs::read_to_string(&file_path)?;
        
        info!("Improving {} of {}", aspect, file_path.display());
        
        let response = agent
            .improve_code(aspect.to_string(), code)
            .with_model(_model.unwrap_or(self.config.default_model.clone()))
            .execute()
            .await?;
        
        let improved_code = agent.extract_code(&response.content);
        
        // Create backup
        crate::utils::fs_utils::backup_file(&file_path)?;
        
        // Write improved code
        std::fs::write(&file_path, improved_code)?;
        
        info!("Code improved successfully!");
        info!("Backup created for original file");
        
        if let Some(tokens) = response.tokens_used {
            info!("Tokens used: {}", tokens);
        }
        
        Ok(())
    }
    
    async fn handle_explain(
        &mut self,
        _model: Option<ModelType>,
        file: Option<PathBuf>,
        project: Option<PathBuf>,
    ) -> Result<()> {
        let agent = self.agent.as_ref()
            .ok_or_else(|| BevyAIError::ai_api("No AI agent available. Please configure API keys.".to_string()))?;
        
        let project_path = project.unwrap_or_else(|| std::env::current_dir().unwrap());
        let file_path = file.unwrap_or_else(|| project_path.join("src/main.rs"));
        
        if !file_path.exists() {
            return Err(BevyAIError::file_operation("read", &file_path.display().to_string()));
        }
        
        let code = std::fs::read_to_string(&file_path)?;
        
        info!("Explaining code in {}", file_path.display());
        
        let response = agent
            .explain_code(code)
            .with_model(_model.unwrap_or(self.config.default_model.clone()))
            .execute()
            .await?;
        
        println!("\nAI Code Explanation:\n");
        println!("{}", response.content);
        
        if let Some(tokens) = response.tokens_used {
            info!("Tokens used: {}", tokens);
        }
        
        Ok(())
    }
    
    async fn handle_debug(
        &mut self,
        error: String,
        _model: Option<ModelType>,
        file: Option<PathBuf>,
        project: Option<PathBuf>,
    ) -> Result<()> {
        let agent = self.agent.as_ref()
            .ok_or_else(|| BevyAIError::ai_api("No AI agent available. Please configure API keys.".to_string()))?;
        
        let project_path = project.unwrap_or_else(|| std::env::current_dir().unwrap());
        let file_path = file.unwrap_or_else(|| project_path.join("src/main.rs"));
        
        if !file_path.exists() {
            return Err(BevyAIError::file_operation("read", &file_path.display().to_string()));
        }
        
        let code = std::fs::read_to_string(&file_path)?;
        
        info!("Debugging issue: {}", error);
        
        let response = agent
            .debug_code(code, error)
            .with_model(_model.unwrap_or(self.config.default_model.clone()))
            .execute()
            .await?;
        
        println!("\nAI Debug Analysis:\n");
        println!("{}", response.content);
        
        // Extract and offer to apply fixed code
        let fixed_code = agent.extract_code(&response.content);
        if fixed_code != response.content {
            println!("\nApply the suggested fix? [y/N]");
            let mut input = String::new();
            std::io::stdin().read_line(&mut input)?;
            
            if input.trim().to_lowercase() == "y" {
                // Create backup
                crate::utils::fs_utils::backup_file(&file_path)?;
                
                // Write fixed code
                std::fs::write(&file_path, fixed_code)?;
                
                info!("Fix applied successfully!");
                info!("Backup created for original file");
            }
        }
        
        if let Some(tokens) = response.tokens_used {
            info!("Tokens used: {}", tokens);
        }
        
        Ok(())
    }
    
    async fn handle_init(
        &mut self,
        name: String,
        description: Option<String>,
        output: Option<PathBuf>,
        template: Option<String>,
    ) -> Result<()> {
        let description = description.unwrap_or_else(|| format!("A new Bevy game: {}", name));
        let project_path = output.unwrap_or_else(|| std::env::current_dir().unwrap().join(&name));
        
        info!("Initializing new Bevy AI project: {}", name);
        
        let mut project_manager = ProjectManager::new(&project_path);
        project_manager.init(&name, &description).await?;
        
        if let Some(template_name) = template {
            let template_manager = TemplateManager::new()?;
            let context = TemplateContext::new(name.clone(), description.clone());
            let code = template_manager.generate(&template_name, &context)?;
            
            std::fs::write(project_path.join("src/main.rs"), code)?;
            info!("Applied template: {}", template_name);
        }
        
        info!("Project '{}' initialized successfully!", name);
        info!("Project location: {}", project_path.display());
        info!("To get started: cd {} && bevy-agent add \"your first feature\"", project_path.display());
        
        Ok(())
    }
    
    async fn handle_config(
        &mut self,
        openai_key: Option<String>,
        anthropic_key: Option<String>,
        google_key: Option<String>,
        default_model: Option<ModelType>,
        show: bool,
        validate: bool,
    ) -> Result<()> {
        if show {
            println!("Current Configuration:");
            println!("OpenAI: {}", if self.config.openai.is_some() { "Configured" } else { "Not configured" });
            println!("Anthropic: {}", if self.config.anthropic.is_some() { "Configured" } else { "Not configured" });
            println!("Google: {}", if self.config.google.is_some() { "Configured" } else { "Not configured" });
            println!("Default Model: {}", self.config.default_model);
            println!("Available Models: {:?}", self.config.available_models());
            return Ok(());
        }
        
        if validate {
            let warnings = config_utils::validate_config(&self.config)?;
            if warnings.is_empty() {
                info!("Configuration is valid");
            } else {
                warn!("Configuration warnings:");
                for warning in warnings {
                    warn!("  - {}", warning);
                }
            }
            return Ok(());
        }
        
        let mut updated = false;
        
        if let Some(key) = openai_key {
            self.config.openai = Some(crate::config::OpenAIConfig {
                api_key: key,
                organization: None,
                base_url: None,
            });
            info!("OpenAI API key configured");
            updated = true;
        }
        
        if let Some(key) = anthropic_key {
            self.config.anthropic = Some(crate::config::AnthropicConfig {
                api_key: key,
                base_url: None,
            });
            info!("Anthropic API key configured");
            updated = true;
        }
        
        if let Some(key) = google_key {
            self.config.google = Some(crate::config::GoogleConfig {
                api_key: key,
                base_url: None,
            });
            info!("Google API key configured");
            updated = true;
        }
        
        if let Some(model) = default_model {
            self.config.default_model = model;
            info!("Default model set to: {}", self.config.default_model);
            updated = true;
        }
        
        if updated {
            let config_path = AIConfig::default_config_path()?;
            self.config.save_to_file(&config_path)?;
            
            // Recreate agent with new config
            if let Ok(agent) = BevyAIAgent::new(self.config.clone()).await {
                self.agent = Some(agent);
                info!("🔄 AI agent updated with new configuration");
            }
        }
        
        Ok(())
    }
    
    async fn handle_build_operation(&self, operation: BuildOperation) -> Result<()> {
        match operation {
            BuildOperation::Build { project, release: _ } => {
                let project_path = project.unwrap_or_else(|| std::env::current_dir().unwrap());
                info!("Building project...");
                
                let manager = ProjectManager::new(&project_path);
                let result = manager.build().await?;
                
                info!("Build completed successfully!");
                if !result.is_empty() {
                    println!("{}", result);
                }
            }
            BuildOperation::Run { project, release: _, args: _ } => {
                let project_path = project.unwrap_or_else(|| std::env::current_dir().unwrap());
                info!("Running project...");
                
                let manager = ProjectManager::new(&project_path);
                let result = manager.run().await?;
                
                if !result.is_empty() {
                    println!("{}", result);
                }
            }
            BuildOperation::Check { project } => {
                let project_path = project.unwrap_or_else(|| std::env::current_dir().unwrap());
                info!("Checking code...");
                
                let result = build_utils::cargo_check(&project_path)?;
                println!("{}", result);
            }
            BuildOperation::Clippy { project } => {
                let project_path = project.unwrap_or_else(|| std::env::current_dir().unwrap());
                info!("Running clippy...");
                
                let result = build_utils::cargo_clippy(&project_path)?;
                println!("{}", result);
            }
            BuildOperation::Format { project } => {
                let project_path = project.unwrap_or_else(|| std::env::current_dir().unwrap());
                info!("Formatting code...");
                
                let result = build_utils::cargo_fmt(&project_path)?;
                info!("{}", result);
            }
            BuildOperation::Test { project } => {
                let _project_path = project.unwrap_or_else(|| std::env::current_dir().unwrap());
                info!("🧪 Running tests...");
                
                // TODO: Implement test running
                info!("Test runner not yet implemented");
            }
        }
        
        Ok(())
    }
    
    async fn handle_project_operation(&self, operation: ProjectOperation) -> Result<()> {
        match operation {
            ProjectOperation::Info { project } => {
                let project_path = project.unwrap_or_else(|| std::env::current_dir().unwrap());
                let mut manager = ProjectManager::new(&project_path);
                manager.load().await?;
                
                if let Some(config) = manager.config() {
                    println!("Project Information:");
                    println!("Name: {}", config.metadata.name);
                    println!("Description: {}", config.metadata.description);
                    println!("Version: {}", config.metadata.version);
                    println!("Created: {}", config.metadata.created_at.format("%Y-%m-%d %H:%M:%S"));
                    println!("Updated: {}", config.metadata.updated_at.format("%Y-%m-%d %H:%M:%S"));
                    println!("Bevy Version: {}", config.metadata.bevy_version);
                    println!("Features: {}", config.metadata.features.join(", "));
                    println!("Conversations: {}", config.conversations.len());
                    println!("Generated Files: {}", config.generated_files.len());
                }
            }
            ProjectOperation::Stats { project } => {
                let project_path = project.unwrap_or_else(|| std::env::current_dir().unwrap());
                let manager = ProjectManager::new(&project_path);
                let stats = manager.stats().await?;
                
                println!("Project Statistics:");
                println!("Lines of Code: {}", stats.lines_of_code);
                println!("Rust Files: {}", stats.rust_files);
                println!("AI Conversations: {}", stats.conversations);
                println!("Generated Files: {}", stats.generated_files);
                println!("Dependencies: {}", stats.dependencies);
                println!("Features: {}", stats.features);
            }
            ProjectOperation::History { project, limit } => {
                let project_path = project.unwrap_or_else(|| std::env::current_dir().unwrap());
                let mut manager = ProjectManager::new(&project_path);
                manager.load().await?;
                
                if let Some(config) = manager.config() {
                    println!("📜 Conversation History (last {}):", limit);
                    for conversation in config.conversations.iter().rev().take(limit) {
                        println!("\n{} ({})", 
                               conversation.timestamp.format("%Y-%m-%d %H:%M:%S"),
                               conversation.model_used);
                        println!("👤 Request: {}", conversation.request);
                        println!("AI Response: {}...", 
                               conversation.response.chars().take(100).collect::<String>());
                        if let Some(tokens) = conversation.tokens_used {
                            println!("Tokens: {}", tokens);
                        }
                    }
                }
            }
            ProjectOperation::Export { output: _, project: _, format: _ } => {
                // TODO: Implement project export
                info!("Project export not yet implemented");
            }
            ProjectOperation::Clean { project, cargo } => {
                let project_path = project.unwrap_or_else(|| std::env::current_dir().unwrap());
                info!("Cleaning project...");
                
                if cargo {
                    std::process::Command::new("cargo")
                        .arg("clean")
                        .current_dir(&project_path)
                        .output()?;
                    info!("Cargo artifacts cleaned");
                }
                
                info!("Project cleaned");
            }
        }
        
        Ok(())
    }
    
    async fn handle_template_operation(&self, operation: TemplateOperation) -> Result<()> {
        match operation {
            TemplateOperation::List => {
                let _manager = TemplateManager::new()?;
                let templates = TemplateManager::builtin_templates();
                
                println!("Available Templates:");
                for template in templates {
                    println!("  {} - {} ({})", 
                           template.name, 
                           template.description,
                           template.category);
                }
            }
            TemplateOperation::Show { name } => {
                let templates = TemplateManager::builtin_templates();
                if let Some(template) = templates.iter().find(|t| t.name == name) {
                    println!("Template: {}", template.name);
                    println!("Description: {}", template.description);
                    println!("Category: {}", template.category);
                    println!("Dependencies: {}", template.dependencies.join(", "));
                    println!("Features: {}", template.features.join(", "));
                } else {
                    error!("Template '{}' not found", name);
                }
            }
            TemplateOperation::Create { name: _, description: _, file: _ } => {
                // TODO: Implement custom template creation
                info!("Custom template creation not yet implemented");
            }
            TemplateOperation::Apply { name: _, project: _ } => {
                // TODO: Implement template application
                info!("Template application not yet implemented");
            }
        }
        
        Ok(())
    }
    
    fn generate_project_name(&self, description: &str) -> String {
        description
            .split_whitespace()
            .take(3)
            .collect::<Vec<_>>()
            .join("_")
            .to_lowercase()
            .chars()
            .filter(|c| c.is_alphanumeric() || *c == '_')
            .collect()
    }
}