"""
Django signals for search index maintenance
"""
from django.db.models.signals import post_save, post_delete, m2m_changed
from django.dispatch import receiver
from .models import Link, Page, Post, Bookmark
from .search_backend import search_backend
import logging

logger = logging.getLogger(__name__)


@receiver(post_save, sender=Link)
def update_link_index(sender, instance, created, **kwargs):
    """Update search index when a link is saved"""
    try:
        search_backend.index_link(instance)
    except Exception as e:
        logger.error(f"Error indexing link {instance.id}: {e}")


@receiver(post_save, sender=Page)
def update_page_index(sender, instance, created, **kwargs):
    """Update search index when a page is saved"""
    try:
        search_backend.index_page(instance)
    except Exception as e:
        logger.error(f"Error indexing page {instance.id}: {e}")


@receiver(post_save, sender=Post)
def update_post_index(sender, instance, created, **kwargs):
    """Update search index when a post is saved"""
    try:
        search_backend.index_post(instance)
    except Exception as e:
        logger.error(f"Error indexing post {instance.id}: {e}")


@receiver(post_save, sender=Bookmark)
def update_bookmark_index(sender, instance, created, **kwargs):
    """Update search index when a bookmark is saved (e.g. bulk import /
    AI summary update via API)."""
    try:
        search_backend.index_bookmark(instance)
    except Exception as e:
        logger.error(f"Error indexing bookmark {instance.id}: {e}")


@receiver(post_delete, sender=Link)
def remove_link_from_index(sender, instance, **kwargs):
    """Remove link from search index when deleted"""
    try:
        search_backend.remove_from_index('link', instance.id)
    except Exception as e:
        logger.error(f"Error removing link {instance.id} from index: {e}")


@receiver(post_delete, sender=Page)
def remove_page_from_index(sender, instance, **kwargs):
    """Remove page from search index when deleted"""
    try:
        search_backend.remove_from_index('page', instance.id)
    except Exception as e:
        logger.error(f"Error removing page {instance.id} from index: {e}")


@receiver(post_delete, sender=Post)
def remove_post_from_index(sender, instance, **kwargs):
    """Remove post from search index when deleted"""
    try:
        search_backend.remove_from_index('post', instance.id)
    except Exception as e:
        logger.error(f"Error removing post {instance.id} from index: {e}")


@receiver(post_delete, sender=Bookmark)
def remove_bookmark_from_index(sender, instance, **kwargs):
    """Remove bookmark from search index when deleted"""
    try:
        search_backend.remove_from_index('bookmark', instance.id)
    except Exception as e:
        logger.error(f"Error removing bookmark {instance.id} from index: {e}")


@receiver(m2m_changed, sender=Link.tags.through)
def update_link_tags_index(sender, instance, action, **kwargs):
    """Update link index when tags change"""
    if action in ['post_add', 'post_remove', 'post_clear']:
        try:
            search_backend.index_link(instance)
        except Exception as e:
            logger.error(f"Error updating link {instance.id} tags in index: {e}")


@receiver(m2m_changed, sender=Page.tags.through)
def update_page_tags_index(sender, instance, action, **kwargs):
    """Update page index when tags change"""
    if action in ['post_add', 'post_remove', 'post_clear']:
        try:
            search_backend.index_page(instance)
        except Exception as e:
            logger.error(f"Error updating page {instance.id} tags in index: {e}")


@receiver(m2m_changed, sender=Post.tags.through)
def update_post_tags_index(sender, instance, action, **kwargs):
    """Update post index when tags change"""
    if action in ['post_add', 'post_remove', 'post_clear']:
        try:
            search_backend.index_post(instance)
        except Exception as e:
            logger.error(f"Error updating post {instance.id} tags in index: {e}")
