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

import logging
import argparse
import json
import re

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

from saas.tools.devops.lib23.saas_entity import SaaSEntity
from saas.tools.devops.lib.gencfg_svncli_api import GencfgSVNApi

LOCATIONS = ["SAS", "MAN", "VLA", "MSK", "ALL"]


def parse_cmd_args():

    description = '''
Helps to set useful options in gencfg groups

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/}'

'''

    parser = argparse.ArgumentParser(description=description)

    parser.add_argument(
        '-l', '--list-topology',
        default=False,
        action='store_true',
        help='Print actual service topology and exit'
    )

    parser.add_argument(
        '-d', '--debug',
        default=False,
        action='store_true',
        help='Dump actual debug info'
    )

    parser.add_argument(
        '-s', '--nanny-service',
        type=str,
        help='Nanny service to add replics into'
    )

    parser.add_argument(
        '--gencfg-groups',
        nargs='+',
        help='Gencfg group to add replics into'
    )

    parser.add_argument(
        '--saas-service',
        type=str,
        help='SaaS service to add replics into'
    )

    parser.add_argument(
        '--saas-ctype',
        type=str,
        help='SaaS ctype'
    )

    parser.add_argument(
        '--gencfg-path',
        default=None,
        help="Path to gencfg working copy"
    )

    parser.add_argument(
        '--cpu-guarantee',
        type=int,
        help='New guarantee for this service'
    )

    parser.add_argument(
        '--cpu-limit',
        # type=int,
        help='New limit for this service'
    )

    parser.add_argument(
        '--update-tags',
        action='store_true',
        help='Update prj tags for service'
    )

    parser.add_argument(
        '--mark-saas-no-indexing',
        action='store_true',
        help='Update itag=[saas-no-indexing] for service'
    )

    return parser.parse_args()


def get_current_topology(service):
    response = ns.get_service_runtime_attrs(service)
    return response.json()["content"]["instances"]["extended_gencfg_groups"]["groups"]


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)

    args = parse_cmd_args()
    if args.debug:
        logging.info("Config : {}".format(str(args)))

    if args.gencfg_groups:
        gencfg_groups = args.gencfg_groups
    else:
        if args.nanny_service:
            nanny_service = args.nanny_service
        else:
            saas_entity = SaaSEntity()

            if args.saas_ctype:
                saas_entity.set_saas_ctype(args.saas_ctype)

            if args.saas_service:
                saas_entity.set_saas_service(args.saas_service)

            if args.nanny_service:
                saas_entity.set_nanny_service(args.nanny_service)

            # if args.gencfg_group:
            #     saas_entity.set_gencfg_group(args.gencfg_group)

            params = {}
            try:
                params = saas_entity.get_entity()
            except:
                logging.error("Could not guess params with SaaS entity predictor")
                exit(1)

            nanny_service = params.get("nanny_service", args.nanny_service)

        topology = get_current_topology(nanny_service)
        gencfg_groups = [x['name'] for x in topology]

        # limits_override = False
        for x in topology:
            if 'limits' in x and ('cpu_limit' in x['limits'] or 'cpu_guarantee' in x['limits']):
                # limits_override = True
                logging.debug('Limits are overriden for service %s, group %s!', nanny_service, x['name'])
                # break

        if args.list_topology:
            print(json.dumps(topology, indent=2))
            return 0

    gencfg = GencfgSVNApi(args.gencfg_path, do_update=True, skip_check=True)

    if args.update_tags:

        prefix = ""
        if args.saas_ctype:
            if args.saas_ctype == 'stable':
                prefix = 'saas-'

            if args.saas_ctype == 'stable_kv':
                prefix = 'saas-kv-'

            if args.saas_ctype == 'stable_middle_kv':
                prefix = 'saas-middle-kv-'

        for group in gencfg_groups:

            prj_tag = prefix + re.sub("_", "-", args.saas_service)
            update_tags_script = 'time ./utils/common/update_card.py -g {} -k tags.prj -v "[{}]" -y'.format(group, prj_tag)
            gencfg.execute_gencfg_script(update_tags_script, fail_on_error=True)

    if args.mark_saas_no_indexing:
        for group in gencfg_groups:

            set_no_indexing_script = './utils/common/update_card.py -g {} -k tags.itag -v "[saas_no_indexing]" -y'.format(group)
            gencfg.execute_gencfg_script(set_no_indexing_script, fail_on_error=True)

    if args.cpu_guarantee:
        for group in gencfg_groups:

            # Set cpu guarantee
            set_guarantee_script = './utils/common/fix_cpu_guarantee.py -g {} -p {}'.format(group, args.cpu_guarantee)
            gencfg.execute_gencfg_script(set_guarantee_script, fail_on_error=True)

    if args.cpu_limit:
        for group in gencfg_groups:

            # Set greedy class
            set_greedy_script = './utils/common/update_card.py -g {} -k audit.cpu.class_name -v "greedy" -y'.format(group)
            gencfg.execute_gencfg_script(set_greedy_script,  fail_on_error=True)

            # Set cpu limit = guarantee + 1 core
            if args.cpu_limit:

                if args.cpu_limit in ['auto']:
                    new_cpu_limit = args.cpu_guarantee + 40
                else:
                    new_cpu_limit = args.cpu_limit

                set_greedy_limit_script = './utils/common/update_card.py -g {} -k audit.cpu.greedy_limit -v "{}" -y'.format(group, new_cpu_limit)
                gencfg.execute_gencfg_script(set_greedy_limit_script, fail_on_error=True)

if __name__ == "__main__":

    main()
