agentis-ctx 0.2.1

Fast CLI tool that generates AI-ready context from your codebase, with built-in code intelligence
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
//! Code quality audit module.
//!
//! Provides automated code quality analysis with scoring for CI integration.
//! Analyzes complexity, duplication potential, documentation coverage,
//! modularity, and naming conventions.
//!
//! Supports incremental mode for pre-commit hooks, auditing only changed files.

use std::collections::HashSet;
use std::path::PathBuf;
use std::process::Command;

use serde::{Deserialize, Serialize};

use crate::analytics::Analytics;
use crate::db::models::{Symbol, Visibility};
use crate::db::Database;
use crate::error::{CtxError, Result};

/// Configuration for audit analysis.
#[derive(Debug, Clone)]
pub struct AuditConfig {
    /// Categories to analyze (empty = all)
    pub categories: Vec<String>,
    /// Path to audit
    pub path: PathBuf,
    /// Only audit changed files
    pub incremental: bool,
    /// Minimum score threshold
    pub min_score: Option<f32>,
}

impl Default for AuditConfig {
    fn default() -> Self {
        Self {
            categories: vec![
                "complexity".to_string(),
                "duplication".to_string(),
                "coverage".to_string(),
                "modularity".to_string(),
                "naming".to_string(),
            ],
            path: PathBuf::from("."),
            incremental: false,
            min_score: None,
        }
    }
}

/// Severity level for quality issues.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Severity {
    Critical,
    Warning,
    Info,
}

impl Severity {
    pub fn as_str(&self) -> &'static str {
        match self {
            Severity::Critical => "critical",
            Severity::Warning => "warning",
            Severity::Info => "info",
        }
    }
}

impl std::fmt::Display for Severity {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

/// A quality issue found during audit.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QualityIssue {
    /// Severity level
    pub severity: Severity,
    /// Category this issue belongs to
    pub category: String,
    /// File path where issue was found
    pub file: String,
    /// Line number (if applicable)
    pub line: Option<u32>,
    /// Issue description
    pub message: String,
    /// Suggested fix (if applicable)
    pub suggestion: Option<String>,
}

/// Score for a single category.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CategoryScore {
    /// Category name
    pub name: String,
    /// Score (0.0-10.0)
    pub score: f32,
    /// Number of issues found
    pub issue_count: usize,
    /// Weight for overall calculation
    pub weight: f32,
}

/// Complete quality report.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QualityReport {
    /// Overall score (0.0-10.0)
    pub overall_score: f32,
    /// Whether the audit passed (score >= threshold)
    pub passed: bool,
    /// Score threshold (if specified)
    pub threshold: Option<f32>,
    /// Scores by category
    pub categories: Vec<CategoryScore>,
    /// Issues found
    pub issues: Vec<QualityIssue>,
    /// Total symbol count
    pub total_symbols: usize,
    /// Total function count
    pub total_functions: usize,
}

impl QualityReport {
    /// Create a new empty report.
    pub fn new() -> Self {
        Self {
            overall_score: 0.0,
            passed: true,
            threshold: None,
            categories: Vec::new(),
            issues: Vec::new(),
            total_symbols: 0,
            total_functions: 0,
        }
    }

    /// Add a category score.
    pub fn add_category(&mut self, score: CategoryScore) {
        self.categories.push(score);
    }

    /// Add an issue.
    pub fn add_issue(&mut self, issue: QualityIssue) {
        self.issues.push(issue);
    }

    /// Calculate the overall score from category scores.
    pub fn calculate_overall(&mut self) {
        let total_weight: f32 = self.categories.iter().map(|c| c.weight).sum();
        if total_weight > 0.0 {
            let weighted_sum: f32 = self.categories.iter().map(|c| c.score * c.weight).sum();
            self.overall_score = weighted_sum / total_weight;
        }

        // Check threshold
        if let Some(threshold) = self.threshold {
            self.passed = self.overall_score >= threshold;
        }
    }

    /// Get issues by severity.
    pub fn issues_by_severity(&self, severity: Severity) -> Vec<&QualityIssue> {
        self.issues
            .iter()
            .filter(|i| i.severity == severity)
            .collect()
    }

    /// Format as text output.
    pub fn format_text(&self) -> String {
        let mut output = String::new();

        output.push_str("Code Quality Audit\n");
        output.push_str("==================\n\n");

        output.push_str(&format!("Overall Score: {:.1}/10\n\n", self.overall_score));

        // Categories
        output.push_str("Categories:\n");
        for cat in &self.categories {
            output.push_str(&format!(
                "  {:12} {:.1}/10  ({} issues)\n",
                format!("{}:", capitalize(&cat.name)),
                cat.score,
                cat.issue_count
            ));
        }
        output.push('\n');

        // Critical issues
        let critical = self.issues_by_severity(Severity::Critical);
        if !critical.is_empty() {
            output.push_str(&format!("Critical Issues ({}):\n", critical.len()));
            for issue in critical.iter().take(5) {
                if let Some(line) = issue.line {
                    output.push_str(&format!(
                        "  [CRIT] {}:{} - {}\n",
                        issue.file, line, issue.message
                    ));
                } else {
                    output.push_str(&format!("  [CRIT] {} - {}\n", issue.file, issue.message));
                }
            }
            if critical.len() > 5 {
                output.push_str(&format!("  ... and {} more\n", critical.len() - 5));
            }
            output.push('\n');
        }

        // Warnings
        let warnings = self.issues_by_severity(Severity::Warning);
        if !warnings.is_empty() {
            output.push_str(&format!("Warnings ({}):\n", warnings.len()));
            for issue in warnings.iter().take(5) {
                if let Some(line) = issue.line {
                    output.push_str(&format!(
                        "  [WARN] {}:{} - {}\n",
                        issue.file, line, issue.message
                    ));
                } else {
                    output.push_str(&format!("  [WARN] {} - {}\n", issue.file, issue.message));
                }
            }
            if warnings.len() > 5 {
                output.push_str(&format!("  ... and {} more\n", warnings.len() - 5));
            }
            output.push('\n');
        }

        // Threshold result
        if let Some(threshold) = self.threshold {
            if self.passed {
                output.push_str(&format!(
                    "✓ Score {:.1} meets threshold {:.1}\n",
                    self.overall_score, threshold
                ));
            } else {
                output.push_str(&format!(
                    "✗ Score {:.1} below threshold {:.1}\n",
                    self.overall_score, threshold
                ));
            }
        }

        output
    }

    /// Format as markdown output.
    pub fn format_markdown(&self) -> String {
        let mut output = String::new();

        output.push_str("# Code Quality Audit\n\n");

        // Summary
        output.push_str(&format!(
            "**Overall Score: {:.1}/10**\n\n",
            self.overall_score
        ));

        if let Some(threshold) = self.threshold {
            if self.passed {
                output.push_str(&format!("✅ Passed (threshold: {:.1})\n\n", threshold));
            } else {
                output.push_str(&format!("❌ Failed (threshold: {:.1})\n\n", threshold));
            }
        }

        // Categories table
        output.push_str("## Categories\n\n");
        output.push_str("| Category | Score | Issues | Weight |\n");
        output.push_str("|----------|-------|--------|--------|\n");
        for cat in &self.categories {
            output.push_str(&format!(
                "| {} | {:.1}/10 | {} | {:.0}% |\n",
                capitalize(&cat.name),
                cat.score,
                cat.issue_count,
                cat.weight * 100.0
            ));
        }
        output.push('\n');

        // Issues by severity
        let critical = self.issues_by_severity(Severity::Critical);
        if !critical.is_empty() {
            output.push_str("## Critical Issues\n\n");
            for issue in &critical {
                if let Some(line) = issue.line {
                    output.push_str(&format!(
                        "- **{}:{}** - {}\n",
                        issue.file, line, issue.message
                    ));
                } else {
                    output.push_str(&format!("- **{}** - {}\n", issue.file, issue.message));
                }
                if let Some(ref suggestion) = issue.suggestion {
                    output.push_str(&format!("  - *Suggestion: {}*\n", suggestion));
                }
            }
            output.push('\n');
        }

        let warnings = self.issues_by_severity(Severity::Warning);
        if !warnings.is_empty() {
            output.push_str("## Warnings\n\n");
            for issue in warnings.iter().take(20) {
                if let Some(line) = issue.line {
                    output.push_str(&format!(
                        "- **{}:{}** - {}\n",
                        issue.file, line, issue.message
                    ));
                } else {
                    output.push_str(&format!("- **{}** - {}\n", issue.file, issue.message));
                }
            }
            if warnings.len() > 20 {
                output.push_str(&format!(
                    "\n*... and {} more warnings*\n",
                    warnings.len() - 20
                ));
            }
            output.push('\n');
        }

        // Statistics
        output.push_str("## Statistics\n\n");
        output.push_str(&format!("- Total symbols: {}\n", self.total_symbols));
        output.push_str(&format!("- Total functions: {}\n", self.total_functions));
        output.push_str(&format!(
            "- Issues: {} critical, {} warnings\n",
            critical.len(),
            warnings.len()
        ));

        output
    }

    /// Format as JSON output.
    pub fn format_json(&self) -> Result<String> {
        Ok(serde_json::to_string_pretty(self)?)
    }
}

impl Default for QualityReport {
    fn default() -> Self {
        Self::new()
    }
}

/// Category weights for overall score calculation.
const WEIGHT_COMPLEXITY: f32 = 0.25;
const WEIGHT_DUPLICATION: f32 = 0.20;
const WEIGHT_COVERAGE: f32 = 0.20;
const WEIGHT_MODULARITY: f32 = 0.20;
const WEIGHT_NAMING: f32 = 0.15;

/// Threshold constants for quality scoring.
pub mod thresholds {
    /// Coverage thresholds for documentation scoring.
    pub const COVERAGE_EXCELLENT: f32 = 0.95;
    pub const COVERAGE_GOOD: f32 = 0.80;
    pub const COVERAGE_ACCEPTABLE: f32 = 0.60;
    pub const COVERAGE_POOR: f32 = 0.40;

    /// Naming violation rate thresholds.
    pub const NAMING_EXCELLENT: f32 = 0.01;
    pub const NAMING_GOOD: f32 = 0.05;
    pub const NAMING_ACCEPTABLE: f32 = 0.20;
    pub const NAMING_POOR: f32 = 0.40;

    /// Modularity thresholds.
    pub const HIGH_COUPLING_THRESHOLD: usize = 20;
    pub const EXTERNAL_RATIO_HIGH: f32 = 0.5;
    pub const EXTERNAL_RATIO_MEDIUM: f32 = 0.3;
}

/// Get changed files from git (staged and unstaged).
pub fn get_changed_files(root: &PathBuf) -> Result<HashSet<String>> {
    let mut changed_files = HashSet::new();

    // Get staged files
    let staged_output = Command::new("git")
        .args(["diff", "--cached", "--name-only"])
        .current_dir(root)
        .output()
        .map_err(|e| CtxError::git(format!("Failed to run git: {}", e)))?;

    if staged_output.status.success() {
        let output = String::from_utf8_lossy(&staged_output.stdout);
        for line in output.lines() {
            if !line.is_empty() {
                changed_files.insert(line.to_string());
            }
        }
    }

    // Get unstaged modified files
    let unstaged_output = Command::new("git")
        .args(["diff", "--name-only"])
        .current_dir(root)
        .output()
        .map_err(|e| CtxError::git(format!("Failed to run git: {}", e)))?;

    if unstaged_output.status.success() {
        let output = String::from_utf8_lossy(&unstaged_output.stdout);
        for line in output.lines() {
            if !line.is_empty() {
                changed_files.insert(line.to_string());
            }
        }
    }

    // Get untracked files
    let untracked_output = Command::new("git")
        .args(["ls-files", "--others", "--exclude-standard"])
        .current_dir(root)
        .output()
        .map_err(|e| CtxError::git(format!("Failed to run git: {}", e)))?;

    if untracked_output.status.success() {
        let output = String::from_utf8_lossy(&untracked_output.stdout);
        for line in output.lines() {
            if !line.is_empty() {
                changed_files.insert(line.to_string());
            }
        }
    }

    Ok(changed_files)
}

/// Run a complete quality audit.
pub fn run_audit(
    db: &Database,
    analytics: Option<&Analytics>,
    config: &AuditConfig,
) -> Result<QualityReport> {
    let mut report = QualityReport::new();
    report.threshold = config.min_score;

    // Get all symbols using a broad search
    // We use "%" pattern to get all symbols with a high limit
    let mut symbols = db.find_symbols("%", 100000)?;

    // If incremental mode, filter to only changed files
    if config.incremental {
        let changed_files = get_changed_files(&config.path)?;
        if changed_files.is_empty() {
            // No changes, return perfect score
            report.overall_score = 10.0;
            report.passed = true;
            return Ok(report);
        }

        // Filter symbols to only those in changed files
        symbols.retain(|s| {
            changed_files
                .iter()
                .any(|f| s.file_path.ends_with(f) || f.ends_with(&s.file_path))
        });
    }

    report.total_symbols = symbols.len();
    report.total_functions = symbols
        .iter()
        .filter(|s| s.kind.as_str() == "function" || s.kind.as_str() == "method")
        .count();

    let should_run = |cat: &str| -> bool {
        config.categories.is_empty() || config.categories.iter().any(|c| c == cat)
    };

    // Complexity analysis
    if should_run("complexity") {
        let (score, issues) = if let Some(a) = analytics {
            score_complexity(a, &symbols)?
        } else {
            (8.0, Vec::new()) // Default good score if no analytics
        };
        report.add_category(CategoryScore {
            name: "complexity".to_string(),
            score,
            issue_count: issues.len(),
            weight: WEIGHT_COMPLEXITY,
        });
        for issue in issues {
            report.add_issue(issue);
        }
    }

    // Duplication analysis (simplified - based on similar function names)
    if should_run("duplication") {
        let (score, issues) = score_duplication(&symbols);
        report.add_category(CategoryScore {
            name: "duplication".to_string(),
            score,
            issue_count: issues.len(),
            weight: WEIGHT_DUPLICATION,
        });
        for issue in issues {
            report.add_issue(issue);
        }
    }

    // Documentation coverage
    if should_run("coverage") {
        let (score, issues) = score_coverage(&symbols);
        report.add_category(CategoryScore {
            name: "coverage".to_string(),
            score,
            issue_count: issues.len(),
            weight: WEIGHT_COVERAGE,
        });
        for issue in issues {
            report.add_issue(issue);
        }
    }

    // Modularity analysis
    if should_run("modularity") {
        let (score, issues) = if let Some(a) = analytics {
            score_modularity(a)?
        } else {
            (8.0, Vec::new())
        };
        report.add_category(CategoryScore {
            name: "modularity".to_string(),
            score,
            issue_count: issues.len(),
            weight: WEIGHT_MODULARITY,
        });
        for issue in issues {
            report.add_issue(issue);
        }
    }

    // Naming conventions
    if should_run("naming") {
        let (score, issues) = score_naming(&symbols);
        report.add_category(CategoryScore {
            name: "naming".to_string(),
            score,
            issue_count: issues.len(),
            weight: WEIGHT_NAMING,
        });
        for issue in issues {
            report.add_issue(issue);
        }
    }

    report.calculate_overall();
    Ok(report)
}

/// Score complexity based on fan-out metrics.
fn score_complexity(
    analytics: &Analytics,
    _symbols: &[Symbol],
) -> Result<(f32, Vec<QualityIssue>)> {
    let mut issues = Vec::new();

    // Get complexity data from analytics
    let complexity_results = analytics.complexity_analysis(20)?;

    // Count high-complexity functions
    let critical_count = complexity_results
        .iter()
        .filter(|r| r.severity == "critical")
        .count();
    let high_count = complexity_results
        .iter()
        .filter(|r| r.severity == "high")
        .count();
    let medium_count = complexity_results
        .iter()
        .filter(|r| r.severity == "medium")
        .count();

    // Generate issues for high-complexity functions
    for result in complexity_results
        .iter()
        .filter(|r| r.severity == "critical" || r.severity == "high")
    {
        issues.push(QualityIssue {
            severity: if result.severity == "critical" {
                Severity::Critical
            } else {
                Severity::Warning
            },
            category: "complexity".to_string(),
            file: result.file_path.clone(),
            line: Some(result.line),
            message: format!(
                "{}: fan-out {} (threshold: 20)",
                result.name, result.fan_out
            ),
            suggestion: Some("Extract helper functions to reduce complexity".to_string()),
        });
    }

    // Calculate score
    let score = calculate_complexity_score(critical_count, high_count, medium_count);

    Ok((score, issues))
}

/// Calculate complexity score based on issue counts.
fn calculate_complexity_score(critical: usize, high: usize, medium: usize) -> f32 {
    // Score based on severity distribution
    if critical > 0 {
        // Critical issues significantly reduce score
        (4.0 - (critical as f32 * 0.5).min(3.0)).max(1.0)
    } else if high > 5 {
        5.0 - ((high - 5) as f32 * 0.2).min(2.0)
    } else if high > 0 {
        6.0 - (high as f32 * 0.2)
    } else if medium > 10 {
        7.0 - ((medium - 10) as f32 * 0.1).min(1.0)
    } else if medium > 0 {
        8.0 - (medium as f32 * 0.1)
    } else {
        10.0
    }
}

/// Score duplication by looking for similar function names.
fn score_duplication(symbols: &[Symbol]) -> (f32, Vec<QualityIssue>) {
    use std::collections::HashMap;

    let mut issues = Vec::new();
    let mut name_counts: HashMap<String, Vec<&Symbol>> = HashMap::new();

    // Group functions by simplified name (without numeric suffixes)
    for symbol in symbols
        .iter()
        .filter(|s| s.kind.as_str() == "function" || s.kind.as_str() == "method")
    {
        // Remove numeric suffixes like _1, _2, etc.
        let base_name = symbol
            .name
            .trim_end_matches(|c: char| c.is_ascii_digit() || c == '_')
            .to_string();
        if base_name.len() >= 4 {
            name_counts.entry(base_name).or_default().push(symbol);
        }
    }

    // Find potential duplicates (3+ similar names)
    let duplicates: Vec<_> = name_counts
        .iter()
        .filter(|(_, syms)| syms.len() >= 3)
        .collect();

    for (name, syms) in &duplicates {
        if syms.len() >= 5 {
            issues.push(QualityIssue {
                severity: Severity::Warning,
                category: "duplication".to_string(),
                file: syms[0].file_path.clone(),
                line: Some(syms[0].line_start),
                message: format!(
                    "Potential code duplication: {} functions with similar name '{}'",
                    syms.len(),
                    name
                ),
                suggestion: Some("Consider extracting shared logic".to_string()),
            });
        }
    }

    // Calculate score based on duplicate patterns
    let score = if duplicates.is_empty() {
        10.0
    } else if duplicates.len() <= 2 {
        8.0
    } else if duplicates.len() <= 5 {
        6.0
    } else {
        4.0
    };

    (score, issues)
}

/// Score documentation coverage for public symbols.
fn score_coverage(symbols: &[Symbol]) -> (f32, Vec<QualityIssue>) {
    let mut issues = Vec::new();

    // Only check public symbols
    let public_symbols: Vec<_> = symbols
        .iter()
        .filter(|s| s.visibility == Visibility::Public)
        .collect();

    if public_symbols.is_empty() {
        return (10.0, issues);
    }

    // Count documented symbols (have brief or docstring)
    let documented_count = public_symbols
        .iter()
        .filter(|s| s.brief.is_some() || s.docstring.is_some())
        .count();

    let coverage = documented_count as f32 / public_symbols.len() as f32;

    // Report undocumented public functions/methods (limit to avoid spam)
    for symbol in public_symbols
        .iter()
        .filter(|s| {
            s.brief.is_none()
                && s.docstring.is_none()
                && (s.kind.as_str() == "function" || s.kind.as_str() == "method")
        })
        .take(10)
    {
        issues.push(QualityIssue {
            severity: Severity::Info,
            category: "coverage".to_string(),
            file: symbol.file_path.clone(),
            line: Some(symbol.line_start),
            message: format!(
                "Undocumented public {}: {}",
                symbol.kind.as_str(),
                symbol.name
            ),
            suggestion: Some("Add documentation comment".to_string()),
        });
    }

    // Calculate score based on coverage percentage
    use thresholds::*;
    let score = if coverage >= COVERAGE_EXCELLENT {
        10.0
    } else if coverage >= COVERAGE_GOOD {
        8.0
    } else if coverage >= COVERAGE_ACCEPTABLE {
        6.0
    } else if coverage >= COVERAGE_POOR {
        4.0
    } else {
        2.0
    };

    (score, issues)
}

/// Score modularity based on file dependencies.
fn score_modularity(analytics: &Analytics) -> Result<(f32, Vec<QualityIssue>)> {
    let mut issues = Vec::new();

    // Get file dependencies
    let deps = analytics.file_dependencies()?;

    // Count cross-file dependencies
    let total_deps = deps.len();
    let external_deps = deps.iter().filter(|(_, t, _)| t == "external").count();

    // High external dependency ratio might indicate poor modularity
    let external_ratio = if total_deps > 0 {
        external_deps as f32 / total_deps as f32
    } else {
        0.0
    };

    // Look for files with too many outgoing dependencies
    use std::collections::HashMap;
    let mut file_dep_counts: HashMap<&str, usize> = HashMap::new();
    for (source, _, _) in &deps {
        *file_dep_counts.entry(source).or_default() += 1;
    }

    for (file, count) in file_dep_counts
        .iter()
        .filter(|(_, &c)| c > thresholds::HIGH_COUPLING_THRESHOLD)
    {
        issues.push(QualityIssue {
            severity: Severity::Warning,
            category: "modularity".to_string(),
            file: file.to_string(),
            line: None,
            message: format!("High coupling: {} outgoing dependencies", count),
            suggestion: Some("Consider splitting into smaller modules".to_string()),
        });
    }

    // Calculate score
    let score = if external_ratio > thresholds::EXTERNAL_RATIO_HIGH {
        5.0
    } else if external_ratio > thresholds::EXTERNAL_RATIO_MEDIUM {
        6.0
    } else if issues.is_empty() {
        9.0 - (external_ratio * 2.0)
    } else {
        7.0 - (issues.len() as f32 * 0.5).min(2.0)
    };

    Ok((score.clamp(2.0, 10.0), issues))
}

/// Score naming convention consistency.
fn score_naming(symbols: &[Symbol]) -> (f32, Vec<QualityIssue>) {
    let mut issues = Vec::new();
    let mut violations = 0;

    for symbol in symbols {
        let name = &symbol.name;

        // Check naming conventions based on kind
        let is_valid = match symbol.kind.as_str() {
            "function" | "method" => is_snake_case(name),
            "struct" | "enum" | "class" | "interface" | "type" => is_pascal_case(name),
            "constant" => is_screaming_snake_case(name) || is_snake_case(name),
            _ => true,
        };

        if !is_valid {
            violations += 1;
            if violations <= 10 {
                issues.push(QualityIssue {
                    severity: Severity::Info,
                    category: "naming".to_string(),
                    file: symbol.file_path.clone(),
                    line: Some(symbol.line_start),
                    message: format!(
                        "{} '{}' doesn't follow naming convention",
                        symbol.kind.as_str(),
                        name
                    ),
                    suggestion: Some(suggest_name_fix(symbol.kind.as_str(), name)),
                });
            }
        }
    }

    // Calculate score based on violation percentage
    let total = symbols.len();
    if total == 0 {
        return (10.0, issues);
    }

    let violation_rate = violations as f32 / total as f32;
    use thresholds::*;
    let score = if violation_rate <= NAMING_EXCELLENT {
        10.0
    } else if violation_rate <= NAMING_GOOD {
        8.0
    } else if violation_rate <= NAMING_ACCEPTABLE {
        6.0
    } else if violation_rate <= NAMING_POOR {
        4.0
    } else {
        2.0
    };

    (score, issues)
}

/// Check if a name is snake_case.
fn is_snake_case(name: &str) -> bool {
    if name.is_empty() {
        return true;
    }
    // Allow leading underscore for private
    let name = name.strip_prefix('_').unwrap_or(name);
    if name.is_empty() {
        return true;
    }

    // Must be lowercase with underscores
    name.chars()
        .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
}

/// Check if a name is PascalCase.
fn is_pascal_case(name: &str) -> bool {
    if name.is_empty() {
        return true;
    }
    // First char must be uppercase
    let first = name.chars().next().unwrap();
    if !first.is_ascii_uppercase() {
        return false;
    }
    // No underscores (except for generic params like T_1)
    !name.contains('_') || name.chars().filter(|&c| c == '_').count() <= 1
}

/// Check if a name is SCREAMING_SNAKE_CASE.
fn is_screaming_snake_case(name: &str) -> bool {
    if name.is_empty() {
        return true;
    }
    name.chars()
        .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')
}

/// Suggest a fix for a naming convention violation.
fn suggest_name_fix(kind: &str, name: &str) -> String {
    match kind {
        "function" | "method" => format!("Use snake_case: {}", to_snake_case(name)),
        "struct" | "enum" | "class" | "interface" | "type" => {
            format!("Use PascalCase: {}", to_pascal_case(name))
        }
        "constant" => format!("Use SCREAMING_SNAKE_CASE: {}", name.to_uppercase()),
        _ => "Follow language naming conventions".to_string(),
    }
}

/// Convert a name to snake_case.
fn to_snake_case(name: &str) -> String {
    let mut result = String::new();
    for (i, c) in name.chars().enumerate() {
        if c.is_ascii_uppercase() && i > 0 {
            result.push('_');
        }
        result.push(c.to_ascii_lowercase());
    }
    result
}

/// Convert a name to PascalCase.
fn to_pascal_case(name: &str) -> String {
    let mut result = String::new();
    let mut capitalize_next = true;
    for c in name.chars() {
        if c == '_' {
            capitalize_next = true;
        } else if capitalize_next {
            result.push(c.to_ascii_uppercase());
            capitalize_next = false;
        } else {
            result.push(c.to_ascii_lowercase());
        }
    }
    result
}

/// Capitalize the first letter of a string.
fn capitalize(s: &str) -> String {
    let mut chars = s.chars();
    match chars.next() {
        None => String::new(),
        Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_snake_case() {
        assert!(is_snake_case("hello_world"));
        assert!(is_snake_case("_private"));
        assert!(is_snake_case("simple"));
        assert!(!is_snake_case("HelloWorld"));
        assert!(!is_snake_case("helloWorld"));
    }

    #[test]
    fn test_pascal_case() {
        assert!(is_pascal_case("HelloWorld"));
        assert!(is_pascal_case("Simple"));
        assert!(!is_pascal_case("hello_world"));
        assert!(!is_pascal_case("helloWorld"));
    }

    #[test]
    fn test_screaming_snake_case() {
        assert!(is_screaming_snake_case("HELLO_WORLD"));
        assert!(is_screaming_snake_case("SIMPLE"));
        assert!(!is_screaming_snake_case("hello_world"));
        assert!(!is_screaming_snake_case("HelloWorld"));
    }

    #[test]
    fn test_quality_report_format() {
        let mut report = QualityReport::new();
        report.add_category(CategoryScore {
            name: "complexity".to_string(),
            score: 7.5,
            issue_count: 5,
            weight: 0.25,
        });
        report.add_category(CategoryScore {
            name: "coverage".to_string(),
            score: 8.0,
            issue_count: 3,
            weight: 0.20,
        });
        report.calculate_overall();

        let text = report.format_text();
        assert!(text.contains("Code Quality Audit"));
        assert!(text.contains("Complexity:"));
        assert!(text.contains("Coverage:"));
    }

    #[test]
    fn test_calculate_overall_score() {
        let mut report = QualityReport::new();
        report.add_category(CategoryScore {
            name: "test1".to_string(),
            score: 8.0,
            issue_count: 0,
            weight: 0.5,
        });
        report.add_category(CategoryScore {
            name: "test2".to_string(),
            score: 6.0,
            issue_count: 0,
            weight: 0.5,
        });
        report.calculate_overall();

        assert!((report.overall_score - 7.0).abs() < 0.01);
    }

    #[test]
    fn test_threshold_pass() {
        let mut report = QualityReport::new();
        report.threshold = Some(7.0);
        report.add_category(CategoryScore {
            name: "test".to_string(),
            score: 8.0,
            issue_count: 0,
            weight: 1.0,
        });
        report.calculate_overall();

        assert!(report.passed);
    }

    #[test]
    fn test_threshold_fail() {
        let mut report = QualityReport::new();
        report.threshold = Some(7.0);
        report.add_category(CategoryScore {
            name: "test".to_string(),
            score: 6.0,
            issue_count: 0,
            weight: 1.0,
        });
        report.calculate_overall();

        assert!(!report.passed);
    }

    #[test]
    fn test_audit_incremental_no_changes() {
        // Test that incremental audit with no changes returns a perfect score
        let mut report = QualityReport::new();
        report.overall_score = 10.0;
        report.passed = true;

        // Verify the report is valid
        assert_eq!(report.overall_score, 10.0);
        assert!(report.passed);
    }

    #[test]
    fn test_get_changed_files() {
        use std::fs;
        use tempfile::TempDir;

        // Create a temp git repo
        let temp_dir = TempDir::new().unwrap();
        let root = temp_dir.path().to_path_buf();

        // Initialize git repo
        Command::new("git")
            .args(["init"])
            .current_dir(&root)
            .output()
            .expect("Failed to init git");

        Command::new("git")
            .args(["config", "user.email", "test@test.com"])
            .current_dir(&root)
            .output()
            .expect("Failed to set git email");

        Command::new("git")
            .args(["config", "user.name", "Test"])
            .current_dir(&root)
            .output()
            .expect("Failed to set git name");

        // Create a file and commit it
        fs::write(root.join("test.rs"), "fn test() {}").unwrap();
        Command::new("git")
            .args(["add", "test.rs"])
            .current_dir(&root)
            .output()
            .expect("Failed to git add");
        Command::new("git")
            .args(["commit", "-m", "initial"])
            .current_dir(&root)
            .output()
            .expect("Failed to git commit");

        // Modify the file
        fs::write(root.join("test.rs"), "fn test() { println!(\"hello\"); }").unwrap();

        // Get changed files
        let changed = get_changed_files(&root).unwrap();

        // Should contain the modified file
        assert!(
            changed.contains("test.rs"),
            "Should find changed file: {:?}",
            changed
        );
    }
}