"""
Avisa a la landing que vuelva a pedir el catálogo del generador.

Lo corre el script de deploy al final, después de `collectstatic` y del
reinicio: para entonces el catálogo nuevo ya es el que contesta la API. A mano
sirve para forzar que la landing se sincronice.

Sin `LANDING_CATALOG_WEBHOOK_URL` o sin secreto no avisa y lo dice, sin fallar:
una instalación sin landing no tiene a quién avisar. Si la landing no contesta
o contesta con error, falla: quien corrió el deploy tiene que enterarse, aunque
el cron horario de la landing lo vaya a cubrir.

**Lo que imprime va en inglés y no pasa por el catálogo.** Es la salida de una
herramienta de operación, no interfaz.
"""

import httpx
from django.core.management.base import BaseCommand, CommandError

from apps.ai import webhook


class Command(BaseCommand):
    help = 'Tell the landing to fetch the image generator catalog again.'

    def handle(self, *args, **options):
        try:
            delivery = webhook.notify_catalog()
        except webhook.WebhookNotConfigured:
            self.stdout.write(
                'LANDING_CATALOG_WEBHOOK_URL or LANDING_WEBHOOK_SECRET is not set: '
                'nothing to notify.'
            )
            return
        except httpx.HTTPError as error:
            raise CommandError(f'The landing did not accept the notice: {error}') from error

        self.stdout.write(
            f'Notified catalog version {delivery.version[:12]} (HTTP {delivery.status_code}).'
        )
