# from fastapi import APIRouter, HTTPException, Depends
# from typing import List, Optional, Dict
# from pydantic import BaseModel
# from datetime import datetime
# from bson import ObjectId
# from app.utils.retell_client import RetellAIManager
# from app.core.config import settings

# router = APIRouter(prefix="/api/ai-assistant", tags=["AI Assistant"])

# retell_manager = RetellAIManager()

# class AIAssistantCreate(BaseModel):
#     name: str
#     gender: str
#     accent: str
#     personality: str
#     voice_id: str
#     voice_model: Optional[str] = "eleven_multilingual_v2"
#     llm_websocket_url: str
#     system_prompt: str
#     conversation_flow: Dict
    
# class AIAssistantUpdate(BaseModel):
#     name: Optional[str]
#     voice_id: Optional[str]
#     voice_model: Optional[str]
#     system_prompt: Optional[str]
#     conversation_flow: Optional[Dict]
#     voice_temperature: Optional[float] = 1.0
#     voice_speed: Optional[float] = 1.0
#     interruption_sensitivity: Optional[float] = 1.0

# @router.post("/create")
# async def create_ai_assistant(assistant: AIAssistantCreate):
#     try:
#         # Prepare the agent configuration for Retell AI
#         agent_config = {
#             "agent_name": assistant.name,
#             "voice_id": assistant.voice_id,
#             "voice_model": assistant.voice_model,
#             "llm_websocket_url": assistant.llm_websocket_url,
#             "voice_temperature": 1.0,
#             "voice_speed": 1.0,
#             "responsiveness": 1.0,
#             "interruption_sensitivity": 1.0,
#             "enable_backchannel": True,
#             "normalize_for_speech": True,
#             "enable_voicemail_detection": True,
#             "voicemail_detection_timeout_ms": 30000,
#             "llm": {
#                 "provider": "openai",
#                 "model": "gpt-4",
#                 "temperature": 0.7,
#                 "system_prompt": assistant.system_prompt
#             },
#             "conversation_flow": assistant.conversation_flow
#         }

#         # Create agent in Retell AI
#         retell_response = await retell_manager.create_agent(agent_config)
        
#         # Store in MongoDB
#         assistant_doc = {
#             "retell_agent_id": retell_response["agent_id"],
#             "name": assistant.name,
#             "gender": assistant.gender,
#             "accent": assistant.accent,
#             "personality": assistant.personality,
#             "voice_id": assistant.voice_id,
#             "voice_model": assistant.voice_model,
#             "system_prompt": assistant.system_prompt,
#             "conversation_flow": assistant.conversation_flow,
#             "created_at": datetime.utcnow(),
#             "updated_at": datetime.utcnow()
#         }
        
#         result = await db.ai_assistants.insert_one(assistant_doc)
        
#         return {
#             "message": "AI Assistant created successfully",
#             "assistant_id": str(result.inserted_id),
#             "retell_agent_id": retell_response["agent_id"]
#         }
        
#     except Exception as e:
#         raise HTTPException(
#             status_code=500,
#             detail=f"Failed to create AI assistant: {str(e)}"
#         )

# @router.put("/{assistant_id}")
# async def update_ai_assistant(assistant_id: str, update_data: AIAssistantUpdate):
#     try:
#         # Get existing assistant
#         assistant = await db.ai_assistants.find_one({"_id": ObjectId(assistant_id)})
#         if not assistant:
#             raise HTTPException(status_code=404, detail="AI Assistant not found")
            
#         # Prepare update for Retell AI
#         retell_update = {}
#         if update_data.voice_id:
#             retell_update["voice_id"] = update_data.voice_id
#         if update_data.voice_model:
#             retell_update["voice_model"] = update_data.voice_model
#         if update_data.voice_temperature:
#             retell_update["voice_temperature"] = update_data.voice_temperature
#         if update_data.voice_speed:
#             retell_update["voice_speed"] = update_data.voice_speed
#         if update_data.interruption_sensitivity:
#             retell_update["interruption_sensitivity"] = update_data.interruption_sensitivity
#         if update_data.system_prompt:
#             retell_update["llm"] = {
#                 "system_prompt": update_data.system_prompt
#             }
#         if update_data.conversation_flow:
#             retell_update["conversation_flow"] = update_data.conversation_flow

#         # Update in Retell AI
#         await retell_manager.update_agent(
#             assistant["retell_agent_id"],
#             retell_update
#         )
        
#         # Prepare MongoDB update
#         mongo_update = {
#             "updated_at": datetime.utcnow()
#         }
#         if update_data.name:
#             mongo_update["name"] = update_data.name
#         if update_data.voice_id:
#             mongo_update["voice_id"] = update_data.voice_id
#         if update_data.voice_model:
#             mongo_update["voice_model"] = update_data.voice_model
#         if update_data.system_prompt:
#             mongo_update["system_prompt"] = update_data.system_prompt
#         if update_data.conversation_flow:
#             mongo_update["conversation_flow"] = update_data.conversation_flow
            
#         # Update in MongoDB
#         await db.ai_assistants.update_one(
#             {"_id": ObjectId(assistant_id)},
#             {"$set": mongo_update}
#         )
        
#         return {"message": "AI Assistant updated successfully"}
        
#     except Exception as e:
#         raise HTTPException(
#             status_code=500,
#             detail=f"Failed to update AI assistant: {str(e)}"
#         )

# @router.get("/list")
# async def list_ai_assistants():
#     try:
#         assistants = await db.ai_assistants.find({}).to_list(length=None)
#         return {
#             "assistants": [{
#                 "id": str(assistant["_id"]),
#                 "name": assistant["name"],
#                 "gender": assistant["gender"],
#                 "accent": assistant["accent"],
#                 "personality": assistant["personality"],
#                 "retell_agent_id": assistant["retell_agent_id"]
#             } for assistant in assistants]
#         }
#     except Exception as e:
#         raise HTTPException(
#             status_code=500,
#             detail=f"Failed to list AI assistants: {str(e)}"
#         ) 
from fastapi import APIRouter, status
from typing import List
from utils.auth_dependency import handles_authentication, user_dependency
from utils.database import db_dependency
from utils.exceptions import NotFoundException, AuthenticationError
from schemas.ai_assistants import AIAssistantCreate, AIAssistantUpdate, AIAssistantOut
from repositories import assistant_repository  # ✅ import the module, not a class

router = APIRouter(prefix="/api/ai-assistants", tags=["AI Assistants"])


@router.post("/create", status_code=status.HTTP_201_CREATED, response_model=AIAssistantOut)
@handles_authentication
async def create_ai_assistant(
    user: user_dependency,
    request: AIAssistantCreate,
    db: db_dependency
):
    if user is None:
        raise AuthenticationError
    
    print(request)

    return assistant_repository.create_ai_assistant(db, request)


@router.put("/{assistant_id}", status_code=status.HTTP_200_OK, response_model=AIAssistantOut)
@handles_authentication
async def update_ai_assistant(
    assistant_id: int,
    user: user_dependency,
    request: AIAssistantUpdate,
    db: db_dependency
):
    if user is None:
        raise AuthenticationError

    updated = assistant_repository.update_ai_assistant(db, assistant_id, request)
    if not updated:
        raise NotFoundException("AI Assistant")
    return updated


@router.get("/list", status_code=status.HTTP_200_OK, response_model=List[AIAssistantOut])
@handles_authentication
async def list_ai_assistants(
    user: user_dependency,
    db: db_dependency
):
    if user is None:
        raise AuthenticationError

    return assistant_repository.list_ai_assistants(db)
