#!/usr/bin/env python3

import sys
import yaml

def do_patch(obj):
    if obj["kind"] != "PrometheusRule":
        return obj

    groups = obj.get("spec", {}).get("groups", [])
    for group in groups:
        if group.get("rules") is not None:
            for rule in group["rules"]:
                if rule.get("alert") != "KubeHpaMaxedOut":
                    continue

                expr = rule.get("expr", "")
                if "spec_min_replicas" in expr:
                    # already patched → idempotent
                    continue

                rule["expr"] = (
                    "("
                    + expr.strip()
                    + ")\nAND\n"
                    + "(\n"
                    + '  kube_horizontalpodautoscaler_spec_max_replicas'
                    + ' !=\n'
                    + '  kube_horizontalpodautoscaler_spec_min_replicas'
                    + "\n)"
                )
    return obj

for obj in yaml.load_all(sys.stdin, yaml.SafeLoader):
    if obj is None:
        continue
    obj = do_patch(obj)
    sys.stdout.write("---\n" + yaml.dump(obj))
