"""
JaaS (8x8) JWT Token Generation Utility

This utility generates JWT tokens for 8x8 JaaS authenticated Jitsi meetings.
You need to set up your API key in the 8x8 JaaS console and provide your private key.

Environment Variables Required:
- JAAS_APP_ID: Your JaaS App ID (e.g., vpaas-magic-cookie-xxxxxx)
- JAAS_API_KEY: Your Key ID from JaaS console
- JAAS_PRIVATE_KEY_PATH: Path to your private key file (PEM format)
"""
import jwt
import time
import uuid
import os


# JaaS Configuration - you can also set these via environment variables
JAAS_CONFIG = {
    'app_id': os.environ.get('JAAS_APP_ID', 'YOUR_JAAS_APP_ID'),  # e.g., vpaas-magic-cookie-xxxxx
    'api_key': os.environ.get('JAAS_API_KEY', 'YOUR_API_KEY'),  # Key ID from JaaS console
    'private_key_path': os.environ.get('JAAS_PRIVATE_KEY_PATH', 'config/jaas_private_key.pem'),
}


def load_private_key():
    """Load the private key from file"""
    try:
        key_path = JAAS_CONFIG['private_key_path']
        with open(key_path, 'r') as f:
            return f.read()
    except FileNotFoundError:
        print(f"⚠️ Private key not found at {key_path}")
        print("Please place your JaaS private key at the specified path")
        return None


def generate_jaas_jwt(
    room_name: str,
    user_name: str,
    user_email: str = '',
    user_id: str = None,
    is_moderator: bool = False,
    avatar_url: str = None,
    features: dict = None
) -> str:
    """
    Generate a JWT token for 8x8 JaaS meeting
    
    Args:
        room_name: The Jitsi room name
        user_name: Display name of the user
        user_email: Email of the user
        user_id: Unique user ID (generated if not provided)
        is_moderator: Whether user should have moderator privileges
        avatar_url: URL to user's avatar image
        features: Dict of features to enable (recording, livestreaming, etc.)
    
    Returns:
        JWT token string
    """
    private_key = load_private_key()
    if not private_key:
        raise ValueError("Private key not configured. Please set up your JaaS private key.")
    
    if not user_id:
        user_id = str(uuid.uuid4())
    
    now = int(time.time())
    exp = now + (3 * 60 * 60)  # 3 hours expiry
    
    # Build payload according to JaaS specifications
    payload = {
        'aud': 'jitsi',
        'iss': 'chat',
        'iat': now,
        'exp': exp,
        'nbf': now,
        'sub': JAAS_CONFIG['app_id'],
        'room': room_name,  # Can be "*" for all rooms
        'context': {
            'user': {
                'id': user_id,
                'name': user_name,
                'email': user_email,
                'moderator': 'true' if is_moderator else 'false',
            },
            'features': features or {
                'recording': 'true' if is_moderator else 'false',
                'livestreaming': 'false',
                'transcription': 'false',
            }
        }
    }
    
    if avatar_url:
        payload['context']['user']['avatar'] = avatar_url
    
    # JWT Header
    headers = {
        'alg': 'RS256',
        'kid': JAAS_CONFIG['api_key'],
        'typ': 'JWT'
    }
    
    # Generate and sign the token
    token = jwt.encode(
        payload,
        private_key,
        algorithm='RS256',
        headers=headers
    )
    
    return token


def get_jaas_meeting_url(room_name: str, jwt_token: str) -> str:
    """
    Generate the full meeting URL with JWT
    
    Args:
        room_name: The room name
        jwt_token: The generated JWT token
    
    Returns:
        Full meeting URL with JWT
    """
    app_id = JAAS_CONFIG['app_id']
    # JaaS URL format: https://8x8.vc/{app_id}/{room_name}?jwt={token}
    return f"https://8x8.vc/{app_id}/{room_name}?jwt={jwt_token}"


# Test function
if __name__ == '__main__':
    # Example usage
    try:
        token = generate_jaas_jwt(
            room_name='test-room',
            user_name='Test User',
            user_email='test@example.com',
            is_moderator=True
        )
        url = get_jaas_meeting_url('test-room', token)
        print(f"✅ Generated JWT: {token[:50]}...")
        print(f"📡 Meeting URL: {url}")
    except Exception as e:
        print(f"❌ Error: {e}")
        print("\nTo set up JaaS:")
        print("1. Go to https://jaas.8x8.vc/#/apikeys")
        print("2. Generate an API key (it will provide you with a private key)")
        print("3. Save the private key to config/jaas_private_key.pem")
        print("4. Update JAAS_CONFIG with your App ID and Key ID")
