#!/usr/bin/env python3
"""Outside watcher for an n8n instance (lesson AUT-204-L04). Stdlib only. Synthetic demo setup.

Why outside? An Error Workflow runs INSIDE n8n: if n8n is down, out of memory, or a scheduled workflow silently
stopped firing, nothing inside n8n will tell you. This script runs somewhere else (cron, another server, a
monitoring service) and checks three things:

  1. readiness   GET  <n8n>/healthz/readiness           200 = up and database ready
  2. heartbeats  GET  <mock>/heartbeat                  each job's last "I finished OK" ping must be recent
  3. metrics     GET  <n8n>/metrics  (N8N_METRICS=true) version and success/failure counters, for the report

Alerts go to the mock messenger (POST /bot<token>/sendMessage) ONCE when a check turns bad and ONCE when it
recovers; the state file stops it from repeating the same alert every minute (alert fatigue).

    python watch_n8n.py            # one round; schedule it every minute with cron or a systemd timer
    python watch_n8n.py --loop 60  # demo: one round every 60 s
"""
import json
import os
import sys
import time
import urllib.error
import urllib.request

N8N = os.environ.get("N8N_BASE", "http://127.0.0.1:5678")
MOCK = os.environ.get("MOCK_API_BASE", "http://127.0.0.1:8787")
TOKEN = os.environ.get("MOCK_API_TOKEN", "local-demo-token")
STATE = os.environ.get("WATCH_STATE", "watch-state.json")
# job name -> max allowed seconds since last successful run (schedule interval + margin)
JOBS = {"order-sync": int(os.environ.get("ORDER_SYNC_MAX_AGE", "150"))}


def get(url, auth=False, timeout=5):
    h = {"Authorization": f"Bearer {TOKEN}"} if auth else {}
    try:
        with urllib.request.urlopen(urllib.request.Request(url, headers=h), timeout=timeout) as r:
            return r.status, r.read().decode("utf-8")
    except urllib.error.HTTPError as e:
        return e.code, ""
    except (urllib.error.URLError, OSError) as e:
        return None, str(getattr(e, "reason", e))


def checks():
    """Return {check_name: (ok, detail)}."""
    out = {}
    code, body = get(N8N + "/healthz/readiness")
    out["n8n-readiness"] = (code == 200, f"HTTP {code}" if code else f"unreachable ({body})")
    code, body = get(MOCK + "/heartbeat", auth=True)
    beats = json.loads(body)["data"] if code == 200 else {}
    now = time.time()
    for job, max_age in JOBS.items():
        last = beats.get(job, {}).get("last")
        if last is None:
            out[f"heartbeat:{job}"] = (False, "no heartbeat yet")
        else:
            age = int(now - last)
            out[f"heartbeat:{job}"] = (age <= max_age, f"last success {age}s ago (max {max_age}s)")
    return out


def metrics_line():
    code, body = get(N8N + "/metrics")
    if code != 200:
        return "metrics: unavailable"
    want = ("n8n_version_info", "n8n_workflow_success_total", "n8n_workflow_failed_total")
    keep = [ln for ln in body.splitlines() if ln.startswith(want)]
    return "metrics: " + " | ".join(keep)


def alert(text):
    data = json.dumps({"chat_id": "ops", "text": text}, ensure_ascii=False).encode("utf-8")
    req = urllib.request.Request(MOCK + "/botDEMO/sendMessage", data=data, method="POST",
                                 headers={"Content-Type": "application/json"})
    try:
        urllib.request.urlopen(req, timeout=5).close()
        return True
    except (urllib.error.URLError, OSError):
        return False


def one_round():
    try:
        prev = json.load(open(STATE, encoding="utf-8"))
    except (OSError, ValueError):
        prev = {}
    res = checks()
    stamp = time.strftime("%H:%M:%S")
    for name, (ok, detail) in res.items():
        was_ok = prev.get(name, True)
        if was_ok and not ok:
            sent = alert(f"🔴 {name}: {detail}")
            print(f"[{stamp}] {name}: FAIL {detail} -> alert {'sent' if sent else 'NOT sent'}")
        elif not was_ok and ok:
            sent = alert(f"🟢 {name} recovered: {detail}")
            print(f"[{stamp}] {name}: RECOVERED {detail} -> alert {'sent' if sent else 'NOT sent'}")
        else:
            print(f"[{stamp}] {name}: {'ok' if ok else 'still failing'} {detail}" + ("" if ok else " (no repeat alert)"))
        prev[name] = ok
    print(f"[{stamp}] {metrics_line()}")
    with open(STATE, "w", encoding="utf-8") as f:
        json.dump(prev, f)


if __name__ == "__main__":
    if sys.argv[1:2] == ["--loop"]:
        every = int(sys.argv[2]) if len(sys.argv) > 2 else 60
        while True:
            one_round()
            time.sleep(every)
    one_round()
