import importlib
import logging
import signal as signal_module

from django.core.management.base import BaseCommand

logger = logging.getLogger("django_devicehub")


class Command(BaseCommand):
    help = "Start the django-devicehub message broker listener"

    def add_arguments(self, parser):
        parser.add_argument(
            "--broker",
            default="default",
            help='Broker name from DJANGO_DEVICEHUB["BROKERS"] (default: "default")',
        )

    def handle(self, *args, **options):
        from django_devicehub.conf import devicehub_settings
        from django_devicehub.registry import registry
        from django_devicehub.routing import MessageRouter

        broker_name = options["broker"]
        broker_config = devicehub_settings.BROKERS.get(broker_name)
        if not broker_config:
            self.stderr.write(
                self.style.ERROR(f"Broker '{broker_name}' not configured")
            )
            return

        # Instantiate the broker engine
        engine = broker_config.get("ENGINE", "django_devicehub.brokers.mqtt.MQTTBroker")
        module_path, class_name = engine.rsplit(".", 1)
        module = importlib.import_module(module_path)
        BrokerClass = getattr(module, class_name)

        broker = BrokerClass(name=broker_name, config=broker_config)

        # Set up message router
        router = MessageRouter()
        broker.set_message_handler(router.handle_message)

        # Graceful shutdown
        def shutdown(signum, frame):
            self.stdout.write("\nShutting down...")
            broker.disconnect()

        signal_module.signal(signal_module.SIGTERM, shutdown)
        signal_module.signal(signal_module.SIGINT, shutdown)

        # Report registered device types
        device_types = registry.all()
        self.stdout.write(
            self.style.SUCCESS(
                f"django-devicehub listener starting on broker '{broker_name}'"
            )
        )
        for dt in device_types:
            if dt._device_model is None:
                self.stdout.write(
                    self.style.WARNING(
                        f"  {dt.__name__}: no models (call create_models())"
                    )
                )
                continue
            topics = dt.get_subscribe_topics()
            self.stdout.write(f"  {dt.__name__}: {', '.join(topics)}")

        if not device_types:
            self.stdout.write(self.style.WARNING("No device types registered"))

        # Connect and block
        broker.connect()
        self.stdout.write(self.style.SUCCESS("Listening for messages..."))
        broker.loop_forever()
