import logging

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

# TBD : export it to nanny lib
def get_current_topology(service):
    response = ns.get_service_runtime_attrs(service)
    topology = None
    if response.ok:
        try:
            topology = response.json()["content"]["instances"]["extended_gencfg_groups"]["groups"]
        except:
            logging.error('Nanny responce is not like valid JSON')
    return topology

# TBD : export it to nanny lib
def get_nanny_limits_override(nanny_service):
    logging.debug("analyzing service {} for overrides".format(nanny_service))
    topology = get_current_topology(nanny_service)
    assert topology is not None, 'Failed to retrieve topology for {} or topology is empty'.format(nanny_service)
    logging.debug("Toopology for service %s is : %s", nanny_service, topology)

    all_limits_override = {}
    for x in topology:
        if 'limits' in x:
            limits_override = {limit: x['limits'][limit] for limit in x['limits'] if limit in ['cpu_guarantee', 'cpu_limit', 'memory_guarantee', 'memory_limit']}
            if len(limits_override) > 0:
                logging.debug('Limits are overriden for service %s, group %s!', nanny_service, x['name'])
                all_limits_override[x['name']] = limits_override

            if "cpu_policy" in x['limits'] and x['limits']["cpu_policy"] == 'rt':
                logging.debug("RT priority detected for service %s, group %s", nanny_service, x['name'])
                limits_override["cpu_policy"] = 'rt'
                all_limits_override[x['name']] = limits_override

    return all_limits_override


def service_overriden(nanny_service):

    report_info = get_nanny_limits_override(nanny_service)
    report_status = len(report_info) > 0

    return report_status, report_info
