from fastapi import APIRouter, HTTPException
from pymongo import MongoClient
from bson import ObjectId
from datetime import datetime
from typing import List, Optional, Dict
from pydantic import BaseModel
from app.utils.retell_client import retell_manager

class PyObjectId(ObjectId):
    @classmethod
    def __get_validators__(cls):
        yield cls.validate

    @classmethod
    def validate(cls, v):
        if not ObjectId.is_valid(v):
            raise ValueError("Invalid ObjectId")
        return ObjectId(v)

class MongoDBManager:
    def __init__(self, mongodb_url: str, db_name: str):
        self.client = MongoClient(mongodb_url)
        self.db = self.client[db_name]
        
        # Initialize collections
        self.users = self.db.users
        self.businesses = self.db.businesses
        self.ai_assistants = self.db.ai_assistants
        
        # Create indexes
        self.users.create_index("email", unique=True)
        self.businesses.create_index("twilio_number", unique=True)

router = APIRouter(prefix="/api/telephony", tags=["Telephony"])

@router.get("/get-bot-config/{phone_number}")
async def get_bot_config(phone_number: str):
    # Find the business by phone number
    business = await db.businesses.find_one({"twilio_number": phone_number})
    if not business:
        raise HTTPException(status_code=404, detail="Business not found")
    
    # Create or update transient bot
    bot_config = business["ai_assistant_config"]
    try:
        bot_response = await retell_manager.create_transient_bot(bot_config)
        
        return {
            "bot_id": bot_response["bot_id"],
            "bot_config": bot_config,
            "business_details": {
                "name": business["business_name"],
                "services": business["services"],
                "availability": business["availability"]
            }
        }
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"Failed to initialize bot: {str(e)}"
        )

@router.post("/update-bot/{bot_id}")
async def update_bot(bot_id: str, config: Dict):
    try:
        response = await retell_manager.update_bot_config(bot_id, config)
        return {"message": "Bot updated successfully", "bot_id": bot_id}
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"Failed to update bot: {str(e)}"
        )

@router.get("/bot-status/{bot_id}")
async def get_bot_status(bot_id: str):
    try:
        status = await retell_manager.get_bot_status(bot_id)
        return {"status": status}
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"Failed to get bot status: {str(e)}"
        ) 