"""
Celery tasks for billing operations.

These tasks run periodically to manage subscription-related operations like
grace period tracking for custom tiers.
"""
from datetime import timedelta

from celery import shared_task
from django.utils import timezone
import logging

logger = logging.getLogger(__name__)


@shared_task
def check_subscription_grace_periods():
    """
    Check custom tier grace periods and manage them based on subscription status.

    This task runs daily to:
    1. Clear grace_period_started_at if subscription becomes active
    2. Set grace_period_started_at if subscription becomes inactive
    3. Delete custom tiers where grace period has exceeded 30 days

    Returns:
        dict: Summary of actions taken
    """
    from smoothschedule.billing.models import TenantCustomTier

    results = {
        'custom_tiers_processed': 0,
        'grace_periods_cleared': 0,
        'grace_periods_started': 0,
        'custom_tiers_deleted': 0,
        'errors': [],
    }

    # Get all custom tiers with related business and subscription
    custom_tiers = TenantCustomTier.objects.select_related(
        'business',
        'business__billing_subscription'
    ).all()

    now = timezone.now()

    for custom_tier in custom_tiers:
        try:
            results['custom_tiers_processed'] += 1

            # Check if business has an active subscription
            subscription = custom_tier.business.billing_subscription
            is_active = subscription.is_active if subscription else False

            # Case 1: Subscription is active and grace period is set → clear it
            if is_active and custom_tier.grace_period_started_at is not None:
                custom_tier.grace_period_started_at = None
                custom_tier.save()
                results['grace_periods_cleared'] += 1
                logger.info(
                    f"Cleared grace period for custom tier {custom_tier.id} "
                    f"(business: {custom_tier.business.name})"
                )

            # Case 2: Subscription is inactive and grace period not set → start it
            elif not is_active and custom_tier.grace_period_started_at is None:
                custom_tier.grace_period_started_at = now
                custom_tier.save()
                results['grace_periods_started'] += 1
                logger.info(
                    f"Started grace period for custom tier {custom_tier.id} "
                    f"(business: {custom_tier.business.name})"
                )

            # Case 3: Grace period started and exceeded 30 days → delete custom tier
            elif custom_tier.grace_period_started_at is not None:
                grace_period_end = custom_tier.grace_period_started_at + timedelta(
                    days=TenantCustomTier.GRACE_PERIOD_DAYS
                )
                if now > grace_period_end:
                    business_name = custom_tier.business.name
                    custom_tier_id = custom_tier.id
                    custom_tier.delete()
                    results['custom_tiers_deleted'] += 1
                    logger.warning(
                        f"Deleted custom tier {custom_tier_id} for business {business_name} "
                        f"- grace period expired"
                    )

        except Exception as e:
            error_msg = f"Error processing custom tier {custom_tier.id}: {str(e)}"
            logger.error(error_msg, exc_info=True)
            results['errors'].append(error_msg)

    logger.info(
        f"Grace period check complete: {results['custom_tiers_processed']} processed, "
        f"{results['grace_periods_cleared']} cleared, "
        f"{results['grace_periods_started']} started, "
        f"{results['custom_tiers_deleted']} deleted"
    )

    return results
