"""Run inside the existing analytics container; no settings or registration writes."""
from collections import Counter
import json
import time
import urllib.parse
import urllib.request

BASE = "http://127.0.0.1:5000/api/v1/streams"


def request(path="", method="GET"):
    with urllib.request.urlopen(urllib.request.Request(BASE + path, method=method), timeout=90) as r:
        return json.load(r)


def main():
    rows = request()["streams"]
    print(json.dumps(dict(phase="before", count=len(rows),
                         states=dict(Counter(row["state"] for row in rows)))), flush=True)
    for row in rows:
        if row["state"] != "stopped" or row.get("cleanup_pending"):
            result = request("/" + urllib.parse.quote(row["stream_id"], safe="") + "/stop", "POST")
            print(json.dumps(dict(phase="stop-requested", stream_id=row["stream_id"],
                                 state=result.get("observed_state", result.get("state")))), flush=True)
    end = time.monotonic() + 90
    while time.monotonic() < end:
        rows = request()["streams"]
        pending = [row for row in rows if row["state"] != "stopped" or row.get("cleanup_pending")]
        if not pending:
            print(json.dumps(dict(phase="after", count=len(rows), all_stopped=True,
                                  cleanup_pending=0)), flush=True)
            return
        time.sleep(2)
    raise RuntimeError("Channel Stop/reap did not finish within the bound")


if __name__ == "__main__":
    main()
