"""Initiates outbound phone calls via Twilio for Pipecat voice sessions."""

import os
import logging
from twilio.rest import Client as TwilioClient

logger = logging.getLogger(__name__)


class OutboundCallService:
    def __init__(self):
        self.account_sid = os.getenv("TWILIO_ACCOUNT_SID", "")
        self.auth_token = os.getenv("TWILIO_AUTH_TOKEN", "")
        self.phone_number = os.getenv("TWILIO_PHONE_NUMBER", "")
        self.host = os.getenv("VOICE_SERVICE_HOST", "localhost:3008")
        self.client = TwilioClient(self.account_sid, self.auth_token) if self.account_sid else None

    async def initiate_call(self, phone_number: str, voice_session_id: str, agent_context: dict = None) -> str | None:
        """Initiate an outbound call via Twilio, connecting to Pipecat Media Streams."""
        if not self.client:
            logger.warning("Twilio client not configured, skipping outbound call")
            return None

        try:
            twiml = f'''<Response><Connect><Stream url="wss://{self.host}/ws/twilio-stream/{voice_session_id}" /></Connect></Response>'''
            call = self.client.calls.create(
                to=phone_number,
                from_=self.phone_number,
                twiml=twiml,
            )
            logger.info(f"Outbound call initiated: {call.sid} to {phone_number}")
            return call.sid
        except Exception as e:
            logger.error(f"Failed to initiate call to {phone_number}: {e}")
            return None

    def is_available(self) -> bool:
        return self.client is not None and bool(self.phone_number)
