"""15초마다 alert.sql을 실행하고, 같은 (metric, page)가 두 번 연속 걸리면 알린다.

    python3 alert_poll.py
"""
import json
import pathlib
import time
import urllib.parse
import urllib.request

URL = "http://localhost:8123/"
AUTH = {"X-ClickHouse-User": "demo", "X-ClickHouse-Key": "demo"}
SQL = (pathlib.Path(__file__).parent / "alert.sql").read_text()
INTERVAL_S = 15
CONSECUTIVE = 2


def violations():
    params = urllib.parse.urlencode({"default_format": "JSONEachRow"})
    req = urllib.request.Request(URL + "?" + params, data=SQL.encode(), headers=AUTH)
    lines = urllib.request.urlopen(req).read().decode().splitlines()
    return {(r["metric"], r["page"]): r for r in map(json.loads, lines)}


def main():
    streak = {}
    firing = set()
    while True:
        found = violations()
        for key in list(streak):
            if key not in found:
                streak.pop(key)
                if key in firing:
                    firing.discard(key)
                    print(f"[resolved] {key[0]} {key[1]}", flush=True)
        for key, r in found.items():
            streak[key] = streak.get(key, 0) + 1
            state = "FIRING" if streak[key] >= CONSECUTIVE else "pending"
            if state == "FIRING":
                firing.add(key)
            print(f"[{state}] {key[0]} {key[1]} p75={r['p75_ms']}ms "
                  f"threshold={r['threshold_ms']}ms n={r['n']}", flush=True)
        if not found:
            print("ok", flush=True)
        time.sleep(INTERVAL_S)


if __name__ == "__main__":
    main()
