import subprocess
import json
import logging

def topology_good(group, generilka_path="/home/i024/GENERILKA", topology=None, check_log=None):

    """
    Reasonable checks :
    "yandex_search_tech_quality_robot_saas" is in group owners,
    group is not empty,
    group has >1 cpu power
    """

    report_status = True
    report_info = {}

    get_owners_script = "./utils/common/show_groups.py -g {} -i owners".format(group)
    logging.debug(get_owners_script)
    get_owners = subprocess.Popen(
        get_owners_script,
        shell=True,
        cwd=generilka_path,
        stdout=subprocess.PIPE
    )
    owners = map(lambda s: s.strip() ,get_owners.stdout.readlines()[0].split(","))

    if "yandex_search_tech_quality_robot_saas" not in owners:
        report_status = False
        report_info["owners"] = owners

    get_power_script = "./utils/common/show_power.py -g {} -t json".format(group)
    logging.debug(get_power_script)
    get_power = subprocess.Popen(
        get_power_script,
        shell=True,
        cwd=generilka_path,
        stdout=subprocess.PIPE
    )
    power = json.loads("".join(get_power.stdout.readlines()))

    instances_count = power[group]['total']['instances_count']
    if  instances_count == 0:
        report_status = False
        report_info['instances_count'] = instances_count

    instances_cpu_avg = power[group]['total']['instances_cpu_avg']
    if  instances_cpu_avg < 40:
        report_status = False
        report_info['instances_cpu_avg'] = instances_cpu_avg

    return report_status, report_info

