#!/usr/bin/env python3
"""Run a simulation against the restaurant booking bot.

This example shows how to use Voiceground's simulation feature to test
a voice bot with a simulated user. The simulator uses an LLM to generate
contextual responses, creating a realistic conversation.

Requirements:
    pip install "pipecat-ai[openai,elevenlabs]"

Environment variables:
    OPENAI_API_KEY: Your OpenAI API key
    ELEVENLABS_API_KEY: Your ElevenLabs API key
    VOICE_ID: Voice ID for the TTS service
"""

import asyncio
import os
import sys

import aiohttp
from dotenv import load_dotenv
from loguru import logger
from pipecat.services.elevenlabs.stt import ElevenLabsSTTService
from pipecat.services.elevenlabs.tts import ElevenLabsTTSService
from pipecat.services.openai.llm import OpenAILLMService

# Import the bot we want to test
from restaurant_bot import run_restaurant_bot

from voiceground.simulation import VoicegroundSimulation, VoicegroundSimulatorConfig

load_dotenv(override=True)

logger.remove(0)
logger.add(sys.stderr, level="DEBUG")


# Simulated user configuration - defines how the "fake user" behaves
SIMULATOR_SYSTEM_PROMPT = """You are simulating a customer calling a restaurant to make a reservation.

YOUR GOAL: Book a table for 2 people tomorrow at 7pm under the name "Smith".

INSTRUCTIONS:
- Start by greeting and stating you want to make a reservation
- Answer any questions the bot asks (party size: 2, date: tomorrow, time: 7pm, name: Smith)
- Be natural and conversational, like a real customer
- Once the reservation is confirmed, thank them and say goodbye
- Keep responses brief (1-2 sentences)

IMPORTANT: When the reservation is complete, end with "Thank you, goodbye!" """


async def main():
    # Validate API keys
    openai_key = os.getenv("OPENAI_API_KEY")
    elevenlabs_key = os.getenv("ELEVENLABS_API_KEY")
    voice_id = os.getenv("VOICE_ID")

    async with aiohttp.ClientSession() as session:
        # Configure the simulator (the "fake user")
        simulator_config = VoicegroundSimulatorConfig(
            llm=OpenAILLMService(api_key=openai_key, model="gpt-4o-mini"),
            tts=ElevenLabsTTSService(
                api_key=elevenlabs_key, aiohttp_session=session, voice_id=voice_id
            ),
            stt=ElevenLabsSTTService(api_key=elevenlabs_key, aiohttp_session=session),
            system_prompt=SIMULATOR_SYSTEM_PROMPT,
            initiate_conversation=True,
            max_turns=5,
            timeout_seconds=45,
        )

        # Run simulation
        async with VoicegroundSimulation(simulator_config) as simulation:
            await run_restaurant_bot(transport=simulation.transport)

        # Display results
        results = simulation.results

        logger.info("-" * 50)
        logger.info("Simulation Results:")
        logger.info(f"  Duration: {results.duration_seconds:.2f}s")
        logger.info(f"  Turns: {results.turn_count}")
        logger.info(f"  Termination: {results.termination_reason.value}")

        logger.info("  Transcript:")
        for entry in results.transcript:
            logger.info(f"    [{entry.role.upper()}]: {entry.text}")


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