"""DMS search — Django signal handlers.

These handlers keep the ``DocumentSearchIndex`` in sync with the
``Document`` and ``DocumentVersion`` models automatically.

They are connected in ``DMSConfig.ready()`` inside apps.py.

Async migration path
--------------------
For production with Celery, replace the direct service calls with task
dispatch, e.g.::

    from simorgh.apps.dms.search.tasks import async_index_document
    async_index_document.delay(instance.pk)

The signal handlers themselves must remain thin — just dispatch.
"""

from __future__ import annotations

import logging

logger = logging.getLogger(__name__)


def on_document_saved(sender, instance, **kwargs) -> None:
    """Re-index the document after every save.

    If the document is soft-deleted we remove it from the index so it no
    longer appears in search results.
    """
    try:
        if getattr(instance, "is_deleted", False):
            from simorgh.apps.dms.search.services import deindex_document
            deindex_document(instance.pk)
        else:
            from simorgh.apps.dms.search.services import index_document
            index_document(instance)
    except Exception:
        logger.exception("search signal: failed to update index for document pk=%s", instance.pk)


def on_version_saved(sender, instance, **kwargs) -> None:
    """Re-index the parent Document whenever one of its versions changes.

    The version's ``document_id`` FK is used to avoid loading the full
    Document if it hasn't changed, but we still re-fetch inside
    ``index_document()`` to get a consistent snapshot.
    """
    try:
        if not instance.document_id:
            return
        from simorgh.apps.dms.documents.models import Document
        from simorgh.apps.dms.search.services import index_document

        # Only index if the parent document still exists and is not deleted.
        doc_qs = Document.objects.filter(pk=instance.document_id, is_deleted=False)
        if doc_qs.exists():
            index_document(doc_qs.get())
    except Exception:
        logger.exception(
            "search signal: failed to re-index document from version pk=%s", instance.pk
        )
