#!/usr/bin/env python3
"""bikoret-watchdog — the kohen's eye on /kodesh/health, from outside the cluster.

Every run (cron, every 5 minutes) probes the health endpoint. A failure is
anything but 200 with overall "healthy" (a 503 at the day boundary, a
Doorpost drift, a hung rollout, the gate dark) — except REST: overall
"shabbat" is the cloud resting, not the vessel failing (Bamidbar 9:18);
it is logged once on entering and once on leaving, never counted, never
an issue. 2026-10-24 and 10-31: 288 FAIL lines and an outage issue for
each Shabbat, because readiness answered 503 on rest and the watchdog
could not tell rest from death. After two consecutive
failures (10 minutes — a rollout's own blip does not alert) it opens ONE
Gitea issue in the repo naming the failed checks; while down it comments
only when the failed set changes; on recovery it comments the duration and
closes the issue. Every transition goes to the log. 2026-10-15: the site
was 503 for 13.5 h at a day boundary and the transmitter learned of the
Doorpost outage by losing Claude — nothing watched.

The calendar, too (2026-11-08): the cluster kubeconfig's client certificate
lives 30 days and expired unnoticed around 11-05 — the rollout of tablet 59
failed "must be logged in". Each run reads its notAfter; at seven days or
fewer it logs once a day, at three or fewer it opens ONE issue naming the
renewal (KOHEN.md "Rolling out": the exo profile renews it without new
secrets), closed by hand when renewed. A watch is a daily act (tablet 59).

The login, too (2026-11-24): the claude.ai sign-in that every Claude Code
session on this VM shares (~/.claude/.credentials.json) carries a hard
deadline, refreshTokenExpiresAt, about four weeks after the browser login;
past it no refresh is possible and every session says "Login reached its
time limit · Please run /login". It was read as a gate failure and the
gate was disarmed for nothing: no login traffic ever passes the gate.
Each run reads that deadline; same thresholds, same shape. Only the
timestamp is read — never a token.
Paths:
  state   ~/.local/state/bikoret-watchdog/state.json
  log     ~/shorashim-operator-notes/watchdog.log
  token   ~/.git-credentials (the Gitea token; read, never printed)

Env overrides (for a test run): BIKORET_HEALTH_URL, BIKORET_WATCHDOG_STATE,
BIKORET_WATCHDOG_LOG, BIKORET_GITEA_API (default https://git.bikoret.ch/api/v1),
BIKORET_GITEA_REPO (default heaviness510/bikoret), BIKORET_WATCHDOG_DRY=1 (no issue).
"""
import json, os, re, sys, time, urllib.request, urllib.error
from datetime import datetime, timezone

HOME = os.path.expanduser("~")
URL = os.environ.get("BIKORET_HEALTH_URL", "https://bikoret.ch/kodesh/health")
STATE = os.environ.get("BIKORET_WATCHDOG_STATE", f"{HOME}/.local/state/bikoret-watchdog/state.json")
LOG = os.environ.get("BIKORET_WATCHDOG_LOG", f"{HOME}/shorashim-operator-notes/watchdog.log")
API = os.environ.get("BIKORET_GITEA_API", "https://git.bikoret.ch/api/v1")
REPO = os.environ.get("BIKORET_GITEA_REPO", "heaviness510/bikoret")
DRY = os.environ.get("BIKORET_WATCHDOG_DRY") == "1"
THRESHOLD = 2


def now():
    return datetime.now(timezone.utc)


def log(msg):
    os.makedirs(os.path.dirname(LOG), exist_ok=True)
    with open(LOG, "a") as f:
        f.write(f"{now().strftime('%Y-%m-%dT%H:%M:%SZ')} {msg}\n")


def judge(code, body):
    """(verdict, summary, failed_checks) — verdict is "ok", "resting" or "fail". Pure; tested in scripts/test_watchdog.py."""
    try:
        d = json.loads(body)
    except Exception:
        return "fail", f"HTTP {code} non-JSON body ({len(body)} bytes)", [f"HTTP {code}"]
    checks = d.get("checks") or {}
    overall = d.get("overall")
    if overall == "shabbat":
        # The cloud rests; the camp stands. Not a failure, whatever the code.
        return "resting", f"HTTP {code} overall=shabbat", []
    failed = sorted(k for k, v in checks.items() if v != "pass")
    ok = code == 200 and overall == "healthy"
    return ("ok" if ok else "fail"), f"HTTP {code} overall={overall} failed={failed or 'none'}", failed or ([f"HTTP {code}"] if not ok else [])


def probe():
    """(verdict, summary, failed_checks)"""
    try:
        with urllib.request.urlopen(urllib.request.Request(URL, headers={"user-agent": "bikoret-watchdog"}), timeout=15) as r:
            code, body = r.status, r.read()
    except urllib.error.HTTPError as e:
        code, body = e.code, e.read()
    except Exception as e:  # DNS, TLS, timeout, refused
        return "fail", f"unreachable: {type(e).__name__}: {e}", ["unreachable"]
    return judge(code, body)


KUBECONFIG = os.environ.get("BIKORET_KUBECONFIG", f"{HOME}/.kube/exoscale-temple-council.yaml")


def kube_days_left(path=None):
    """Days until the kubeconfig's client certificate expires, or None when it cannot be read."""
    import base64, subprocess
    try:
        s = open(path or KUBECONFIG).read()
        m = re.search(r"client-certificate-data:\s*([A-Za-z0-9+/=]+)", s)
        pem = base64.b64decode(m.group(1)).decode()
        out = subprocess.run(["openssl", "x509", "-noout", "-enddate"], input=pem, capture_output=True, text=True, timeout=10).stdout
        end = datetime.strptime(out.strip().split("=", 1)[1], "%b %d %H:%M:%S %Y %Z").replace(tzinfo=timezone.utc)
        return (end - now()).total_seconds() / 86400
    except Exception:
        return None


CREDENTIALS = os.environ.get("BIKORET_CLAUDE_CREDENTIALS", f"{HOME}/.claude/.credentials.json")


def login_days_left(path=None):
    """Days until the shared claude.ai sign-in can no longer be refreshed (refreshTokenExpiresAt, ms), or None."""
    try:
        c = json.load(open(path or CREDENTIALS))["claudeAiOauth"]
        end = datetime.fromtimestamp(c["refreshTokenExpiresAt"] / 1000, timezone.utc)
        return (end - now()).total_seconds() / 86400
    except Exception:
        return None


def watch_calendar(s):
    """The kubeconfig's days, then the login's: log once a day under seven, one issue under three."""
    watch_kubeconfig(s)
    watch_login(s)


def watch_login(s):
    days = login_days_left()
    if days is None:
        return
    today = now().strftime("%Y-%m-%d")
    if days <= 7 and s.get("login_warned") != today:
        log(f"LOGIN: the claude.ai sign-in reaches its time limit in {days:.1f} days — /login in any session, the gate stays armed (KOHEN.md 'When it is the login')")
        s["login_warned"] = today
    if days <= 3 and s.get("login_issue") is None:
        r = gitea("POST", "/issues", {"title": f"WATCHDOG: Claude Code sign-in reaches its time limit in {days:.1f} days",
                                     "body": "The shared claude.ai sign-in (~/.claude/.credentials.json, refreshTokenExpiresAt) is about to pass the point "
                                             "where it can no longer be refreshed; every session on the VM will then say "
                                             "\"Login reached its time limit · Please run /login\". Run /login in any session, or `claude auth login` "
                                             "from the shell. This is not the gate: no login traffic passes bikoret.ch, so leave it armed "
                                             "(KOHEN.md, 'When it is the login, not the gate').\n\n"
                                             "Opened by bikoret-watchdog; close it when signed in again."})
        if r:
            s["login_issue"] = r.get("number")
            log(f"ALERT issue #{s['login_issue']} opened for the login: {r.get('html_url')}")
    if days > 7 and (s.get("login_warned") or s.get("login_issue") is not None):
        log(f"LOGIN renewed: {days:.1f} days left")
        s["login_warned"] = None
        s["login_issue"] = None


def watch_kubeconfig(s):
    days = kube_days_left()
    if days is None:
        return
    today = now().strftime("%Y-%m-%d")
    if days <= 7 and s.get("kube_warned") != today:
        log(f"KUBECONFIG: the cluster certificate expires in {days:.1f} days — renew (KOHEN.md 'Rolling out')")
        s["kube_warned"] = today
    if days <= 3 and s.get("kube_issue") is None:
        r = gitea("POST", "/issues", {"title": f"WATCHDOG: cluster kubeconfig expires in {days:.1f} days",
                                     "body": "The 30-day client certificate in ~/.kube/exoscale-temple-council.yaml is about to expire; a rollout will fail "
                                             "\"must be logged in\". Renew from the stored exo profile (KOHEN.md, Rolling out):\n\n"
                                             "    umask 077; exo compute sks kubeconfig temple-council-starter admin -z ch-gva-2 -g system:masters -t 2592000 > ~/.kube/exoscale-temple-council.yaml\n\n"
                                             "Opened by bikoret-watchdog; close it when renewed."})
        if r:
            s["kube_issue"] = r.get("number")
            log(f"ALERT issue #{s['kube_issue']} opened for the kubeconfig: {r.get('html_url')}")
    if days > 7 and (s.get("kube_warned") or s.get("kube_issue") is not None):
        log(f"KUBECONFIG renewed: {days:.1f} days left")
        s["kube_warned"] = None
        s["kube_issue"] = None


def token():
    """The Gitea token: ~/.config/bikoret/gitea_watchdog_token first (a token
    the kohen issued with write:issue — the clone token in ~/.git-credentials
    has only the code scopes and Gitea answers 403 on an issue), else that."""
    try:
        t = open(f"{HOME}/.config/bikoret/gitea_watchdog_token").read().strip()
        if t:
            return t
    except FileNotFoundError:
        pass
    try:
        for line in open(f"{HOME}/.git-credentials"):
            m = re.match(r"https?://([^:]+):([^@]+)@", line.strip())
            if m:
                return m.group(2)
    except FileNotFoundError:
        pass
    return None


def gitea(method, path, payload=None):
    if DRY:
        log(f"DRY {method} {path} {json.dumps(payload)[:120] if payload else ''}")
        return {"number": -1, "html_url": "(dry)"}
    tok = token()
    if not tok:
        log("no Gitea token in ~/.git-credentials — cannot open an issue")
        return None
    data = json.dumps(payload).encode() if payload is not None else None
    req = urllib.request.Request(f"{API}/repos/{REPO}{path}", data=data, method=method,
                                 headers={"authorization": f"token {tok}", "content-type": "application/json", "accept": "application/json"})
    try:
        with urllib.request.urlopen(req, timeout=20) as r:
            return json.loads(r.read() or b"{}")
    except urllib.error.HTTPError as e:
        log(f"Gitea {method} {path} -> HTTP {e.code}: {e.read()[:120]!r}")
        return None
    except Exception as e:
        log(f"Gitea {method} {path} failed: {type(e).__name__}: {e}")
        return None


def load_state():
    try:
        return json.load(open(STATE))
    except Exception:
        return {"fails": 0, "down_since": None, "issue": None, "failed": [], "resting": False}


def save_state(s):
    os.makedirs(os.path.dirname(STATE), exist_ok=True)
    tmp = STATE + ".tmp"
    json.dump(s, open(tmp, "w"))
    os.replace(tmp, STATE)


def main():
    s = load_state()
    watch_calendar(s)
    save_state(s)
    verdict, summary, failed = probe()
    t = now().strftime("%Y-%m-%d %H:%M:%SZ")

    if verdict == "resting":
        if not s.get("resting"):
            log(f"SHABBAT: the cloud rests, the camp stands ({summary}); nothing counted until it lifts")
        s["resting"] = True
        save_state(s)
        return 0
    if s.get("resting"):
        log(f"SHABBAT over ({summary})")
        s["resting"] = False

    if verdict == "ok":
        if s["issue"] is not None or s["down_since"]:
            since = s["down_since"] or t
            mins = int((now() - datetime.fromisoformat(since.replace("Z", "+00:00").replace(" ", "T"))).total_seconds() // 60)
            log(f"RECOVERED after {mins} min ({summary})")
            if s["issue"] is not None:
                gitea("POST", f"/issues/{s['issue']}/comments", {"body": f"Recovered at {t} after {mins} min. `{summary}`"})
                gitea("PATCH", f"/issues/{s['issue']}", {"state": "closed"})
        elif s["fails"]:
            log(f"ok again after {s['fails']} failed probe(s), no alert raised ({summary})")
        save_state({"fails": 0, "down_since": None, "issue": None, "failed": [], "resting": False,
                    "kube_warned": s.get("kube_warned"), "kube_issue": s.get("kube_issue"),
                    "login_warned": s.get("login_warned"), "login_issue": s.get("login_issue")})
        return 0

    s["fails"] += 1
    if not s["down_since"]:
        s["down_since"] = t
    log(f"FAIL #{s['fails']}: {summary}")

    if s["fails"] >= THRESHOLD and s["issue"] is None:
        body = (f"bikoret.ch health has failed {s['fails']} consecutive probes since {s['down_since']}.\n\n"
                f"Last probe: `{summary}`\n\nFailed checks: {', '.join(failed) or 'none named'}\n\n"
                "What to look at first: the vav-pipeline startup log (`kubectl -n shorashim logs <pod> -c vav-pipeline | grep -v health`) — "
                "a Doorpost drift, stale manna at the day boundary, and a missing anchor all look the same from outside. "
                "Claude Code behind the gate is down with the site: `claude-direct` or `claude-key` (KOHEN.md, Fallback).\n\n"
                "Opened by bikoret-watchdog on the dev VM; it will comment and close this issue on recovery.")
        r = gitea("POST", "/issues", {"title": f"WATCHDOG: bikoret.ch down since {s['down_since']} ({', '.join(failed)[:60]})", "body": body, "labels": []})
        if r:
            s["issue"] = r.get("number")
            s["failed"] = failed
            log(f"ALERT issue #{s['issue']} opened: {r.get('html_url')}")
    elif s["issue"] is not None and failed != s.get("failed"):
        gitea("POST", f"/issues/{s['issue']}/comments", {"body": f"{t}: failed checks now {', '.join(failed)} — `{summary}`"})
        s["failed"] = failed
        log(f"issue #{s['issue']} updated: failed={failed}")

    save_state(s)
    return 1


if __name__ == "__main__":
    sys.exit(main())
