import time
from django.conf import settings

try:
    from agora_token_builder import RtcTokenBuilder, Role_Publisher, Role_Subscriber
    AGORA_AVAILABLE = True
except ImportError:
    AGORA_AVAILABLE = False
    Role_Publisher = 1
    Role_Subscriber = 2


def generate_agora_token(channel_name, uid, role='publisher', expire_seconds=3600):
    app_id = getattr(settings, 'AGORA_APP_ID', '')
    app_certificate = getattr(settings, 'AGORA_APP_CERTIFICATE', '')

    if not app_id or not app_certificate:
        return None

    if not AGORA_AVAILABLE:
        return None

    agora_role = Role_Publisher if role == 'publisher' else Role_Subscriber
    expiration_time = int(time.time()) + expire_seconds

    token = RtcTokenBuilder.buildTokenWithUid(
        app_id, app_certificate, channel_name, uid, agora_role, expiration_time
    )
    return token
