#!/usr/bin/env python3
"""多人会议测试 - 使用 LiveKit API 生成 Token"""
import asyncio
import logging
import os
import sys
from dotenv import load_dotenv

load_dotenv('/Users/leo/.hermes/workspace/livekit-agents/.env.dev')
sys.path.insert(0, '/Users/leo/.hermes/workspace/livekit-agents')

from livekit import api
from agent import VoiceAgent, AgentState

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

LIVEKIT_URL = os.environ.get("LIVEKIT_URL", "http://localhost:7880")
LIVEKIT_API_KEY = os.environ.get("LIVEKIT_API_KEY", "devkey")
LIVEKIT_API_SECRET = os.environ.get("LIVEKIT_API_SECRET", "secret12345678901234567890abcdef")


async def main():
    print("=" * 60)
    print("🎙️ LiveKit Voice AI - 多人会议测试")
    print("=" * 60)
    
    room_name = "voice-ai-meeting"
    logger.info(f"🏠 会议室: {room_name}")
    logger.info(f"🔗 访问: {LIVEKIT_URL}/explore#{room_name}")
    
    # 使用 LiveKit API 生成 Token
    livekit = api.LiveKitAPI(LIVEKIT_URL, LIVEKIT_API_KEY, LIVEKIT_API_SECRET)
    
    participants = [
        {"identity": "alice", "name": "Alice", "avatar": "👩"},
        {"identity": "bob", "name": "Bob", "avatar": "👨"},
        {"identity": "charlie", "name": "Charlie", "avatar": "👱"},
    ]
    
    logger.info(f"\n👥 为 {len(participants)} 个参与者生成 Token...")
    tokens = {}
    
    for p in participants:
        token = (
            api.AccessToken(LIVEKIT_API_KEY, LIVEKIT_API_SECRET)
            .with_identity(p["identity"])
            .with_name(p["name"])
            .with_grants(api.VideoGrants(
                room_join=True,
                room=room_name,
                can_publish=True,
                can_subscribe=True,
            ))
            .to_jwt()
        )
        tokens[p["identity"]] = token
        logger.info(f"  {p['avatar']} {p['name']}: {token[:40]}...")
    
    # 模拟对话
    logger.info("\n🎙️ 开始会议对话...")
    conversations = [
        ("alice", "大家好，我是 Alice"),
        ("bob", "我是 Bob，很高兴认识大家"),
        ("charlie", "请问 Agnes 在吗？"),
        ("agent", "大家好！我是 Agnes AI 助手"),
        ("alice", "帮我总结一下刚才的讨论"),
        ("agent", "好的，我来总结..."),
        ("bob", "谢谢 Agnes"),
        ("charlie", "能帮我安排会议吗？"),
        ("agent", "当然可以！"),
    ]
    
    for person, msg in conversations:
        name = next((p['name'] for p in participants if p['identity'] == person), 'Agnes')
        avatar = next((p['avatar'] for p in participants if p['identity'] == person), '🤖')
        logger.info(f"\n💬 [{name}] 说: {msg}")
        await asyncio.sleep(1)
    
    # 输出 Token
    print("\n" + "=" * 60)
    print("📋 React Native 测试 Token:")
    print("=" * 60)
    for ident, tok in tokens.items():
        print(f"\n{ident}:")
        print(f"  URL: {LIVEKIT_URL}")
        print(f"  Room: {room_name}")
        print(f"  Identity: {ident}")
        print(f"  Token: {tok}")
    
    print(f"\n🔗 LiveKit Console: {LIVEKIT_URL}/explore#{room_name}")
    print()
    print("✅ 测试完成！")


if __name__ == "__main__":
    asyncio.run(main())
