"""AI boilerplate detection rule.

This module provides rules to detect AI boilerplate and
template code in source files.
"""

from __future__ import annotations

import re
from pathlib import Path
from typing import List

from prefact.config import Config
from prefact.models import Fix, Issue, Severity, ValidationResult
from prefact.rules import BaseRule, register


@register
class AIBoilerplateRule(BaseRule):
    """Detect AI boilerplate and template code."""
    
    rule_id = "ai-boilerplate"
    description = "Detect AI boilerplate and template code"
    
    def scan_file(self, path: Path, source: str) -> List[Issue]:
        issues = []
        
        # Check for common AI boilerplate
        boilerplate_patterns = [
            (r"# (Copyright|License|MIT)", "boilerplate copyright"),
            (r"# Author: .*(AI|ChatGPT|Claude|Bard)", "AI author attribution"),
            (r"# Generated by .*AI", "AI generation attribution"),
            (r"def main\(\):", "standalone main function"),
            (r"if __name__ == ['\"]__main__['\"]:", "module execution block"),
        ]
        
        lines = source.splitlines()
        for line_num, line in enumerate(lines, 1):
            for pattern, message in boilerplate_patterns:
                if re.search(pattern, line, re.IGNORECASE):
                    issues.append(Issue(
                        rule_id=self.rule_id,
                        file=path,
                        line=line_num,
                        col=0,
                        message=message,
                        severity=Severity.INFO,
                        original=line.strip()
                    ))
        
        return issues
    
    def fix(self, path: Path, source: str, issues: List[Issue]) -> tuple[str, List[Fix]]:
        # Boilerplate removal requires manual decision
        return source, []
    
    def validate(self, path: Path, original: str, fixed: str) -> ValidationResult:
        issues = self.scan_file(path, fixed)
        
        return ValidationResult(
            file=path,
            passed=len(issues) == 0,
            checks=["no_boilerplate"] if not issues else [],
            errors=[f"Still has {len(issues)} boilerplate"] if issues else []
        )
