from maps.wikimap.stat.tasks_payment.dictionaries.tariff.schema import TariffsSchema

from library.python import resource
from startrek_client import Startrek

import argparse
import yaml


_ENV_TO_URL = {
    'testing': 'https://st-api.test.yandex-team.ru/v2/',
    'production': 'https://st-api.yandex-team.ru/v2/'
}

_RESOURCE_ROOT = 'maps/tasks_tariffs/'
_RESOURCE_TO_QUEUE = {
    _RESOURCE_ROOT + 'cartographic/tracker/feedbackpw': 'FEEDBACKPW',
    _RESOURCE_ROOT + 'cartographic/tracker/mapspw':     'MAPSPW',
    _RESOURCE_ROOT + 'cartographic/tracker/outkartpw':  'OUTKARTPW',
    _RESOURCE_ROOT + 'geotest/archive/geotestpw':       'GEOTESTPW',
}


def _parse_args():
    parser = argparse.ArgumentParser(
        description='Creates components in Tracker queues according to tariffs.'
    )
    parser.add_argument(
        '--tracker-token',
        help=(
            'OAuth token to access to Tracker '
            '(can be obtained at https://oauth.yandex-team.ru/authorize?response_type=token&client_id=5f671d781aca402ab7460fde4050267b)'
        ),
        required=True
    )
    parser.add_argument(
        '--env',
        help=(
            'Tracker environment (default: %(default)s)'
        ),
        choices=_ENV_TO_URL.keys(),
        default='testing'
    )

    return parser.parse_args()


def _get_tracker_client(environment, tracker_token):
    return Startrek(
        useragent='maps.wikimap.stat.tasks_payment.tariffs_to_components',
        base_url=_ENV_TO_URL[environment],
        token=tracker_token
    )


def _get_task_names(tariffs_description_yaml):
    tariffs = TariffsSchema().load(
        yaml.full_load(
            tariffs_description_yaml.decode()
        )
    )
    assert len(tariffs['tariffs']) > 0, 'Tariffs list is empty in the tariffs: {}'.format(tariffs)

    result = set()
    for tariff in tariffs['tariffs']:
        assert 'tasks' in tariff, 'Tariff has no tasks: {}'.format(tariff)

        tasks = tariff['tasks']
        assert len(tasks) == 1, 'Exactly one task is expected: {}'.format(tariff)

        result.add(tasks[0])
    return result


def _create_components(tracker_client, queue_name, task_names):
    print('Create components in queue "{}"'.format(queue_name))
    existing_components = {component.name for component in tracker_client.queues[queue_name].components}

    for task_name in task_names:
        if task_name in existing_components:
            print('Component "{}" already exists'.format(task_name))
            continue

        print('Create component "{}"'.format(task_name))
        tracker_client.components.create(queue=queue_name, name=task_name)


def main():
    args = _parse_args()

    tracker_client = _get_tracker_client(args.env, args.tracker_token)

    for resource_name, tariffs_description_yaml in resource.iteritems(_RESOURCE_ROOT):
        queue_name = _RESOURCE_TO_QUEUE.get(resource_name)
        if queue_name is None:
            continue

        _create_components(
            tracker_client,
            queue_name,
            _get_task_names(tariffs_description_yaml)
        )
