import re
import difflib
from .profanity_list import PROFANITY_LIST

class UsernameChecker:
    def __init__(self):
        self.profanity_list = PROFANITY_LIST

    def check_length(self, username, min_len=3, max_len=20):
        if len(username) < min_len:
            return False, f"Username too short (min {min_len})"
        if len(username) > max_len:
            return False, f"Username too long (max {max_len})"
        return True, "OK"

    def check_unsafe_chars(self, username, allowed_regex=r'^[a-zA-Z0-9_-]+$'):
        if not re.match(allowed_regex, username):
            return False, "Username contains unsafe characters"
        return True, "OK"

    def check_profanity(self, username):
        # Basic check: exact match or substring match
        # For a more robust check, we might want to normalize the username
        username_lower = username.lower()
        for word in self.profanity_list:
            if word in username_lower:
                return False, "Username contains profanity"
        return True, "OK"

    def check_similarity(self, username, real_name, threshold=0.8):
        if not real_name:
            return True, "OK"
        
        # Simple similarity check using SequenceMatcher
        ratio = difflib.SequenceMatcher(None, username.lower(), real_name.lower()).ratio()
        if ratio >= threshold:
            return False, f"Username is too similar to real name (similarity: {ratio:.2f})"
        return True, "OK"

    def validate(self, username, real_name=None):
        checks = [
            self.check_length(username),
            self.check_unsafe_chars(username),
            self.check_profanity(username),
            self.check_similarity(username, real_name)
        ]

        errors = []
        for success, message in checks:
            if not success:
                errors.append(message)

        if errors:
            return False, errors
        return True, ["OK"]
