coderlib 0.1.0

A Rust library for AI-powered code assistance and agentic system
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
//! Context gathering system for Edit integration
//!
//! This module provides intelligent context gathering from the editor state,
//! open files, project structure, and version control information.

use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use tokio::fs;
use tracing::{debug, info};

use crate::core::CoderLibError;
use crate::lsp::{Position, Range};
use crate::integration::{EditState, HostIntegration};
use crate::tools::{git::GitTool, code_analysis::CodeAnalysisTool};

/// Context gathering configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ContextConfig {
    /// Maximum number of files to include in context
    pub max_files: usize,
    /// Maximum total context size in characters
    pub max_context_size: usize,
    /// Number of lines to include around cursor
    pub cursor_context_lines: usize,
    /// Whether to include git information
    pub include_git_info: bool,
    /// Whether to include code analysis
    pub include_code_analysis: bool,
    /// Whether to include project structure
    pub include_project_structure: bool,
    /// File extensions to prioritize
    pub priority_extensions: Vec<String>,
    /// Directories to exclude from context
    pub exclude_directories: Vec<String>,
}

impl Default for ContextConfig {
    fn default() -> Self {
        Self {
            max_files: 10,
            max_context_size: 50000,
            cursor_context_lines: 10,
            include_git_info: true,
            include_code_analysis: true,
            include_project_structure: true,
            priority_extensions: vec![
                "rs".to_string(), "py".to_string(), "js".to_string(), "ts".to_string(),
                "go".to_string(), "java".to_string(), "c".to_string(), "cpp".to_string(),
                "md".to_string(), "toml".to_string(), "json".to_string(), "yaml".to_string(),
            ],
            exclude_directories: vec![
                "target".to_string(), "node_modules".to_string(), ".git".to_string(),
                "build".to_string(), "dist".to_string(), "__pycache__".to_string(),
            ],
        }
    }
}

/// Gathered context information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GatheredContext {
    /// Current file information
    pub current_file: Option<FileContext>,
    /// Related files
    pub related_files: Vec<FileContext>,
    /// Project structure overview
    pub project_structure: Option<ProjectStructure>,
    /// Git repository information
    pub git_info: Option<GitContext>,
    /// Code analysis results
    pub code_analysis: Option<CodeAnalysisContext>,
    /// Cursor and selection context
    pub cursor_context: Option<CursorContext>,
    /// Total context size in characters
    pub total_size: usize,
}

/// File context information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileContext {
    /// File path
    pub path: PathBuf,
    /// File content (may be truncated)
    pub content: String,
    /// File language/type
    pub language: Option<String>,
    /// File size in bytes
    pub size: usize,
    /// Whether content was truncated
    pub truncated: bool,
    /// Relevance score (0.0 to 1.0)
    pub relevance: f64,
}

/// Project structure information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProjectStructure {
    /// Project root directory
    pub root: PathBuf,
    /// Project type (rust, node, python, etc.)
    pub project_type: Option<String>,
    /// Important files (README, Cargo.toml, package.json, etc.)
    pub important_files: Vec<PathBuf>,
    /// Directory structure overview
    pub directories: Vec<String>,
    /// File count by extension
    pub file_counts: HashMap<String, usize>,
}

/// Git context information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GitContext {
    /// Current branch
    pub branch: String,
    /// Recent commits (last 5)
    pub recent_commits: Vec<String>,
    /// Modified files
    pub modified_files: Vec<PathBuf>,
    /// Current file git blame info (if applicable)
    pub blame_info: Option<String>,
}

/// Code analysis context
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CodeAnalysisContext {
    /// Complexity metrics for current file
    pub complexity: Option<String>,
    /// Security issues found
    pub security_issues: Vec<String>,
    /// Code quality metrics
    pub quality_metrics: Option<String>,
}

/// Cursor and selection context
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CursorContext {
    /// Current position
    pub position: Position,
    /// Selected text (if any)
    pub selection: Option<String>,
    /// Context around cursor
    pub surrounding_text: String,
    /// Current function/method name (if detectable)
    pub current_function: Option<String>,
    /// Current class/struct name (if detectable)
    pub current_class: Option<String>,
}

/// Context gatherer implementation
pub struct ContextGatherer {
    /// Configuration
    config: ContextConfig,
    /// Git tool for repository information
    git_tool: Option<GitTool>,
    /// Code analysis tool
    code_analysis_tool: Option<CodeAnalysisTool>,
}

impl ContextGatherer {
    /// Create a new context gatherer
    pub fn new(config: ContextConfig) -> Self {
        let git_tool = if config.include_git_info {
            Some(GitTool::new())
        } else {
            None
        };

        let code_analysis_tool = if config.include_code_analysis {
            CodeAnalysisTool::new().ok()
        } else {
            None
        };

        Self {
            config,
            git_tool,
            code_analysis_tool,
        }
    }

    /// Gather context from the current editor state
    pub async fn gather_context(
        &self,
        state: &EditState,
        host: &dyn HostIntegration,
    ) -> Result<GatheredContext, CoderLibError> {
        info!("Gathering context for AI assistance");

        let mut context = GatheredContext {
            current_file: None,
            related_files: Vec::new(),
            project_structure: None,
            git_info: None,
            code_analysis: None,
            cursor_context: None,
            total_size: 0,
        };

        // Gather current file context
        if let Some(current_file_path) = &state.current_file {
            context.current_file = self.gather_file_context(current_file_path, host, 1.0).await?;
        }

        // Gather cursor context
        context.cursor_context = self.gather_cursor_context(state, host).await?;

        // Gather related files
        context.related_files = self.gather_related_files(state, host).await?;

        // Gather project structure
        if self.config.include_project_structure {
            context.project_structure = self.gather_project_structure(&state.working_directory).await?;
        }

        // Gather git information
        if self.config.include_git_info {
            context.git_info = self.gather_git_context(&state.working_directory, &state.current_file).await?;
        }

        // Gather code analysis
        if self.config.include_code_analysis {
            if let Some(current_file) = &state.current_file {
                context.code_analysis = self.gather_code_analysis_context(current_file, host).await?;
            }
        }

        // Calculate total context size
        context.total_size = self.calculate_context_size(&context);

        // Trim context if it exceeds maximum size
        if context.total_size > self.config.max_context_size {
            self.trim_context(&mut context);
        }

        debug!("Context gathered: {} files, {} total characters", 
            context.related_files.len() + if context.current_file.is_some() { 1 } else { 0 },
            context.total_size);

        Ok(context)
    }

    /// Gather context for a specific file
    async fn gather_file_context(
        &self,
        path: &Path,
        host: &dyn HostIntegration,
        relevance: f64,
    ) -> Result<Option<FileContext>, CoderLibError> {
        match host.get_file_content(path).await {
            Ok(content) => {
                let language = self.detect_language(path);
                let size = content.len();
                let truncated = size > 10000; // Truncate very large files
                let final_content = if truncated {
                    format!("{}...\n[Content truncated - showing first 10000 characters]", 
                        &content[..10000])
                } else {
                    content
                };

                Ok(Some(FileContext {
                    path: path.to_path_buf(),
                    content: final_content,
                    language,
                    size,
                    truncated,
                    relevance,
                }))
            }
            Err(_) => {
                debug!("Could not read file: {}", path.display());
                Ok(None)
            }
        }
    }

    /// Gather cursor context
    async fn gather_cursor_context(
        &self,
        state: &EditState,
        host: &dyn HostIntegration,
    ) -> Result<Option<CursorContext>, CoderLibError> {
        if let Some(current_file) = &state.current_file {
            let content = host.get_file_content(current_file).await?;
            let lines: Vec<&str> = content.lines().collect();
            
            let cursor_line = (state.cursor_position.line as usize).saturating_sub(1);
            let start_line = cursor_line.saturating_sub(self.config.cursor_context_lines);
            let end_line = (cursor_line + self.config.cursor_context_lines + 1).min(lines.len());
            
            let surrounding_text = lines[start_line..end_line].join("\n");
            
            // Get selected text if there's a selection
            let selection = if let Some(range) = &state.selection {
                self.extract_selection_text(&content, range)
            } else {
                None
            };

            // Try to detect current function/class (simple heuristic)
            let (current_function, current_class) = self.detect_current_scope(&lines, cursor_line);

            Ok(Some(CursorContext {
                position: state.cursor_position,
                selection,
                surrounding_text,
                current_function,
                current_class,
            }))
        } else {
            Ok(None)
        }
    }

    /// Gather related files based on current context
    async fn gather_related_files(
        &self,
        state: &EditState,
        host: &dyn HostIntegration,
    ) -> Result<Vec<FileContext>, CoderLibError> {
        let mut related_files = Vec::new();
        let mut processed_files = HashSet::new();

        // Add open files
        for file_path in &state.open_files {
            if Some(file_path) != state.current_file.as_ref() && !processed_files.contains(file_path) {
                if let Some(file_context) = self.gather_file_context(file_path, host, 0.8).await? {
                    related_files.push(file_context);
                    processed_files.insert(file_path.clone());
                }
            }
        }

        // Find related files in the project
        if let Some(current_file) = &state.current_file {
            let related_paths = self.find_related_files(current_file, &state.working_directory).await?;
            
            for path in related_paths {
                if !processed_files.contains(&path) && related_files.len() < self.config.max_files {
                    if let Some(file_context) = self.gather_file_context(&path, host, 0.6).await? {
                        related_files.push(file_context);
                        processed_files.insert(path);
                    }
                }
            }
        }

        // Sort by relevance
        related_files.sort_by(|a, b| b.relevance.partial_cmp(&a.relevance).unwrap_or(std::cmp::Ordering::Equal));

        // Limit to max files
        related_files.truncate(self.config.max_files);

        Ok(related_files)
    }

    /// Detect programming language from file extension
    fn detect_language(&self, path: &Path) -> Option<String> {
        path.extension()
            .and_then(|ext| ext.to_str())
            .map(|ext| match ext {
                "rs" => "rust",
                "py" => "python",
                "js" => "javascript",
                "ts" => "typescript",
                "go" => "go",
                "java" => "java",
                "c" => "c",
                "cpp" | "cc" | "cxx" => "cpp",
                "cs" => "csharp",
                "html" => "html",
                "css" => "css",
                "json" => "json",
                "yaml" | "yml" => "yaml",
                "toml" => "toml",
                "md" => "markdown",
                _ => ext,
            })
            .map(|s| s.to_string())
    }

    /// Extract selected text from content
    fn extract_selection_text(&self, content: &str, range: &Range) -> Option<String> {
        let lines: Vec<&str> = content.lines().collect();
        
        if range.start.line == range.end.line {
            // Single line selection
            if let Some(line) = lines.get((range.start.line as usize).saturating_sub(1)) {
                let start_col = (range.start.character as usize).saturating_sub(1);
                let end_col = (range.end.character as usize).min(line.len());
                if start_col < end_col {
                    return Some(line[start_col..end_col].to_string());
                }
            }
        } else {
            // Multi-line selection
            let start_line_idx = (range.start.line as usize).saturating_sub(1);
            let end_line_idx = (range.end.line as usize).saturating_sub(1);
            
            if start_line_idx < lines.len() && end_line_idx < lines.len() {
                let mut selected_text = String::new();
                
                for (i, line) in lines[start_line_idx..=end_line_idx].iter().enumerate() {
                    if i == 0 {
                        // First line
                        let start_col = (range.start.character as usize).saturating_sub(1);
                        if start_col < line.len() {
                            selected_text.push_str(&line[start_col..]);
                        }
                    } else if i == end_line_idx - start_line_idx {
                        // Last line
                        let end_col = (range.end.character as usize).min(line.len());
                        selected_text.push_str(&line[..end_col]);
                    } else {
                        // Middle lines
                        selected_text.push_str(line);
                    }
                    
                    if i < end_line_idx - start_line_idx {
                        selected_text.push('\n');
                    }
                }
                
                return Some(selected_text);
            }
        }
        
        None
    }

    /// Detect current function and class scope (simple heuristic)
    fn detect_current_scope(&self, lines: &[&str], cursor_line: usize) -> (Option<String>, Option<String>) {
        let mut current_function = None;
        let mut current_class = None;

        // Look backwards from cursor to find function/class definitions
        for i in (0..=cursor_line.min(lines.len().saturating_sub(1))).rev() {
            let line = lines[i].trim();
            
            // Rust function detection
            if line.starts_with("fn ") && current_function.is_none() {
                if let Some(name) = line.split_whitespace().nth(1) {
                    current_function = Some(name.split('(').next().unwrap_or(name).to_string());
                }
            }
            
            // Rust struct/impl detection
            if (line.starts_with("struct ") || line.starts_with("impl ")) && current_class.is_none() {
                if let Some(name) = line.split_whitespace().nth(1) {
                    current_class = Some(name.split('<').next().unwrap_or(name).to_string());
                }
            }
            
            // Python function detection
            if line.starts_with("def ") && current_function.is_none() {
                if let Some(name) = line.split_whitespace().nth(1) {
                    current_function = Some(name.split('(').next().unwrap_or(name).to_string());
                }
            }
            
            // Python class detection
            if line.starts_with("class ") && current_class.is_none() {
                if let Some(name) = line.split_whitespace().nth(1) {
                    current_class = Some(name.split('(').next().unwrap_or(name).split(':').next().unwrap_or(name).to_string());
                }
            }
        }

        (current_function, current_class)
    }

    /// Find files related to the current file
    async fn find_related_files(&self, current_file: &Path, project_root: &Path) -> Result<Vec<PathBuf>, CoderLibError> {
        let mut related_files = Vec::new();

        // Get the directory of the current file
        if let Some(current_dir) = current_file.parent() {
            // Look for files in the same directory
            if let Ok(entries) = fs::read_dir(current_dir).await {
                let mut entries = entries;
                while let Some(entry) = entries.next_entry().await.unwrap_or(None) {
                    let path = entry.path();
                    if path.is_file() && path != current_file {
                        if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
                            if self.config.priority_extensions.contains(&ext.to_string()) {
                                related_files.push(path);
                            }
                        }
                    }
                }
            }
        }

        // Look for test files
        if let Some(test_file) = self.find_test_file(current_file, project_root).await {
            related_files.push(test_file);
        }

        // Look for module files (for Rust)
        if current_file.extension().and_then(|e| e.to_str()) == Some("rs") {
            if let Some(mod_file) = self.find_module_file(current_file, project_root).await {
                related_files.push(mod_file);
            }
        }

        Ok(related_files)
    }

    /// Find test file for the current file
    async fn find_test_file(&self, current_file: &Path, project_root: &Path) -> Option<PathBuf> {
        let file_stem = current_file.file_stem()?.to_str()?;
        let extension = current_file.extension()?.to_str()?;

        // Common test file patterns
        let test_patterns = vec![
            format!("{}_test.{}", file_stem, extension),
            format!("test_{}.{}", file_stem, extension),
            format!("{}.test.{}", file_stem, extension),
        ];

        // Look in the same directory
        if let Some(current_dir) = current_file.parent() {
            for pattern in &test_patterns {
                let test_path = current_dir.join(pattern);
                if test_path.exists() {
                    return Some(test_path);
                }
            }
        }

        // Look in tests directory
        let tests_dir = project_root.join("tests");
        if tests_dir.exists() {
            for pattern in &test_patterns {
                let test_path = tests_dir.join(pattern);
                if test_path.exists() {
                    return Some(test_path);
                }
            }
        }

        None
    }

    /// Find module file for Rust files
    async fn find_module_file(&self, current_file: &Path, _project_root: &Path) -> Option<PathBuf> {
        if let Some(current_dir) = current_file.parent() {
            let mod_rs = current_dir.join("mod.rs");
            if mod_rs.exists() {
                return Some(mod_rs);
            }

            let lib_rs = current_dir.join("lib.rs");
            if lib_rs.exists() {
                return Some(lib_rs);
            }

            let main_rs = current_dir.join("main.rs");
            if main_rs.exists() {
                return Some(main_rs);
            }
        }

        None
    }

    /// Gather project structure information
    async fn gather_project_structure(&self, project_root: &Path) -> Result<Option<ProjectStructure>, CoderLibError> {
        if !project_root.exists() {
            return Ok(None);
        }

        let project_type = self.detect_project_type(project_root).await;
        let important_files = self.find_important_files(project_root).await?;
        let (directories, file_counts) = self.analyze_directory_structure(project_root).await?;

        Ok(Some(ProjectStructure {
            root: project_root.to_path_buf(),
            project_type,
            important_files,
            directories,
            file_counts,
        }))
    }

    /// Detect project type based on files present
    async fn detect_project_type(&self, project_root: &Path) -> Option<String> {
        if project_root.join("Cargo.toml").exists() {
            Some("rust".to_string())
        } else if project_root.join("package.json").exists() {
            Some("node".to_string())
        } else if project_root.join("requirements.txt").exists() || project_root.join("pyproject.toml").exists() {
            Some("python".to_string())
        } else if project_root.join("go.mod").exists() {
            Some("go".to_string())
        } else if project_root.join("pom.xml").exists() || project_root.join("build.gradle").exists() {
            Some("java".to_string())
        } else if project_root.join("Makefile").exists() {
            Some("c/cpp".to_string())
        } else {
            None
        }
    }

    /// Find important project files
    async fn find_important_files(&self, project_root: &Path) -> Result<Vec<PathBuf>, CoderLibError> {
        let important_names = vec![
            "README.md", "README.txt", "README",
            "Cargo.toml", "package.json", "requirements.txt", "pyproject.toml",
            "go.mod", "pom.xml", "build.gradle", "Makefile",
            "LICENSE", "LICENSE.txt", "LICENSE.md",
            ".gitignore", "Dockerfile", "docker-compose.yml",
        ];

        let mut important_files = Vec::new();
        for name in important_names {
            let path = project_root.join(name);
            if path.exists() {
                important_files.push(path);
            }
        }

        Ok(important_files)
    }

    /// Analyze directory structure
    async fn analyze_directory_structure(&self, project_root: &Path) -> Result<(Vec<String>, HashMap<String, usize>), CoderLibError> {
        let mut directories = Vec::new();
        let mut file_counts = HashMap::new();

        self.walk_directory(project_root, project_root, &mut directories, &mut file_counts, 0).await?;

        Ok((directories, file_counts))
    }

    /// Recursively walk directory structure
    fn walk_directory<'a>(
        &'a self,
        current_dir: &'a Path,
        project_root: &'a Path,
        directories: &'a mut Vec<String>,
        file_counts: &'a mut HashMap<String, usize>,
        depth: usize,
    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<(), CoderLibError>> + 'a>> {
        Box::pin(async move {
            if depth > 3 {
                return Ok(()); // Limit recursion depth
            }

            if let Ok(mut entries) = fs::read_dir(current_dir).await {
                while let Some(entry) = entries.next_entry().await.unwrap_or(None) {
                    let path = entry.path();
                    let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");

                    // Skip excluded directories
                    if self.config.exclude_directories.contains(&name.to_string()) {
                        continue;
                    }

                    if path.is_dir() {
                        if let Ok(relative_path) = path.strip_prefix(project_root) {
                            directories.push(relative_path.display().to_string());
                        }
                        self.walk_directory(&path, project_root, directories, file_counts, depth + 1).await?;
                    } else if path.is_file() {
                        if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
                            *file_counts.entry(ext.to_string()).or_insert(0) += 1;
                        }
                    }
                }
            }

            Ok(())
        })
    }

    /// Gather git context information
    async fn gather_git_context(&self, project_root: &Path, current_file: &Option<PathBuf>) -> Result<Option<GitContext>, CoderLibError> {
        if let Some(git_tool) = &self.git_tool {
            // This is a simplified version - in a real implementation,
            // we would use the git_tool to get actual git information
            debug!("Would gather git context for project: {}", project_root.display());

            // Placeholder git context
            Ok(Some(GitContext {
                branch: "main".to_string(),
                recent_commits: vec![
                    "feat: add new feature".to_string(),
                    "fix: resolve bug in parser".to_string(),
                    "docs: update README".to_string(),
                ],
                modified_files: vec![],
                blame_info: None,
            }))
        } else {
            Ok(None)
        }
    }

    /// Gather code analysis context
    async fn gather_code_analysis_context(&self, current_file: &Path, host: &dyn HostIntegration) -> Result<Option<CodeAnalysisContext>, CoderLibError> {
        if let Some(_code_analysis_tool) = &self.code_analysis_tool {
            // This is a simplified version - in a real implementation,
            // we would use the code_analysis_tool to get actual analysis
            debug!("Would analyze code for file: {}", current_file.display());

            // Placeholder analysis context
            Ok(Some(CodeAnalysisContext {
                complexity: Some("Cyclomatic complexity: 5, Cognitive complexity: 3".to_string()),
                security_issues: vec![],
                quality_metrics: Some("Maintainability index: 85, Documentation ratio: 15%".to_string()),
            }))
        } else {
            Ok(None)
        }
    }

    /// Calculate total context size
    fn calculate_context_size(&self, context: &GatheredContext) -> usize {
        let mut size = 0;

        if let Some(current_file) = &context.current_file {
            size += current_file.content.len();
        }

        for file in &context.related_files {
            size += file.content.len();
        }

        if let Some(cursor_context) = &context.cursor_context {
            size += cursor_context.surrounding_text.len();
            if let Some(selection) = &cursor_context.selection {
                size += selection.len();
            }
        }

        size
    }

    /// Trim context to fit within size limits
    fn trim_context(&self, context: &mut GatheredContext) {
        // Remove least relevant files first
        context.related_files.sort_by(|a, b| a.relevance.partial_cmp(&b.relevance).unwrap_or(std::cmp::Ordering::Equal));

        while context.total_size > self.config.max_context_size && !context.related_files.is_empty() {
            if let Some(removed_file) = context.related_files.pop() {
                context.total_size -= removed_file.content.len();
            }
        }

        // Recalculate size
        context.total_size = self.calculate_context_size(context);
    }

    /// Format context for AI consumption
    pub fn format_context_for_ai(&self, context: &GatheredContext) -> String {
        let mut formatted = String::new();

        // Add current file context
        if let Some(current_file) = &context.current_file {
            formatted.push_str(&format!("## Current File: {}\n", current_file.path.display()));
            if let Some(language) = &current_file.language {
                formatted.push_str(&format!("Language: {}\n", language));
            }
            formatted.push_str("```\n");
            formatted.push_str(&current_file.content);
            formatted.push_str("\n```\n\n");
        }

        // Add cursor context
        if let Some(cursor_context) = &context.cursor_context {
            formatted.push_str(&format!("## Cursor Position: Line {}, Column {}\n",
                cursor_context.position.line, cursor_context.position.character));

            if let Some(function) = &cursor_context.current_function {
                formatted.push_str(&format!("Current function: {}\n", function));
            }

            if let Some(class) = &cursor_context.current_class {
                formatted.push_str(&format!("Current class/struct: {}\n", class));
            }

            if let Some(selection) = &cursor_context.selection {
                formatted.push_str(&format!("Selected text:\n```\n{}\n```\n", selection));
            }

            formatted.push_str(&format!("Context around cursor:\n```\n{}\n```\n\n", cursor_context.surrounding_text));
        }

        // Add related files
        if !context.related_files.is_empty() {
            formatted.push_str("## Related Files:\n");
            for file in &context.related_files {
                formatted.push_str(&format!("### {}\n", file.path.display()));
                if file.truncated {
                    formatted.push_str("(Content truncated)\n");
                }
                formatted.push_str("```\n");
                formatted.push_str(&file.content);
                formatted.push_str("\n```\n\n");
            }
        }

        // Add project structure
        if let Some(project_structure) = &context.project_structure {
            formatted.push_str("## Project Structure:\n");
            if let Some(project_type) = &project_structure.project_type {
                formatted.push_str(&format!("Project type: {}\n", project_type));
            }
            formatted.push_str(&format!("Root: {}\n", project_structure.root.display()));

            if !project_structure.important_files.is_empty() {
                formatted.push_str("Important files:\n");
                for file in &project_structure.important_files {
                    formatted.push_str(&format!("- {}\n", file.display()));
                }
            }
            formatted.push_str("\n");
        }

        // Add git context
        if let Some(git_info) = &context.git_info {
            formatted.push_str("## Git Information:\n");
            formatted.push_str(&format!("Branch: {}\n", git_info.branch));

            if !git_info.recent_commits.is_empty() {
                formatted.push_str("Recent commits:\n");
                for commit in &git_info.recent_commits {
                    formatted.push_str(&format!("- {}\n", commit));
                }
            }

            if !git_info.modified_files.is_empty() {
                formatted.push_str("Modified files:\n");
                for file in &git_info.modified_files {
                    formatted.push_str(&format!("- {}\n", file.display()));
                }
            }
            formatted.push_str("\n");
        }

        // Add code analysis
        if let Some(code_analysis) = &context.code_analysis {
            formatted.push_str("## Code Analysis:\n");

            if let Some(complexity) = &code_analysis.complexity {
                formatted.push_str(&format!("Complexity: {}\n", complexity));
            }

            if let Some(quality) = &code_analysis.quality_metrics {
                formatted.push_str(&format!("Quality metrics: {}\n", quality));
            }

            if !code_analysis.security_issues.is_empty() {
                formatted.push_str("Security issues:\n");
                for issue in &code_analysis.security_issues {
                    formatted.push_str(&format!("- {}\n", issue));
                }
            }
            formatted.push_str("\n");
        }

        formatted
    }
}