import os
from app.advisor_service.services.base_service import BaseService
from fastapi import HTTPException
from datetime import datetime, timezone

from app.common.models import Advisor, Notifications, CallsLog
from app.common.twillio_helper import get_twillio_client
from app.retell_service.services.retell_service import create_offline_message
from app.utils.helpers.common import get_app_url

class UltravoxService(BaseService):    
    def __init__(self, db):
        super().__init__(db)

    def create_offline_message(self, advisor_name: str, message: str, customer_name: str = "Unknown", call_id: str = None) -> dict:
        """
        Create an offline message and notification for an advisor
        
        Args:
            advisor_name: Name of the advisor
            message: Message content
            customer_name: Name of the customer (defaults to "Unknown")
            customer_phone: Phone number of the customer
        """
        call_log = self.get_by_field(CallsLog, "call_id", call_id)
        customer_phone = call_log.caller_number
        
        advisor = self.db.query(Advisor).filter(
            Advisor.full_name.ilike(f"%{advisor_name}%")
        ).first()
        
        if not advisor:
            raise HTTPException(
                status_code=404,
                detail="Advisor not found, message not saved and no notification created."
            )

        create_offline_message(
            db=self.db,
            customer_name=customer_name,
            customer_note=message,
            advisor_name=advisor_name,
            customer_phone=customer_phone,
        )

        self.create(Notifications, {
            "user_id": advisor.user_id,
            "advisor_id": advisor.id,
            "notification_type": "offline_message", 
            "title": f"New Message from {customer_name}",
            "message": message,
            "customer_name": customer_name,
            "customer_phone": customer_phone,
            "is_read": False,
            "call_id": call_id,
            "created_at": datetime.now(timezone.utc),
            "updated_at": datetime.now(timezone.utc)
        })