import signal
import time

from django.conf import settings
from django.core.management.base import BaseCommand, CommandError

from api.services.integration.publisher import publish_once


class Command(BaseCommand):
    help = "Publish eligible Timetabler canonical outbox events to the Resource Booking sync adapter."

    def add_arguments(self, parser):
        parser.add_argument("--once", action="store_true")
        parser.add_argument("--interval", type=float, default=1.0)
        parser.add_argument("--batch-size", type=int)

    def handle(self, *args, **options):
        if not settings.RESOURCE_BOOKING_INTEGRATION["PUBLISH_ENABLED"]:
            raise CommandError(
                "RB publisher is disabled; complete preflight and set the explicit activation gate first"
            )
        stopping = False

        def stop(*_):
            nonlocal stopping
            stopping = True

        signal.signal(signal.SIGTERM, stop)
        signal.signal(signal.SIGINT, stop)
        while not stopping:
            result = publish_once(limit=options["batch_size"])
            if any((result.claimed, result.published, result.retried, result.dead_lettered)):
                self.stdout.write(
                    f"claimed={result.claimed} published={result.published} "
                    f"retried={result.retried} dead_lettered={result.dead_lettered}"
                )
            if options["once"]:
                break
            time.sleep(max(0.05, options["interval"]))
