# Code Review Extension

Automatic code quality review system for neoCoder SDK.

## Features

- 🔴 **5 critical rules** - syntax, security, error handling
- 🟡 **5 important rules** - style, duplication, complexity, dead code
- 🟢 **4 nice-to-have rules** - type hints, performance
- 📊 **Code metrics** - LOC, complexity, duplication
- 🎯 **Score 0-100** - overall quality score
- 💡 **Recommendations** - specific improvement suggestions

## Quick Start

### 1. Usage with CCA Agent

```python
from neoCoder.nca import NeoCoderAgent

# Code review is enabled by default
agent = NeoCoderAgent()

# Agent can call review_code automatically
result = agent.run("Review the code in my_file.py")
```

### 2. Standalone Usage

```python
from neoCoder.sdk.extensions.code_review import CodeReviewExtension

extension = CodeReviewExtension()
result = extension.review_code("path/to/file.py")

# Output results
print(extension.reporter.format_result(result))
```

### 3. With Custom Configuration

```python
from pathlib import Path
from neoCoder.sdk.extensions.code_review import (
    CodeReviewExtension,
    CodeReviewConfig
)

config = CodeReviewConfig.from_file(Path(".kiro/code-review-rules.json"))
extension = CodeReviewExtension(config)
```

## Configuration

Create a file `.kiro/code-review-rules.json`:

```json
{
  "enabled": true,
  "auto_review_on_write": true,
  "blocking_mode": false,
  "languages": {
    "python": {
      "enabled": true,
      "style_guide": "pep8",
      "max_complexity": 10,
      "min_score": 70
    }
  },
  "rules": {
    "critical": {
      "no-syntax-errors": true,
      "no-hardcoded-secrets": true,
      "error-handling-present": true,
      "no-sql-injection": true,
      "no-eval-exec": true
    },
    "important": {
      "follows-style-guide": true,
      "no-code-duplication": true,
      "complexity-acceptable": true,
      "no-dead-code": true,
      "no-magic-numbers": true
    },
    "nice_to_have": {
      "has-type-hints": false,
      "performance-optimized": false,
      "consistent-formatting": false,
      "logging-present": false
    }
  },
  "ignore_patterns": [
    "**/__pycache__/**",
    "**/node_modules/**",
    "**/*.test.py"
  ]
}
```

## Check Rules

### 🔴 Critical (MUST FIX)

1. **no-syntax-errors** - Code compiles without errors
2. **no-hardcoded-secrets** - No hardcoded passwords/tokens
3. **error-handling-present** - Error handling in critical places
4. **no-sql-injection** - No SQL injection vulnerabilities
5. **no-eval-exec** - No eval()/exec() usage

### 🟡 Important (SHOULD FIX)

6. **follows-style-guide** - PEP8/ESLint compliance
7. **no-code-duplication** - No code duplication (>10 lines)
8. **complexity-acceptable** - Cyclomatic complexity < 10
9. **no-dead-code** - No unused code/imports
10. **no-magic-numbers** - No magic numbers

### 🟢 Nice to Have

11. **has-type-hints** - Type hints present
12. **performance-optimized** - No O(n²) loops
13. **consistent-formatting** - Consistent formatting
14. **logging-present** - Logging present

## Example Output

```
╔══════════════════════════════════════════════════════════╗
║                  CODE REVIEW RESULTS                     ║
╚══════════════════════════════════════════════════════════╝

📁 File: my_file.py
📊 Score: 75/100 (Fair)

🔴 CRITICAL ISSUES (1)
  ❌ No Hardcoded Secrets (line 5)
     Hardcoded password
     Fix: Use environment variables or secure configuration

🟡 IMPORTANT ISSUES (2)
  ❌ No Dead Code (line 2)
     Unused import: os
     Fix: Remove unused import
  
  ❌ No Magic Numbers (line 25)
     Magic number 86400 without explanation
     Fix: Use named constant: SECONDS_IN_DAY = 86400

📈 METRICS
  Lines of Code: 234
  Functions: 12
  Classes: 3
  Cyclomatic Complexity: 8.5 (avg), 12 (max)

💡 RECOMMENDATIONS
  1. Fix No Hardcoded Secrets issue
  2. Remove unused imports
  3. Replace magic numbers with constants
```

## API Reference

### CodeReviewExtension

```python
class CodeReviewExtension(Extension):
    def __init__(self, config: CodeReviewConfig | None = None)
    
    def review_code(
        self,
        file_path: str,
        rules: list[str] | None = None,
        auto_fix: bool = False
    ) -> ReviewResult
```

### ReviewResult

```python
@dataclass
class ReviewResult:
    file_path: str
    score: int  # 0-100
    issues: List[Issue]
    metrics: CodeMetrics | None
    recommendations: List[str]
    
    def get_issues_by_priority(self, priority: Priority) -> List[Issue]
    def has_critical_issues(self) -> bool
    def get_summary(self) -> str
```

### Issue

```python
@dataclass
class Issue:
    rule_id: str
    rule_name: str
    priority: Priority  # CRITICAL, IMPORTANT, NICE_TO_HAVE
    category: Category  # SYNTAX, SECURITY, STYLE, etc.
    message: str
    line: int | None
    fix_suggestion: str | None
```

## Extension

### Adding a Custom Rule

```python
from neoCoder.sdk.extensions.code_review import Rule, RuleContext, Issue

def check_my_rule(ctx: RuleContext) -> List[Issue]:
    issues = []
    # Your check logic
    if "bad_pattern" in ctx.content:
        issues.append(Issue(
            rule_id="my-custom-rule",
            rule_name="My Custom Rule",
            priority=Priority.IMPORTANT,
            category=Category.BEST_PRACTICES,
            message="Found bad pattern",
            fix_suggestion="Use good pattern instead"
        ))
    return issues

# Register rule
extension = CodeReviewExtension()
extension.rule_engine.register_rule(Rule(
    id="my-custom-rule",
    name="My Custom Rule",
    priority=Priority.IMPORTANT,
    category=Category.BEST_PRACTICES,
    check=check_my_rule
))
```

## Performance

- **Caching**: Results are cached by default
- **Speed**: ~100-500ms for typical file (< 500 LOC)
- **Memory**: Minimal usage thanks to AST parsing

## Supported Languages

- ✅ **Python** - full support (AST parsing, all rules)
- 🟡 **JavaScript/TypeScript** - basic support (metrics)
- ⏳ **Other languages** - planned (Go, Rust, Java)

## Troubleshooting

### Problem: Extension not loading

```python
# Check that extension is enabled
agent = NeoCoderAgent(enable_code_review=True)
```

### Problem: Configuration not applying

```python
# Make sure file exists
from pathlib import Path
config_path = Path(".kiro/code-review-rules.json")
print(f"Config exists: {config_path.exists()}")
```

### Problem: Too many false positives

```json
// Disable strict rules
{
  "rules": {
    "nice_to_have": {
      "has-type-hints": false,
      "performance-optimized": false
    }
  }
}
```

## License

Part of neoCoder SDK. See LICENSE in project root.

## Contributing

Welcome:
- New check rules
- Support for new languages
- Improving existing rules
- Performance optimization

## Changelog

### v1.0.0 (2024)
- ✅ First release
- ✅ 14 check rules
- ✅ Python support
- ✅ CCA integration
- ✅ JSON configuration
