from celery import shared_task
from .pms_integration import PMSService
from .models import HotelBooking
from celery.exceptions import MaxRetriesExceededError
import logging
from django.conf import settings

logger = logging.getLogger(__name__)

@shared_task(bind=True)
def sync_booking_to_pms_task(self, booking_id):
    """
    Async task to sync booking to PMS.
    """
    # Load settings
    max_retries = getattr(settings, 'PMS_MAX_RETRIES', 3)
    retry_delay = 60  # Base delay in seconds

    try:
        booking = HotelBooking.objects.get(id=booking_id)
        logger.info(f"Starting PMS sync for booking {booking_id} (Task ID: {self.request.id})")
        
        success = PMSService.send_booking(booking)
        
        if not success:
            logger.warning(f"PMS sync failed for booking {booking_id}. Retrying...")
            try:
                raise self.retry(countdown=retry_delay, max_retries=max_retries)
            except MaxRetriesExceededError:
                logger.error(f"Max retries exceeded for PMS sync of booking {booking_id}")
                return False
            
        logger.info(f"PMS sync successful for booking {booking_id}")
        return True
        
    except HotelBooking.DoesNotExist:
        logger.error(f"Booking {booking_id} does not exist. Cannot sync to PMS.")
        return False
        
    except Exception as exc:
        logger.error(f"Exception during PMS sync for booking {booking_id}: {str(exc)}")
        try:
            raise self.retry(exc=exc, countdown=retry_delay, max_retries=max_retries)
        except MaxRetriesExceededError:
            logger.error(f"Max retries exceeded for PMS sync of booking {booking_id}")
            return False

def send_hotel_bill_email_task(booking_id):
    from django.core.mail import EmailMultiAlternatives
    from django.template.loader import render_to_string
    from django.utils.html import strip_tags
    try:
        booking = HotelBooking.objects.get(id=booking_id)
        if not booking.email:
            logger.warning(f"No email provided for booking {booking_id}")
            return False

        context = {
            'hotel_name': booking.hotel.name,
            'hotel_city': booking.hotel.city,
            'guest_name': booking.guest_name or booking.user.get_full_name() or booking.user.username,
            'invoice_number': booking.invoice_number or f"INV-HB-{booking.id}",
            'check_in': booking.check_in,
            'check_out': booking.check_out,
            'room_type': booking.room_type.name,
            'rooms_booked': booking.rooms_booked,
            'nights': booking.nights,
            'total_amount': booking.total_amount,
        }

        html_content = render_to_string('hotel/emails/hotel_bill.html', context)
        text_content = strip_tags(html_content)
        
        subject = f"Your Bill/Invoice for {booking.hotel.name}"
        from_email = settings.DEFAULT_FROM_EMAIL
        to_email = booking.email

        email = EmailMultiAlternatives(subject, text_content, from_email, [to_email])
        email.attach_alternative(html_content, "text/html")
        email.send()
        
        logger.info(f"Successfully sent hotel bill email for booking {booking_id} to {to_email}")
        return True
    except HotelBooking.DoesNotExist:
        logger.error(f"Booking {booking_id} does not exist. Cannot send email.")
        return False
    except Exception as exc:
        logger.error(f"Exception during sending hotel bill email for booking {booking_id}: {str(exc)}")
        return False

def send_hotel_bill_whatsapp_task(booking_id):
    try:
        from .models import HotelBooking
        booking = HotelBooking.objects.get(id=booking_id)
        
        phone = booking.mobile or (booking.user.phone if hasattr(booking.user, 'phone') else None)
        if not phone:
            logger.warning(f"No phone provided for booking {booking_id}")
            return False

        message = (
            f"Thank you for your stay at {booking.hotel.name}!\n"
            f"Your booking (ID: {booking.id}) is now completed.\n"
            f"Total Bill Amount: Rs {booking.total_amount}\n"
            f"We have also sent a detailed receipt to your email."
        )

        from restaurant.whatsapp_service import send_reply
        success = send_reply(phone, message)
        
        if success:
            logger.info(f"Successfully sent hotel bill whatsapp for booking {booking_id} to {phone}")
        return success
    except HotelBooking.DoesNotExist:
        logger.error(f"Booking {booking_id} does not exist. Cannot send whatsapp.")
        return False
    except Exception as exc:
        logger.error(f"Exception during sending hotel bill whatsapp for booking {booking_id}: {str(exc)}")
        return False

