import datetime
import re

from balancer.production.l7_alerts.solomon.registry.project.projects import l7_balancer_project
from balancer.production.l7_alerts.solomon.registry.sensor.sensors import l3_rs_down
from balancer.production.l7_alerts.solomon.helpers.juggler import Tags, build_juggler_check
from library.python.monitoring.solo.objects.solomon.v2 import Type, Expression, MultiAlert

exports = []

for label, service, threshold, location_re in [
    ("term", "family.yandex.com.tr", 700, '.*'),
    ("term", "familysearch.yandex.ru", 700, '.*'),
    ("term", "yandex.com", 700, '.*'),
    ("term", "yandex.com.tr", 700, '.*'),
    ("term", "yandex.ru", 700, '.*'),
    ("term", "yandex.ua", 700, 'man|sas|vla'),
    ("yaru", "ya.ru", 700, 'man|sas|vla'),
    ("any", "any.yandex.ru", 700, '.*'),
    ("kubr_testing", "l7b-test.yandex.ru", 8, 'man|sas'),
    ("geo_only", "man.yandex.com", 40, 'man'),
    ("geo_only", "man.yandex.com.tr", 40, 'man'),
    ("geo_only", "man.yandex.ru", 40, 'man'),
    ("geo_only", "sas.yandex.com", 40, 'sas'),
    ("geo_only", "sas.yandex.com.tr", 40, 'sas'),
    ("geo_only", "sas.yandex.ru", 40, 'sas'),
    ("geo_only", "vla.yandex.com", 40, 'vla'),
    ("geo_only", "vla.yandex.com.tr", 40, 'vla'),
    ("geo_only", "vla.yandex.ru", 40, 'vla'),
    ("proxy_ua", "proxy.yandex.ua", 400, 'man|sas|vla'),
]:
    l3_rs_down_alert = MultiAlert(
        id=f"{label}-{service}-l3-rs-down",
        project_id=l7_balancer_project.id,
        name=f"{service} down RS too hi",
        description=f"Для L3 {service} service:slb_metrics_rs sensor:down больше {threshold}. Нужно проверить инcтансы {label} балансера в nanny.",
        type=Type(
            expression=Expression(
                program=f"""
                        let source = {l3_rs_down.mutate(service_name=service)};
                        let lastValue = last(source);
                        alarm_if(lastValue > {threshold});
                        """)),
        no_points_policy="NO_POINTS_NO_DATA",
        resolved_empty_policy="RESOLVED_EMPTY_NO_DATA",
        group_by_labels={"location"},
        window_secs=int(datetime.timedelta(minutes=5).total_seconds()),
        annotations={
            "host": l7_balancer_project.id,
            "service": f"{label}-{service}-l3-rs-down",
            "location": "{{labels.location}}",
            "jugglerTags": "{{labels.location}}"
        },
    )
    exports.append(l3_rs_down_alert)

    location_re = re.compile(location_re)
    for location, location_tag in [
        ('man', 'man'),
        ('sas', 'sas'),
        ('vla', 'vla'),
        ('iva', 'msk'),
        ('myt', 'msk')
    ]:
        if (location_re.match(location)):
            tags = [Tags.MARTY_DOWNTIME, Tags.MARTY_GEO.format(location_tag), Tags.L7_AlERT_FOR_L3_RS_DOWN]
            l3_rs_down_check = build_juggler_check(l3_rs_down_alert, location, tags)
            exports.append(l3_rs_down_check)
