"""
POC Voice Agent for LiveKit + Cartesia TTS + Deepgram

This is a minimal proof-of-concept agent that demonstrates:
1. Joining a LiveKit room using credentials
2. Speaking a greeting using Cartesia TTS (ultra-low latency)
3. Listening to audio and transcribing using Deepgram STT
4. Echoing back what it hears

This validates technical feasibility before full implementation in Task #144.
"""

import logging
import os

from livekit import agents
from livekit.agents import Agent, AgentSession, JobContext
from livekit.plugins import deepgram, silero

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)


class SimpleVoiceAgent(Agent):
    """
    A simple voice agent that echoes back what it hears.

    This is a minimal POC - no GPT-4 integration, no tool calling.
    Focus is on validating the STT → TTS pipeline works.
    """

    def __init__(self) -> None:
        super().__init__(
            instructions=(
                "You are a friendly AI voice assistant testing the LiveKit voice pipeline. "
                "Greet the user warmly and repeat back what you hear to test the audio system. "
                "Keep responses brief and natural."
            )
        )
        logger.info("SimpleVoiceAgent initialized")


async def entrypoint(ctx: JobContext) -> None:
    """
    Main entry point for the LiveKit agent.

    This function is called when a new job (room connection) is created.
    It sets up the voice agent with ElevenLabs TTS and Deepgram STT.
    """
    logger.info(f"Starting POC agent for room: {ctx.room.name}")

    try:
        # Get API keys from environment
        deepgram_api_key = os.environ.get("DEEPGRAM_API_KEY")
        openai_api_key = os.environ.get("OPENAI_API_KEY")

        if not deepgram_api_key:
            logger.error("DEEPGRAM_API_KEY not found in environment")
            raise ValueError("DEEPGRAM_API_KEY is required")

        if not openai_api_key:
            logger.error("OPENAI_API_KEY not found in environment")
            raise ValueError("OPENAI_API_KEY is required")

        logger.info("API keys validated")

        # Configure the agent session with voice services
        session = AgentSession(
            # Cartesia TTS through LiveKit Inference (uses LiveKit's free credits)
            # See: https://docs.livekit.io/agents/models/tts/inference/cartesia/
            # No separate API key needed - billed through LiveKit Cloud
            tts="cartesia/sonic-2:9626c31c-bec5-4cca-baa8-f8ba9e84c8bc",  # British Lady voice

            # Deepgram STT - using cheapest base model for testing
            # See: https://docs.livekit.io/agents/integrations/stt/deepgram/
            stt=deepgram.STT(
                model="base",  # Cheapest base model (~$0.0043 per minute vs $0.0059 for nova)
            ),

            # OpenAI for conversation intelligence
            # Using gpt-4o-mini for POC (fast and cheap)
            llm="gpt-4o-mini",

            # Silero VAD for voice activity detection
            vad=silero.VAD.load(),
        )

        logger.info("Agent session configured")

        # Start the agent session
        await session.start(
            room=ctx.room,
            agent=SimpleVoiceAgent(),
        )

        logger.info("Agent session started")

        # Generate initial greeting
        await session.generate_reply(
            instructions=(
                "Greet the user warmly. "
                "Tell them you're testing the LiveKit voice system and ask them to say something. "
                "Keep it friendly and brief."
            )
        )

        logger.info("Initial greeting generated")

        # Keep the agent running until disconnected
        logger.info("Agent is now active and listening...")

    except Exception as e:
        logger.error(f"Error in agent entrypoint: {e}", exc_info=True)
        raise


def main() -> None:
    """
    Main function to run the POC agent.

    This uses the LiveKit CLI runner which handles:
    - Environment variable loading (.env file)
    - Room connection management
    - Graceful shutdown
    """
    logger.info("Starting LiveKit POC Voice Agent")
    logger.info(f"LiveKit URL: {os.environ.get('LIVEKIT_URL', 'not set')}")
    logger.info(f"Room name: {os.environ.get('LIVEKIT_ROOM_NAME', 'auto-generated')}")

    # Run the agent using LiveKit's CLI runner
    agents.cli.run_app(
        agents.WorkerOptions(
            entrypoint_fnc=entrypoint,
        )
    )


if __name__ == "__main__":
    main()
