#!/usr/bin/env python3
"""
Code Quality Checks Module

Checks for common code quality issues like incorrect role usage.
"""

from pathlib import Path
import re
from typing import List, Tuple
from tests.utils.logger import Logger


class CodeQualityChecks:
    """Code quality checks for the project"""
    
    def __init__(self, logger: Logger, project_dir: str, version: str = "unknown"):
        self.logger = logger
        self.version = version
        self.project_dir = Path(project_dir)
        self.backend_dir = self.project_dir / 'backend'
    
    def check_role_usage(self) -> bool:
        """Check for incorrect role usage in Python files."""
        self.logger.subheader(f"Role Usage Check (v{self.version})")
        
        if not self.backend_dir.exists():
            self.logger.warning("CODE_QUALITY", f"Backend directory not found: {self.backend_dir}")
            return True
        
        issues = self._find_role_issues(str(self.backend_dir))
        
        if issues:
            self.logger.error("CODE_QUALITY", f"Found {len(issues)} role usage issues:")
            for file_path, line_num, line_content in issues:
                self.logger.error("CODE_QUALITY", f"  {file_path}:{line_num}")
                self.logger.error("CODE_QUALITY", f"    {line_content}")
            return False
        else:
            self.logger.success("CODE_QUALITY", "No role usage issues found")
            return True
    
    def _find_role_issues(self, directory: str) -> List[Tuple[str, int, str]]:
        """Find incorrect role usage in Python files."""
        issues = []
        
        # Patterns to search for
        pattern1 = re.compile(r'\.role\s*[!=]=\s*["\']')
        pattern2 = re.compile(r'\.role\s+(?:not\s+)?in\s+\[')
        
        for file_path in Path(directory).rglob('*.py'):
            # Skip __pycache__
            if '__pycache__' in str(file_path):
                continue
            
            try:
                with open(file_path, 'r', encoding='utf-8') as f:
                    for line_num, line in enumerate(f, 1):
                        # Skip comments
                        if '#' in line and line.strip().startswith('#'):
                            continue
                        
                        # Check for patterns
                        if pattern1.search(line) or pattern2.search(line):
                            # Check if .name is already present
                            if '.role.name' not in line:
                                issues.append((str(file_path), line_num, line.strip()))
            except Exception as e:
                self.logger.warning("CODE_QUALITY", f"Error reading {file_path}: {e}")
        
        return issues
    
    def run_all_checks(self) -> bool:
        """Run all code quality checks."""
        all_passed = True
        
        # Role usage check
        if not self.check_role_usage():
            all_passed = False
        
        return all_passed
