"""
Background tasks replacing Celery for cPanel shared hosting.
Run with: python manage.py process_tasks
"""
from background_task import background
from django.utils import timezone


@background(schedule=0)
def transition_sale_states():
    """
    Sweep all sales and transition status based on current time.
    upcoming -> live when start_at <= now
    live -> ended when end_at <= now
    Runs every 30 seconds via a scheduled repeat.
    """
    from sales.models import Sale
    from orders.models import Order

    # Release expired pending checkouts so their stock is returned
    Order.release_expired_pending_orders()

    now = timezone.now()

    # upcoming -> live
    upcoming_to_live = Sale.objects.filter(
        status='upcoming',
        start_at__lte=now,
    )
    count_live = upcoming_to_live.update(status='live')

    # live -> ended
    live_to_ended = Sale.objects.filter(
        status='live',
        end_at__lte=now,
    )
    count_ended = live_to_ended.update(status='ended')

    if count_live or count_ended:
        print(f"[SaleTransition] {count_live} -> live, {count_ended} -> ended")


@background(schedule=0)
def send_booking_confirmation(business_id):
    """Send booking confirmation email to a business."""
    from businesses.models import Business
    from django.core.mail import send_mail
    from django.conf import settings

    try:
        business = Business.objects.get(id=business_id)
    except Business.DoesNotExist:
        return

    send_mail(
        subject='Booking Confirmed -- FlashSale',
        message=(
            f"Hello {business.name},\n\n"
            f"Your sale slot has been booked successfully.\n"
            f"Log in to your dashboard to add products and set up your sale.\n\n"
            f"-- FlashSale Platform"
        ),
        from_email=settings.DEFAULT_FROM_EMAIL,
        recipient_list=[business.email],
        fail_silently=True,
    )


@background(schedule=0)
def send_order_confirmation(order_id):
    """Send order confirmation email to buyer."""
    from orders.models import Order
    from django.core.mail import send_mail
    from django.conf import settings

    try:
        order = Order.objects.select_related('sale__business').get(id=order_id)
    except Order.DoesNotExist:
        return

    send_mail(
        subject=f'Order Confirmed -- {order.order_number}',
        message=(
            f"Hello {order.buyer_name},\n\n"
            f"Your order #{order.order_number} has been confirmed.\n"
            f"Sale: {order.sale.title}\n"
            f"Total: GHS {order.total_amount}\n\n"
            f"The seller ({order.sale.business.name}) will be in touch regarding delivery.\n\n"
            f"-- FlashSale Platform"
        ),
        from_email=settings.DEFAULT_FROM_EMAIL,
        recipient_list=[order.buyer_email],
        fail_silently=True,
    )


@background(schedule=0)
def process_product_image(image_id):
    """Generate thumbnail, medium, large, and WebP variants of a product image."""
    import os
    from io import BytesIO
    from PIL import Image
    from django.core.files.base import ContentFile
    from django.conf import settings as django_settings
    from products.models import ProductImage

    try:
        product_image = ProductImage.objects.get(id=image_id)
    except ProductImage.DoesNotExist:
        return

    product_image.processing_status = 'processing'
    product_image.save(update_fields=['processing_status'])

    try:
        img = Image.open(product_image.image)
        if img.mode in ('RGBA', 'P'):
            img = img.convert('RGB')

        sizes = django_settings.IMAGE_SIZES

        # Thumbnail
        thumb = img.copy()
        thumb.thumbnail(sizes['thumbnail'], Image.LANCZOS)
        thumb_io = BytesIO()
        thumb.save(thumb_io, format='JPEG', quality=85)
        product_image.thumbnail.save(
            f"thumb_{product_image.image.name.split('/')[-1]}",
            ContentFile(thumb_io.getvalue()),
            save=False,
        )

        # Medium
        med = img.copy()
        med.thumbnail(sizes['medium'], Image.LANCZOS)
        med_io = BytesIO()
        med.save(med_io, format='JPEG', quality=85)
        product_image.medium.save(
            f"med_{product_image.image.name.split('/')[-1]}",
            ContentFile(med_io.getvalue()),
            save=False,
        )

        # Large
        lg = img.copy()
        lg.thumbnail(sizes['large'], Image.LANCZOS)
        lg_io = BytesIO()
        lg.save(lg_io, format='JPEG', quality=90)
        product_image.large.save(
            f"lg_{product_image.image.name.split('/')[-1]}",
            ContentFile(lg_io.getvalue()),
            save=False,
        )

        # WebP
        webp = img.copy()
        webp.thumbnail(sizes['large'], Image.LANCZOS)
        webp_io = BytesIO()
        webp.save(webp_io, format='WEBP', quality=85)
        product_image.webp.save(
            f"{os.path.splitext(product_image.image.name.split('/')[-1])[0]}.webp",
            ContentFile(webp_io.getvalue()),
            save=False,
        )

        product_image.processing_status = 'done'
        product_image.save()

    except Exception as e:
        product_image.processing_status = 'failed'
        product_image.save(update_fields=['processing_status'])
        print(f"[ImageProcess] Failed for {image_id}: {e}")
