import os
from collections import defaultdict
from django.core.management.base import BaseCommand

from intranet.search.core.utils.ydeploy import get_celery_workers_config


TEMPLATE = """[program:celery-{name}{suffix}]
user=www-data
command=isearch-celery worker
    -Ofair
    --without-gossip --without-heartbeat
    -C -q -l {loglevel} -f {name}{suffix}
    -n {name}{suffix}@%%h
    -Q {queue}
    -P {pool}
    -c {concurrency}
    -A intranet.search.core.celery.{app}_app
    {env_celery_opts}
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
"""

GROUP_TEMPLATE = """[group:celery-{app}]
programs={workers}
"""


class Command(BaseCommand):
    help = 'Генерирует опции для запуска различных celery'

    def add_arguments(self, parser):
        parser.add_argument('--names-only', '-n', action='store_true', default=False)

    def handle(self, **options):
        suffixes = set()
        names = defaultdict(list)
        for name, data in get_celery_workers_config():
            program_name = 'celery-{name}{suffix}'.format(name=name, suffix=data['suffix'])
            data['queue'] = ','.join(data['queue'])
            data['env_celery_opts'] = os.environ.get('ENV_ISEARCH_CELERY_OPTS', '')

            if data['suffix']:
                suffixes.add(data['suffix'])
            if options['names_only']:
                print(program_name)
            else:
                names[data['app']].append(program_name)
                print(TEMPLATE.format(**data))

        for app, workers in names.items():
            print(GROUP_TEMPLATE.format(app=app, workers=','.join(workers)))

        if len(suffixes) > 1:
            raise RuntimeError('More than one suffix set for workers, got %s' % suffixes)
