import logging
import argparse

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

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


def parse_cmd_args():

    description = 'Finf SaaS services with old release branches'
    epilog = 'Usage : ./find_old_releases'
    parser = argparse.ArgumentParser(description=description, epilog=epilog)

    parser.add_argument(
        '--saas-ctypes',
        nargs='+',
        default=None,
        help='SaaS ctypes to account'
    )

    parser.add_argument(
        '-d', '--debug',
        default=False,
        action='store_true'
    )

    return parser.parse_args()


def get_saas_releases_stat(ctypes):
    releases = []
    for s in saas_service_iterator(ctypes):
        try:
            releases.append(('{}/{}'.format(s.name, s.ctype), s.get_release_branch()))
        except:
            logging.error("Can't determine release branch of %s/%s", s.ctype, s.name)

    return releases


def main():

    args = parse_cmd_args()
    if args.debug:
        u.logger_setup(2)
        logging.debug(args)
    else:
        u.logger_setup(1)

    releases = get_saas_releases_stat(args.saas_ctypes)
    releases.sort(key=lambda x: x[1])
    for s in releases:
        print(s)


if __name__ == '__main__':
    main()
