"""
Wagtail signal handlers：发布内容后通知 Next.js 前端失效 ISR 缓存。
详见 documents/设计方案分析与完善版.md §2.7。
"""
import logging

import requests
from django.conf import settings
from django.dispatch import receiver
from wagtail.signals import page_published

logger = logging.getLogger(__name__)


@receiver(page_published)
def notify_frontend_revalidate(sender, instance, **kwargs):
    if not settings.FRONTEND_REVALIDATE_URL:
        return
    try:
        requests.post(
            settings.FRONTEND_REVALIDATE_URL,
            json={"tags": [f"page:{instance.id}", instance.url_path]},
            headers={"Authorization": f"Bearer {settings.REVALIDATE_SECRET}"},
            timeout=3,
        )
    except requests.RequestException:
        logger.warning("Failed to notify frontend revalidate webhook", exc_info=True)
