from saas.library.python.common_functions import get_datetime_timestamp
import datetime
from saas.library.python.yasm import signal, constants

COMMON_BALANCER_NAME = "rl-saas-searchproxy.yandex.net"


def mean_rps_last_30m(report='service_total', **kwargs):
    interval_end = datetime.datetime.now()
    interval_begin = interval_end - datetime.timedelta(minutes=30)
    upstream_signal = signal.YasmSignal(
        'balancer_report-report-{}-requests_summ'.format(report.replace('-', '_')),
        **kwargs
    )

    return upstream_signal.signal_iterator.mean(
        get_datetime_timestamp(interval_begin), get_datetime_timestamp(interval_end),
        period=constants.YasmPeriod.five_seconds, normalize=True)


def namespace_id_from_ctype(ctype):
    if ctype == 'common':
        return COMMON_BALANCER_NAME
    if ctype == 'stable':
        return "saas-searchproxy.yandex.net"
    if ctype == 'prestable':
        return "saas-searchproxy-prestable.yandex.net"
    if ctype == 'stable_kv':
        return "saas-searchproxy-kv.yandex.net"
    if ctype == 'stable_middle_kv':
        return "saas-searchproxy-middle-kv.yandex.net"
    if ctype == 'ferryman':
        return "saas-ferryman.yandex.net"
    if ctype == 'testing':
        return "saas-searchproxy-testing.yandex.net"
    return "{}.saas.yandex.net".format(ctype.lower().replace("_", "-"))
