import random
import string
from app.db import get_db_controller

def generate_unique_code():
    db = get_db_controller()
    while True:
        # Requirements: 6 chars, Capital, lowercase, at least 1 number.
        # Let's verify ensuring all constraints.
        
        # Strategy: pick 1 upper, 1 lower, 1 digit, then 3 random.
        chars = [
            random.choice(string.ascii_uppercase),
            random.choice(string.ascii_lowercase),
            random.choice(string.digits)
        ]
        chars += [random.choice(string.ascii_letters + string.digits) for _ in range(3)]
        random.shuffle(chars)
        code = ''.join(chars)
        
        if not db.check_code_exists(code):
            return code

def generate_unique_sub_name(username):
    db = get_db_controller()
    base = f"{username}_karaoke"
    
    # Check if base exists
    if not db.check_sub_name_exists(base):
        return base
        
    # Append random suffix
    while True:
        suffix = ''.join(random.choices(string.ascii_uppercase + string.digits, k=4))
        name = f"{username}_{suffix}"
        if not db.check_sub_name_exists(name):
            return name
