import random
from chatapp.models import ChatMessage, Escalation


def generate_unique_visitor_code(company, length=6, max_attempts=20):
    """Generate a unique numeric visitor id code of given length for a company.
    Ensures it does not collide with existing visitor_id values in ChatMessage or Escalation.
    Returns string or raises RuntimeError if unable to find a free code.
    """
    for _ in range(max_attempts):
        code = ''.join(str(random.randint(0, 9)) for _ in range(length))
        # avoid leading zeros maybe acceptable; keep as string
        exists_msg = ChatMessage.objects.filter(company=company, visitor_id=code).exists()
        exists_esc = Escalation.objects.filter(company=company, visitor_id=code).exists()
        if not exists_msg and not exists_esc:
            return code
    raise RuntimeError('Unable to generate unique visitor code')
