from retell import Retell
from fastapi import HTTPException
import os
from typing import Dict, Any

class RetellAIManager:
    def __init__(self):
        self.api_key = os.getenv("RETELLAI_API_KEY")
        if not self.api_key:
            raise ValueError("RETELLAI_API_KEY not found in environment variables")
        
        self.client = Retell(api_key=self.api_key)
    
    async def create_transient_bot(self, bot_config: Dict[str, Any]):
        try:
            response = await self.client.create_transient_bot(
                llm_config=bot_config["llm"],
                voice_config=bot_config["voice"],
                conversation_flow=bot_config["conversation_flow"]
            )
            return response
        except Exception as e:
            raise HTTPException(
                status_code=500,
                detail=f"Failed to create Retell AI bot: {str(e)}"
            )
    
    async def get_bot_status(self, bot_id: str):
        try:
            return await self.client.get_bot_status(bot_id)
        except Exception as e:
            raise HTTPException(
                status_code=500,
                detail=f"Failed to get bot status: {str(e)}"
            )
    
    async def update_bot_config(self, bot_id: str, bot_config: Dict[str, Any]):
        try:
            return await self.client.update_bot_config(
                bot_id=bot_id,
                llm_config=bot_config["llm"],
                voice_config=bot_config["voice"],
                conversation_flow=bot_config["conversation_flow"]
            )
        except Exception as e:
            raise HTTPException(
                status_code=500,
                detail=f"Failed to update bot configuration: {str(e)}"
            )

# Create a singleton instance
retell_manager = RetellAIManager() 