"""Phone-fallback calling via Bolna's outbound API + web-call config for the browser.""" from __future__ import annotations import re from typing import Optional import httpx from fastapi import APIRouter from pydantic import BaseModel import config import sanitize router = APIRouter(prefix="/api", tags=["calls"]) class CallBody(BaseModel): phone: str table_number: Optional[str] = None outlet_location: str = config.DEFAULT_OUTLET def normalize_phone(phone: str) -> Optional[str]: """Return E.164 or None. Bare 10-digit numbers are assumed Indian (+91).""" digits = re.sub(r"[^\d+]", "", phone.strip()) if re.fullmatch(r"\+\d{10,15}", digits): return digits if re.fullmatch(r"\d{10}", digits): return f"+91{digits}" if re.fullmatch(r"91\d{10}", digits): return f"+{digits}" return None @router.post("/call") async def start_phone_call(body: CallBody): phone = normalize_phone(body.phone) if not phone: return {"success": False, "message": "Please enter a valid 10-digit phone number."} if not (config.BOLNA_API_KEY and config.BOLNA_AGENT_ID): return {"success": False, "message": "Phone calling is not configured yet (missing Bolna keys)."} payload = { "agent_id": config.BOLNA_AGENT_ID, "recipient_phone_number": phone, "user_data": { "restaurant_name": "BYG Brewski", "table_number": sanitize.clean(body.table_number) or "takeaway", "outlet_location": sanitize.clean(body.outlet_location) or config.DEFAULT_OUTLET, }, } try: async with httpx.AsyncClient(timeout=15) as client: res = await client.post( f"{config.BOLNA_API_HOST}/call", json=payload, headers={"Authorization": f"Bearer {config.BOLNA_API_KEY}"}, ) data = res.json() if res.status_code >= 400: return {"success": False, "message": data.get("message", "Bolna rejected the call request.")} return {"success": True, "execution_id": data.get("execution_id"), "message": "Bell is calling you now."} except Exception as exc: return {"success": False, "message": f"Could not start the call: {exc}"} @router.get("/webcall-config") async def webcall_config(): """Runtime config for the browser web call. Keeps tokens out of the JS bundle; exposure at runtime is an accepted hackathon trade-off (use short-lived tokens here if/when Bolna issues them).""" if not (config.BOLNA_AGENT_ID and config.BOLNA_API_KEY and config.BOLNA_WS_HOST): return {"available": False, "message": "Web calling not configured. Use phone fallback."} return { "available": True, "agent_id": config.BOLNA_AGENT_ID, "access_token": config.BOLNA_API_KEY, "ws_host": config.BOLNA_WS_HOST, }