#!/usr/bin/env python3
"""
Test script to find incorrect role usage in Python files.
Finds patterns like `.role ==` or `.role !=` that should be `.role.name ==` or `.role.name !=`
"""

import os
import re
from pathlib import Path
from typing import List, Tuple

def find_role_issues(directory: str) -> List[Tuple[str, int, str]]:
    """
    Find incorrect role usage in Python files.
    
    Returns:
        List of tuples: (file_path, line_number, line_content)
    """
    issues = []
    
    # Patterns to search for
    # Pattern 1: .role == "string" or .role != "string"
    pattern1 = re.compile(r'\.role\s*[!=]=\s*["\']')
    # Pattern 2: .role in [...] or .role not in [...]
    pattern2 = re.compile(r'\.role\s+(?:not\s+)?in\s+\[')
    # Pattern 3: if current_user.role (without .name)
    pattern3 = re.compile(r'if\s+\w+\.role\s*[!=]=\s*["\']')
    
    for root, dirs, files in os.walk(directory):
        # Skip node_modules, __pycache__, etc.
        dirs[:] = [d for d in dirs if d not in ['node_modules', '__pycache__', '.git', 'venv', 'env']]
        
        for file in files:
            if file.endswith('.py'):
                file_path = Path(root) / file
                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:
                    print(f"Error reading {file_path}: {e}")
    
    return issues

def main():
    """Main function to run the test."""
    # Search in backend directory
    backend_dir = Path(__file__).parent.parent / 'backend'
    
    if not backend_dir.exists():
        print(f"Backend directory not found: {backend_dir}")
        return
    
    print("Searching for incorrect role usage in backend...")
    print("=" * 80)
    
    issues = find_role_issues(str(backend_dir))
    
    if issues:
        print(f"\nFound {len(issues)} potential issues:\n")
        for file_path, line_num, line_content in issues:
            print(f"{file_path}:{line_num}")
            print(f"  {line_content}")
            print()
    else:
        print("\nNo issues found!")
    
    print("=" * 80)
    
    # Exit with error code if issues found
    if issues:
        exit(1)
    else:
        exit(0)

if __name__ == "__main__":
    main()
