#!/usr/bin/python

import logging
import argparse
import os

import saas.tools.devops.lib23.saas_entity as saas_entity
import search.tools.devops.libs.utils as u

from saas.library.python.gencfg.group import GencfgGroup, GENCFG_GROUPS_LOCATIONS
from saas.tools.ssm.modules.gencfg_api import GencfgGroupRequest
from saas.tools.devops.lib23.crutches import number_or_diff


def parse_cmd_args():
    description = '''
Works only for services allocated in *_SAAS_CLOUD

Need environment variable OAUTH_SANDBOX with sandbox token

You don't need to specify all possible args.
In most cases service (nanny or saas) and hosts quantity will be enough
'''
    parser = argparse.ArgumentParser(description=description, parents=[saas_entity.get_saas_entity_arg_parser(), ])

    parser.add_argument('-d', '--debug', action='store_true',
                        help='More debug info')

    parser.add_argument('-n', '--new-hosts-count', type=number_or_diff, required=True,
                        help='Change instance number: +x to add; -x to reduce; =x to set exact number (per location)')

    parser.add_argument('--geo', choices=GENCFG_GROUPS_LOCATIONS, nargs='+',
                        help='Add replicas only in given locations (will not work if there is no gencfg group in location)')

    parser.add_argument('--conflicting-groups', type=GencfgGroup.from_str, nargs='+',
                        help='Gencfg groups with antiaffinity to target')

    parser.add_argument('-t', '--ticket',
                        help='Startrek ticket if any')

    parser.add_argument('-w', '--wait-tag',
                        help='Wait for gencfg tag with change')

    parser.add_argument('--dry-run', action='store_true',
                        help='Just pretend. Do not commit anything to gencfg repo')

    return parser.parse_args()


def main():

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

    saas_service = saas_entity.get_saas_service_from_args(args)  # type: saas_entity.s_service.SaasService

    if args.geo:
        gencfg_groups = filter(lambda s: s.location in args.geo, saas_service.gencfg_groups)
    else:
        gencfg_groups = saas_service.gencfg_groups

    assert len(gencfg_groups) == len(set([g.location for g in gencfg_groups])), 'Some locations have more than one group'

    topology_update = GencfgGroupRequest.update_groups(
        [g.name for g in gencfg_groups], instance_count_diff=args.new_hosts_count, conflicting_groups=args.conflicting_groups,
        request_author=os.getlogin(), ticket=args.ticket, dry_run=args.dry_run
    )

    new_hosts = []
    for change in topology_update.changes:
        new_hosts.extend(change.added_hosts)

    if new_hosts:
        print('New hosts in groups: {}'.format(new_hosts))

    print('Changes committed in revision: {}'.format(topology_update.commit))

    if args.wait_tag and topology_update.commit > 0:
        tag = topology_update.get_tag_with_wait()
        print('Tag with changes: {}'.format(tag))
    return


if __name__ == '__main__':
    main()
