# coding: utf-8


import socket
import glob
import os

from django.core.management.base import BaseCommand

from idm.celery_app import app

OK = '0;OK'


class Command(BaseCommand):
    """
    inspect_celery management command
    Prints '0;OK' if all ok.
    Prints '2;{error description}' in case of error.
    """
    help = (
        'Trying to determine if every workerset is available.'
        'Returns status in monrun-compliant format'
    )
    requires_system_checks = False

    def handle(self, *args, **options):
        try:
            hostname = socket.gethostname()
            paths = glob.glob('/etc/yandex/idm/celery/*.conf')
            queues = [os.path.splitext(os.path.split(path)[1])[0] for path in paths]
            inspect = app.control.inspect(timeout=5)
            active = inspect.active()
            if active is None:
                active = {}
            active = active.keys()
            absent_queues = [queue for queue in queues if '%s@%s' % (queue, hostname) not in active]
            if absent_queues:
                print('2;Queues not responding: %s' % ','.join(absent_queues))
            else:
                print(OK)
        except Exception as exc:
            print('2;Unhandled exception:{0}'.format(exc))
