"""
Issue LiveKit JWT for user (participant) or agent.
Uses same key/secret as local LiveKit server. No LiveKit API call.
"""
import time
import jwt


def create_user_token(api_key: str, api_secret: str, room_name: str, identity: str, metadata: str = "") -> str:
    """Create a LiveKit access token for a participant (user) to join a room."""
    now = int(time.time())
    payload = {
        "video": {
            "room": room_name,
            "roomJoin": True,
            "canPublish": True,
            "canSubscribe": True,
            "canPublishData": True,
        },
        "sub": identity,
        "iat": now,
        "nbf": now,
        "exp": now + 3600 * 24,
        "iss": api_key,
    }
    if metadata:
        payload["metadata"] = metadata
    return jwt.encode(
        payload,
        api_secret,
        algorithm="HS256",
    )


def create_agent_token(
    api_key: str,
    api_secret: str,
    agent_identity: str = "agent",
    metadata: str = "",
) -> str:
    """Create a LiveKit token for an agent worker (connects to /agent)."""
    now = int(time.time())
    payload = {
        "video": {
            "roomJoin": True,
            "room": "",
            "canPublish": True,
            "canSubscribe": True,
            "canPublishData": True,
            "agent": True,
        },
        "sub": agent_identity,
        "iat": now,
        "nbf": now,
        "exp": now + 3600 * 24,
        "iss": api_key,
    }
    if metadata:
        payload["metadata"] = metadata
    return jwt.encode(
        payload,
        api_secret,
        algorithm="HS256",
    )
