"""IndexNow: tells Bing (which powers ChatGPT search and Copilot), Yandex and others about new or changed URLs
within minutes, instead of waiting for a crawl. Set INDEXNOW_KEY in .env; the storefront serves /<key>.txt."""
import logging
import threading

import requests
from django.conf import settings

log = logging.getLogger(__name__)


def ping(paths):
    key = settings.INDEXNOW_KEY
    if not key or not paths:
        return
    host = settings.SITE_URL.split("//", 1)[-1].rstrip("/")
    urls = [settings.SITE_URL.rstrip("/") + p for p in paths]

    def run():
        try:
            requests.post("https://api.indexnow.org/indexnow", timeout=10, json={
                "host": host, "key": key, "keyLocation": f"{settings.SITE_URL.rstrip('/')}/{key}.txt", "urlList": urls[:10000]})
        except requests.RequestException as e:
            log.warning("IndexNow failed: %s", e)
    threading.Thread(target=run, daemon=True).start()
