from app.advisor_service.services.advisor_service import process_booking_intent
from app.common.ai_helpers import get_speech_to_text
from app.common.constants import BookingIntent, CronJobStatus, TwilioCallStatus
from app.common.database import get_db
from app.common.models import CallsLog, Advisor, LoginLog
from app.common.twillio_helper import get_call_recording_public_url, get_call_status
from sqlalchemy.orm import Session
import asyncio
from datetime import datetime, date
import traceback
from app.twilio_service.services.twilio_service import send_sms
from auth_service.services.auth_service import logout_advisor, set_user_offline
from app.common.models import AppointmentScheduling
from datetime import datetime, timedelta
import os


def process_booking_intent_async_wrapper():
    """Wrapper function to run the async process_booking_intent_async"""
    asyncio.run(process_booking_intent_async())

async def process_booking_intent_async():
    db = next(get_db())
    try:
        calls = db.query(CallsLog).filter(
            CallsLog.booking_intent_status == CronJobStatus.PENDING
        ).limit(50).all()
        
        for call in calls:
            try:
                call_status = get_call_status(call.twilio_call_id)
                if call_status == TwilioCallStatus.IN_PROGRESS:
                    continue
                await process_booking_intent(call, db)
            except Exception as e:
                call_log = db.query(CallsLog).filter(CallsLog.id == call.id).first()
                call_log.booking_intent_status = CronJobStatus.FAILED
                db.commit()
                db.refresh(call_log)
                print(traceback.format_exc())
                print(f"Error processing booking intent: {str(e)}")
                continue
            
    except Exception as e:
        print(traceback.format_exc())
        print(f"Error processing booking intent: {str(e)}")
    finally:
        db.close()


def logout_all_advisors():
    db = next(get_db())
    try:
        print("Logging out all advisors", flush=True)
        advisors = db.query(Advisor).all()
        for advisor in advisors:
            logout_advisor(advisor.id, db)
            print(f"Logged out advisor {advisor.id}", flush=True)
    except Exception as e:
        print(f"Error logging out all advisors: {str(e)}", flush=True)
    finally:
        db.close()
        
        
def send_appointment_reminders():
    db = next(get_db())
    try:
        print("cron Job")
        now = datetime.utcnow().replace(second=0, microsecond=0)
        target_time = now + timedelta(minutes=30)

        # 🔍 Find appointments scheduled exactly 30 minutes from now
        appointments = db.query(AppointmentScheduling).filter(
            AppointmentScheduling.schedule == target_time,
            AppointmentScheduling.reminder_sent == False
        ).all()
        
        # message = (
        #     f"Hi, this is Hazel from Surfcity Nissan. I just want to remind you that there is a scheduled phone call "
        #     f"from our sales department in 30 minutes. Please be ready for that. Thank you."
        # )
        # print(f"[Reminder] Sending SMS to +923344148734 for appointment at ", flush=True)

        # send_sms(
        #     to_number="+923344148734",
        #     message=message,
        #     from_number=os.getenv('TWILIO_FROM_NUMBER')
        # )

        print(appointments,  now , "==", target_time)
        for appointment in appointments:
            print(appointment.schedule, "55555555",  now)
            message = (
                f"Hi, this is Hazel from SurfCity Nissan. Just a quick reminder about your scheduled"
                f" callback with our sales team in 30 minutes. We look forward to speaking with you!"
            )
            print(f"[Reminder] Sending SMS to {appointment.phone} for appointment at {appointment.schedule}", flush=True)

            send_sms(
                to_number=appointment.phone,
                message=message,
                from_number=os.getenv('TWILIO_FROM_NUMBER')
            )
            appointment.reminder_sent = True
            db.commit()

    except Exception as e:
        print(f"Error sending appointment reminders: {str(e)}", flush=True)
    finally:
        db.close()
