from fastapi import APIRouter, HTTPException, Query

from pydantic import BaseModel
from typing import List, Optional
from pymongo import MongoClient
from bson import ObjectId
from services.twilio_service import fetch_twilio_numbers

router = APIRouter(prefix="/api/business", tags=["Business Setup"])

class Service(BaseModel):
    name: str
    price: float
    slot_length: int  # in minutes
    description: Optional[str]

@router.post("/services")
async def setup_services(services: List[Service]):
    # Save services to MongoDB
    return {"message": "Services saved successfully"}

# class PhoneNumber(BaseModel):
#     number: str
#     region: str
#     monthly_cost: float

@router.get("/available-numbers")
async def get_available_numbers(
    country: str = Query(..., example="GB"),
    number_type: str = Query("local", regex="^(local|tollfree)$", example="local"),
    contains: Optional[str] = Query(None),
    page: Optional[int] = Query(None),
    state: Optional[str] = Query(None)
):
    return await fetch_twilio_numbers(
        country=country,
        number_type=number_type,
        contains=contains,
        page=page,
        state=state
    )

class AIAssistant(BaseModel):
    id: str
    name: str
    gender: str
    accent: str
    personality: str
    voice_sample_url: Optional[str]

@router.get("/ai-assistants")
async def get_ai_assistants():
    assistants = await db.ai_assistants.find({}, {
        "_id": 1,
        "name": 1,
        "gender": 1,
        "accent": 1,
        "personality": 1,
        "description": 1
    }).to_list(length=None)
    return {"assistants": assistants}

class Availability(BaseModel):
    day_of_week: int  # 0-6 (Monday-Sunday)
    start_time: str  # HH:MM format
    end_time: str
    is_working_day: bool

@router.post("/availability")
async def set_availability(availability: List[Availability]):
    # Save availability schedule to MongoDB
    return {"message": "Availability saved successfully"}

@router.post("/select-assistant/{assistant_id}")
async def select_assistant(assistant_id: str, business_id: str):
    # Get the assistant configuration
    assistant = await db.ai_assistants.find_one({"_id": ObjectId(assistant_id)})
    if not assistant:
        raise HTTPException(status_code=404, detail="Assistant not found")
    
    # Create a custom configuration for the business
    custom_config = assistant["bot_config"].copy()
    custom_config["business_id"] = business_id
    
    # Update the business with the selected assistant
    await db.businesses.update_one(
        {"_id": ObjectId(business_id)},
        {
            "$set": {
                "ai_assistant_id": assistant_id,
                "ai_assistant_config": custom_config
            }
        }
    )
    
    return {"message": "AI assistant configured successfully"} 