#!/usr/bin/env python3
"""task-2990 PR#239 CI watcher. 감시 전용 - 머지/수정은 하지 않는다."""
import json, subprocess, sys, time, datetime

REPO = "Jeon-Jonghyuk/InsuRo"
SHA = "5e991e7c2b0ca4ba6155578c8f7cc30184d0f466"
POLL = 120
MAX_MIN = 36
LOG = "/home/jay/workspace/teams/dev2/t2990_ci_watch.log"

BAD = {"failure", "timed_out", "cancelled", "action_required", "stale"}
OK = {"success", "neutral", "skipped"}


def now():
    return datetime.datetime.now().strftime("%H:%M:%S")


def emit(msg):
    line = "[%s] %s" % (now(), msg)
    with open(LOG, "a") as f:
        f.write(line + "\n")
    print(line, flush=True)


def api(path):
    p = subprocess.run(
        ["bash", "-lc", "source /home/jay/workspace/.env.keys 2>/dev/null; gh api " + path],
        capture_output=True, text=True, timeout=90)
    if p.returncode != 0:
        return None, p.stderr.strip()[:300]
    try:
        return json.loads(p.stdout), None
    except Exception as e:
        return None, str(e)[:200]


deadline = time.time() + MAX_MIN * 60
emit("WATCH_START sha=%s max=%dmin poll=%ds" % (SHA[:10], MAX_MIN, POLL))

while True:
    data, err = api("repos/%s/commits/%s/check-runs" % (REPO, SHA))
    if err:
        emit("API_ERR %s" % err)
    else:
        runs = data.get("check_runs", [])
        pend = [r["name"] for r in runs if r["status"] != "completed"]
        bad = [(r["name"], r["conclusion"]) for r in runs
               if r["status"] == "completed" and (r.get("conclusion") or "") in BAD]
        good = [r["name"] for r in runs
                if r["status"] == "completed" and (r.get("conclusion") or "") in OK]
        emit("total=%d ok=%d pending=%d bad=%d | pending:%s" %
             (len(runs), len(good), len(pend), len(bad), ",".join(pend) or "-"))
        if bad:
            emit("TERMINAL=CI_FAILED " + json.dumps(bad))
            sys.exit(2)
        if runs and not pend:
            emit("TERMINAL=ALL_GREEN %d/%d" % (len(good), len(runs)))
            sys.exit(0)
    if time.time() > deadline:
        emit("TERMINAL=LOOP_BOUNDARY")
        sys.exit(3)
    time.sleep(POLL)
