#!/usr/bin/env python3
"""LiveKit Voice AI Agent - 启动脚本"""
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.agents import JobContext, AutoSubscribe
from livekit.agents.worker import WorkerOptions
from livekit.agents import cli
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", "secret")


async def entrypoint(ctx: JobContext):
    """LiveKit Agent 入口函数"""
    logger.info("=" * 60)
    logger.info("🚀 Voice AI Agent 启动")
    logger.info(f"   房间: {ctx.room.name}")
    logger.info(f"   VAD: TEN VAD (0.234ms/帧)")
    logger.info(f"   STT: FunASR SenseVoiceSmall")
    logger.info(f"   LLM: Agnes AI (agnes-2.5-flash)")
    logger.info(f"   TTS: Edge TTS (zh-CN-XiaoxiaoNeural)")
    logger.info("=" * 60)
    
    agent = VoiceAgent()
    await agent.initialize()
    
    await ctx.connect(auto_subscribe=AutoSubscribe.AUDIO_ONLY)
    
    @ctx.room.on("participant_connected")
    async def on_participant_connected(participant):
        logger.info(f"👤 新参与者: {participant.identity}")
    
    @ctx.room.on("participant_disconnected")
    async def on_participant_disconnected(participant):
        logger.info(f"👋 参与者离开: {participant.identity}")
    
    @ctx.room.on("track_subscribed")
    async def on_track_subscribed(track, publication, participant):
        if track.kind.value == "audio":
            logger.info(f"🎵 订阅音频: {participant.identity}")
            asyncio.create_task(_process_audio(agent, track))
    
    logger.info("✅ Agent 已就绪，等待连接...")
    
    while ctx.room.isconnected:
        await asyncio.sleep(1)
    
    await agent.close()
    logger.info("👋 Agent 已关闭")


async def _process_audio(agent: VoiceAgent, track):
    """处理音频流"""
    stream = track.media_stream
    async for event in stream:
        if hasattr(event, 'frame'):
            frame = event.frame
            audio_bytes = bytes(frame.buffer)
            await agent.process_audio_chunk(audio_bytes)


def main():
    """主入口"""
    options = WorkerOptions(
        entrypoint_fnc=entrypoint,
        agent_name="voice-ai-agent",
        ws_url=LIVEKIT_URL,
        api_key=LIVEKIT_API_KEY,
        api_secret=LIVEKIT_API_SECRET,
    )
    
    logger.info("🚀 启动 LiveKit Voice AI Agent")
    logger.info(f"   URL: {LIVEKIT_URL}")
    logger.info(f"   API Key: {LIVEKIT_API_KEY[:8]}...")
    logger.info(f"   STT: {os.environ.get('FUNASR_ENDPOINT', 'http://localhost:8080')}")
    logger.info(f"   LLM: {os.environ.get('OPENAI_BASE_URL', 'https://api.openai.com/v1')}")
    logger.info(f"   TTS: {'Edge TTS (已启用)' if os.environ.get('TTS_ENABLED', 'false').lower() == 'true' else '已禁用'}")
    
    cli.run_app(options)


if __name__ == "__main__":
    main()
