#!/usr/bin/env python
# -*- coding: utf-8 -*-

import logging
import argparse

import search.tools.devops.libs.utils as u

from saas.tools.devops.lib23.saas_entity import saas_service_iterator
import saas.tools.devops.lib23.saas_entity as saas_entity

NANNY_URL = 'http://nanny.yandex-team.ru/'


def parse_cmd_args():

    description = '''
Creates endpointsets for yp saas service

You need to have defined OAuth tokens for nanny and sandbox in your ENV, just like this:
    export OAUTH_NANNY='{Get your token here : https://nanny.yandex-team.ru/ui/#/oauth/}'
    export NANNY_OAUTH_TOKEN='{Get your token here : https://nanny.yandex-team.ru/ui/#/oauth/}'

'''

    parser = argparse.ArgumentParser(description=description, parents=[saas_entity.get_saas_entity_arg_parser(), ])

    parser.add_argument(
        '-d', '--debug',
        default=False,
        action='store_true',
        help='Dump actual debug info'
    )
    parser.add_argument('-k', '--skip-dm-update', default=False, action='store_true')
    parser.add_argument('-ds', '--disable-search', default=False, action='store_true')
    parser.add_argument('--batch', default=False, action='store_true')
    parser.add_argument('--force-mixed-allocaion', default=False, action='store_true')

    return parser.parse_args()


def main():

    args = parse_cmd_args()
    if args.debug:
        u.logger_setup(verbose_level=2)
        logging.info("Config : {}".format(str(args)))
    else:
        u.logger_setup(verbose_level=1)

    ctypes = [args.saas_ctype]  # if args.saas_ctype is not None or None
    saas_services = [args.saas_service]  # if args.saas_service is not None or None

    yp_services = []
    semi_yp_services = []
    non_yp_services = []
    wtf_services = []

    for ss in saas_service_iterator(saas_ctypes=ctypes, saas_services=saas_services):
        has_yp = False
        has_gencfg = False
        try:
            for ns in ss.nanny_services:
                if ns.is_yp_lite():
                    has_yp = True
                if ns.is_gencfg_allocated():
                    has_gencfg = True
            if has_yp and not has_gencfg:
                yp_services.append(ss)
            elif not has_yp and has_gencfg:
                non_yp_services.append(ss)
            elif has_yp and has_gencfg:
                semi_yp_services.append(ss)
            else:
                wtf_services.append(ss)
        except:
            wtf_services.append(ss)
            logging.exception('Err while processing service %s', ss.name)

    logging.debug('Found %s yp-allocated services : %s\n', len(yp_services), yp_services)
    logging.debug('Found %s services with mixed allocation : %s\n', len(semi_yp_services), semi_yp_services)
    logging.debug('Found %s non-yp-allocated services : %s\n', len(non_yp_services), non_yp_services)
    logging.debug('Errors occured while determining allocation type for %s services : %s\n', len(wtf_services), wtf_services)

    services_to_be_endpointed = [] + yp_services
    if args.force_mixed_allocaion:
        services_to_be_endpointed += semi_yp_services

    assert args.batch or len(services_to_be_endpointed) == 1, 'Need to allow batch processing explicitly'

    for yss in services_to_be_endpointed:
        logging.info("Endpointing in service {}/{}".format(yss.ctype, yss.name))
        try:
            yss.update_pod_labels(update_disable_search=args.disable_search)
            yss.create_endpointsets(do_update_dm=not args.skip_dm_update)
        except:
            logging.exception("Error while endpointsetting %s/%s", yss.ctype, yss.name)


if __name__ == "__main__":
    main()
