from datetime import datetime, timezone
import logging
import traceback
from app.common.models import Advisor, Notifications
from app.repositories.base_repo import BaseRepo
from app.twilio_service.services.twilio_service import send_sms
from auth_service.services.settings_service import get_setting
import os
import ast

logger = logging.getLogger(__name__)
class AdvisorRepo(BaseRepo):    
    def __init__(self, db):
        super().__init__(db)

  
    def send_missed_call_alert(self, customer_details=None):
        if customer_details is None:
            return
        
        customer_name = customer_details.get("customer_name")
        customer_phone = customer_details.get("customer_phone")
        transfer_target_name = customer_details.get("transfer_target_name")
        transfer_target_phone = customer_details.get("transfer_target_phone")
        call_id = customer_details.get("call_id")

        notification_phones_id = get_setting(self.db, "MISSING_AGENT_INFORM")
        if isinstance(notification_phones_id, str) and notification_phones_id.startswith('"') and notification_phones_id.endswith('"'):
            notification_phones_id = notification_phones_id[1:-1]

        advisor_ids = ast.literal_eval(notification_phones_id)
        success_count = 0
        try:
            for advisor_id in advisor_ids:
                advisor = self.db.query(Advisor).filter(Advisor.id == advisor_id).first()
                advisor_number = advisor.phone_number if advisor else None

                message = (
                    f"Missed Call Alert! A customer, {customer_name} {customer_phone}, called and was transferred to {transfer_target_name} {transfer_target_phone},"
                    f"but the call went unanswered. Kindly return the customer's call at your earliest convenience."
                    f"\nDealerPulse"
                    f"\nCall ID: {call_id}"
                )

                if advisor:
                    notification = Notifications(
                        user_id=advisor.user_id,
                        advisor_id=advisor.id,
                        call_id=call_id,
                        notification_type="missed_call",
                        customer_phone=customer_phone,
                        customer_name=customer_name,
                        title=f"Missed Call from {customer_phone}",
                        message=f"You have recieved a missed call from {customer_phone}. Please call them back as soon as possible.",
                        is_read=False,
                        created_at=datetime.now(timezone.utc),
                        updated_at=datetime.now(timezone.utc),
                    )
                    self.db.add(notification)
                    self.db.commit()
                send_sms(
                    to_number=advisor_number,
                    message=message,
                    from_number=os.getenv("TWILIO_FROM_NUMBER"),
                )
                success_count += 1

        except Exception as e:
            print(traceback.format_exc())
            print(f"Failed to send SMS to any of the advisors: {str(e)}")