from celery import shared_task
from celery.utils.log import get_task_logger
from celery.exceptions import Retry
from apps.business.rewards.services.level_service import process_level_rewards
from apps.business.distributor.models import DistributorID

logger = get_task_logger(__name__)

@shared_task(bind=True, max_retries=3, default_retry_delay=10)
def process_level_rewards_task(self, distributor_id):
    logger.info(f"[START] process_level_rewards_task distributor_id={distributor_id}")
    try:
        distributor = DistributorID.objects.filter(id=distributor_id).first()
        if not distributor:
            logger.error(f"Distributor not found: distributor_id={distributor_id}")
            return
        # Idempotency: check if already processed (e.g., level_rewards_processed flag)
        if hasattr(distributor, 'level_rewards_processed') and distributor.level_rewards_processed:
            logger.info(f"[SKIP] Already processed: distributor_id={distributor_id}")
            return
        result = process_level_rewards(distributor)
        # Optionally set a flag to mark as processed (if model supports it)
        # distributor.level_rewards_processed = True
        # distributor.save(update_fields=["level_rewards_processed"])
        logger.info(f"[SUCCESS] process_level_rewards_task distributor_id={distributor_id} result={result}")
        return result
    except Exception as exc:
        logger.error(f"[FAIL] process_level_rewards_task distributor_id={distributor_id} error={exc}")
        try:
            self.retry(exc=exc)
        except Retry:
            logger.error(f"[RETRY-FAIL] process_level_rewards_task distributor_id={distributor_id}")
