#!/usr/bin/env python3
"""
Generate LiveKit Access Token

Helper script to generate a LiveKit access token for testing the bot locally.
This token is used to authenticate the bot when joining a LiveKit room.

Usage:
    .venv/bin/python generate_livekit_token.py [room_name] [identity]

Environment Variables (from .env.local):
    LIVEKIT_API_KEY     - LiveKit API key
    LIVEKIT_API_SECRET  - LiveKit API secret
"""

import os
import sys
from pathlib import Path

# Try to load environment variables from .env.local
try:
    from dotenv import load_dotenv
    env_file = Path(__file__).parent / '.env.local'
    if env_file.exists():
        load_dotenv(env_file)
        print(f"✅ Loaded environment variables from {env_file}")
    else:
        print(f"⚠️  No .env.local file found")
        print(f"   Please create .env.local from .env.local.example")
        sys.exit(1)
except ImportError:
    print("❌ python-dotenv not installed")
    print("   Install with: .venv/bin/pip install python-dotenv")
    sys.exit(1)

# Import LiveKit API
try:
    from livekit.api import AccessToken, VideoGrants
except ImportError:
    print("❌ LiveKit API not installed")
    print("   Install with: .venv/bin/pip install livekit-api")
    sys.exit(1)

def generate_token(room_name: str, identity: str) -> str:
    """
    Generate a LiveKit access token.

    Args:
        room_name: Name of the LiveKit room
        identity: Identity/name for the bot participant

    Returns:
        JWT access token string
    """
    api_key = os.getenv('LIVEKIT_API_KEY')
    api_secret = os.getenv('LIVEKIT_API_SECRET')

    if not api_key or not api_secret:
        raise ValueError(
            "Missing LIVEKIT_API_KEY or LIVEKIT_API_SECRET environment variables. "
            "Please set these in .env.local"
        )

    print(f"📝 Generating token for:")
    print(f"   Room: {room_name}")
    print(f"   Identity: {identity}")
    print(f"   API Key: {api_key[:10]}...")

    # Create token with video grants
    token = AccessToken(api_key, api_secret)
    token.with_identity(identity)
    token.with_name(f"Screenshare Bot ({identity})")
    token.with_grants(VideoGrants(
        room_join=True,
        room=room_name,
        can_publish=True,
        can_subscribe=True,
        can_publish_data=True
    ))

    jwt = token.to_jwt()
    print(f"✅ Token generated successfully")
    print()
    return jwt


def main():
    """Main entry point"""
    # Parse arguments
    room_name = sys.argv[1] if len(sys.argv) > 1 else "test-room-local"
    identity = sys.argv[2] if len(sys.argv) > 2 else "screenshare-bot"

    try:
        token = generate_token(room_name, identity)

        print("=" * 70)
        print("LIVEKIT ACCESS TOKEN")
        print("=" * 70)
        print(token)
        print("=" * 70)
        print()
        print("Copy this token and use it with:")
        print(f"  export LIVEKIT_TOKEN=\"{token}\"")
        print()
        print("Or use it directly in bot.py:")
        livekit_url = os.getenv('LIVEKIT_URL', 'wss://your-project.livekit.cloud')
        print(f"  .venv/bin/python bot.py \\")
        print(f"    \"{livekit_url}/{room_name}\" \\")
        print(f"    \"https://buzztrail.github.io/buzztrail-presentations/p10e-2f8z-h0fi/\" \\")
        print(f"    \"test-session-$(date +%s)\" \\")
        print(f"    \"test-bot-$(date +%s)\" \\")
        print(f"    \"{token}\"")

    except Exception as e:
        print(f"❌ Error: {e}")
        sys.exit(1)


if __name__ == "__main__":
    main()
