import click
import logging

from yp.client import YpClient, find_token
from saas.tools.devops.lib23.nanny_helpers import NannyService


@click.command()
@click.option('--cluster', default='sas', help='Yp cluster to work with')
@click.option('--account-id', default='abc:service:664', help='Account id to cleanup')
@click.option('--do-remove', default=False, help='Set it to True if you need to do cleanup.')
def main(cluster, account_id, do_remove):

    orphan_pods, orphan_podsets = find_orphan_yp_podsets(cluster, account_id)

    if do_remove:
        for pod in orphan_pods:
            remove_pod(pod)
        for podset in orphan_podsets:
            remove_podset(podset)


def remove_pod(pod_id):
    yp = YpClient('man', config={'token': find_token()})
    yp.remove_object('pod', pod_id)


def remove_podset(podset_id):
    yp = YpClient('man', config={'token': find_token()})
    yp.remove_object('pod_set', podset_id)


def find_orphan_yp_podsets(cluster, account_id):
    yp = YpClient('man', config={'token': find_token()})
    all_podset_info = yp.select_objects(
        'pod_set',
        filter="[/spec/account_id] = '{}' AND [/labels/deploy_engine] = 'YP_LITE'".format(account_id),
        selectors=["/labels/nanny_service_id", "/meta/id"]
        )

    orphan_podsets = []
    orphan_pods = []
    total_lost_cpu = 0
    total_lost_mem = 0
    for _ in all_podset_info:
        ns_id, ps_id = tuple(_)
        try:
            ns = NannyService(ns_id)
            ns  # just for linter
        except:
            logging.debug(ns_id)
            orphan_podsets.append(ps_id)
            pods = yp.select_objects(
                'pod',
                selectors=["/meta/id", "/spec/resource_requests/vcpu_guarantee", "/spec/resource_requests/memory_guarantee"],
                filter="[/meta/pod_set_id] = 'saas-yp-ydo-priemka'",
                limit=1
                )
            for pod in pods:
                pod_id, cpu, mem = tuple(pod)
                orphan_pods.append(pod_id)
                total_lost_cpu += cpu
                total_lost_mem += mem

    print cluster
    print orphan_podsets
    print orphan_pods
    print total_lost_cpu / 1000
    print total_lost_mem / 1024 / 1024 / 1024

    return orphan_pods, orphan_podsets

if __name__ == '__main__':
    main()
