"""
Search Service Celery Tasks.

Async tasks for search indexing with retry and batch processing.
"""
from celery import shared_task

import logging

logger = logging.getLogger(__name__)


@shared_task(bind=True, max_retries=3)
def process_search_index_queue(self, batch_size: int = 50):
    """
    Process pending items in the search index queue.
    
    Run periodically via Celery Beat to drain the queue.
    """
    from .worker import SearchIndexWorker

    try:
        processed = SearchIndexWorker.process_batch(batch_size=batch_size)
        return {'processed': processed}
    except Exception as e:
        logger.error(f"Search queue processing error: {e}")
        raise self.retry(exc=e, countdown=60)


@shared_task(bind=True)
def enqueue_entity_index(
    self,
    tenant_id: str,
    entity_type: str,
    entity_id: str,
    operation: str = 'index',
    payload: dict = None,
    priority: int = 50,
):
    """
    Enqueue an entity for search indexing.
    
    Called when entities are created/updated/deleted to schedule indexing.
    """
    from .models import SearchIndexQueue

    try:
        SearchIndexQueue.objects.create(
            tenant_id=tenant_id,
            entity_type=entity_type,
            entity_id=entity_id,
            operation=operation,
            payload=payload or {},
            priority=priority,
        )
        logger.debug(f"Enqueued {operation} for {entity_type}:{entity_id}")
    except Exception as e:
        logger.error(f"Failed to enqueue index: {e}")


@shared_task(bind=True)
def reindex_entity_type(self, tenant_id: str, entity_type: str):
    """
    Schedule full reindex for an entity type.
    """
    from .models import SearchIndexQueue, IndexOperation

    try:
        SearchIndexQueue.objects.create(
            tenant_id=tenant_id,
            entity_type=entity_type,
            entity_id='00000000-0000-0000-0000-000000000000',
            operation=IndexOperation.REINDEX,
            payload={'entity_type': entity_type},
            priority=100,
        )
        logger.info(f"Scheduled reindex for {entity_type}")
    except Exception as e:
        logger.error(f"Failed to schedule reindex: {e}")


@shared_task
def cleanup_completed_queue_items(days_old: int = 7):
    """
    Clean up completed queue items older than N days.
    """
    from datetime import timedelta
    from django.utils import timezone
    from .models import SearchIndexQueue, QueueStatus

    cutoff = timezone.now() - timedelta(days=days_old)
    deleted, _ = SearchIndexQueue.objects.filter(
        status=QueueStatus.COMPLETED,
        processed_at__lt=cutoff,
    ).delete()

    logger.info(f"Cleaned up {deleted} completed search index queue items")
    return {'deleted': deleted}
