import random
import string
import logging
from sqlalchemy.orm import Session
from app.models.user import User

logger = logging.getLogger(__name__)

def generate_random_string(length=6):
    return ''.join(random.choices(string.ascii_lowercase + string.digits, k=length))

def fix_user_names(db: Session) -> None:
    """
    Check and fix empty user names and english_names.
    Ensure uniqueness.
    """
    logger.info("Checking user names and english_names...")
    
    # Get all non-deleted users
    users = db.query(User).filter(User.is_deleted == 0).all()
    
    # Track existing values to ensure uniqueness
    existing_names = set()
    existing_english_names = set()
    
    users_to_update_count = 0
    
    for user in users:
        is_modified = False
        
        # --- Handle Chinese Name ---
        original_name = user.name
        current_name = original_name
        
        # 1. Fill if empty
        if not current_name:
            current_name = "用户" + generate_random_string(6)
        
        # 2. Ensure Unique
        # If we just generated it, it's base + random.
        # If it existed, it's the original name.
        # We need to preserve the "base" for incrementing.
        base_name = current_name
        
        # If the name is already in our *current session* set of names, we must change it.
        # Note: We rely on the order of processing.
        counter = 2
        while current_name in existing_names:
            current_name = f"{base_name}{counter}"
            counter += 1
        
        existing_names.add(current_name)
        
        if current_name != original_name:
            user.name = current_name
            is_modified = True

        # --- Handle English Name ---
        original_eng = user.english_name
        current_eng = original_eng
        
        # 1. Fill if empty
        if not current_eng:
            current_eng = "user_" + generate_random_string(6)
            
        # 2. Ensure Unique
        base_eng = current_eng
        eng_counter = 2
        while current_eng in existing_english_names:
            current_eng = f"{base_eng}{eng_counter}"
            eng_counter += 1
            
        existing_english_names.add(current_eng)
        
        if current_eng != original_eng:
            user.english_name = current_eng
            is_modified = True
            
        if is_modified:
            users_to_update_count += 1
    
    if users_to_update_count > 0:
        logger.info(f"Updating names for {users_to_update_count} users.")
        db.commit()
    else:
        logger.info("No user name updates needed.")

