#!/usr/bin/env python3
"""RED ALERT desktop widget (DizyDiz) - a small always-on-top window for the public board at https://dizydiz.com/REDALERT/

Python 3 standard library only (tkinter). Run:  python3 redalert_widget.py
  Linux: if tkinter is missing, install your distro's python3-tk package.
It reads ONE public file, https://dizydiz.com/REDALERT/status.json, every 60 seconds. Nothing else is sent anywhere.

Banner: RED ALERT (red) > CONFIRMING (yellow, unconfirmed reports) > AMBER (orange; an unknown tier also counts as amber)
        > ALL QUIET (one short line). NO DATA when the feed is older than 15 minutes or cannot be fetched: never an all-clear.
Desktop pop-up for a NEW red or confirming item where the system offers one (notify-send on Linux, osascript on macOS);
otherwise the window rings the bell and comes to the front.
Mouse: drag = move · double-click = open the board · right-click = menu (on top, quit).
Unofficial and automated. Can be wrong or late. Not a substitute for official sources; call 911 in an emergency.
"""
import datetime, json, os, platform, shutil, subprocess, sys, threading, time, urllib.request, webbrowser
import tkinter as tk

FEED = os.environ.get("REDALERT_FEED", "https://dizydiz.com/REDALERT/status.json")  # override only for testing
BOARD = "https://dizydiz.com/REDALERT/"
REFRESH_S, STALE_S, MAX_ITEMS, WIDTH = 60, 15 * 60, 4, 360
BG, CARD, INK, MUT = "#0a0e19", "#101726", "#e6edf7", "#8fa3c4"
COL = {"red": "#ef2b2b", "confirm": "#facc15", "amber": "#f59e0b", "quiet": "#22c55e", "nodata": "#94a3b8", "gone": "#5d6f8f"}
LABEL = {"red": "RED ALERT", "confirm": "CONFIRMING", "amber": "AMBER", "gone": "FALSE ALARM"}
RANK = {"red": 0, "confirm": 1, "amber": 2, "gone": 3}


def kind(ev):
    """One decider for an item's colour. Unknown tier = amber (loud), never quiet."""
    if ev.get("status") == "retracted":
        return "gone"
    t = str(ev.get("tier") or "").strip().upper()
    return {"RED ALERT": "red", "CONFIRMING": "confirm"}.get(t, "amber")


def parse(s):
    try:
        return datetime.datetime.fromisoformat(str(s).replace("Z", "+00:00")).timestamp()
    except Exception:
        return None


def quiet_line(e):
    """'Going quiet' is decided ONCE by the watcher (e['quiet']); the widget only words it."""
    if not isinstance(e, dict) or not e.get("quiet"):
        return None
    c = parse(e.get("confirmed"))
    return "No new reports since " + (time.strftime("%b %-d, %-I:%M %p", time.localtime(c)) if c else "an unknown time")


def ago(sec):
    m = round(max(0, sec) / 60)
    return "just now" if m < 1 else f"{m} min ago" if m < 60 else f"{m // 60} h {m % 60} min ago"


def fetch():
    req = urllib.request.Request(f"{FEED}?t={int(time.time())}", headers={"User-Agent": "redalert-widget/1", "Cache-Control": "no-cache"})
    with urllib.request.urlopen(req, timeout=20) as r:
        d = json.loads(r.read(2_000_000).decode("utf-8"))
    if not isinstance(d, dict):
        raise ValueError("bad feed")
    return d


def decide(d, err):
    """-> (state, headline, sub, items). The same rules as the board page."""
    if err or not d:
        return "nodata", "NO DATA", "Feed unreachable. This is not an all-clear.", []
    gen = parse(d.get("generated"))
    age = None if gen is None else time.time() - gen
    act = d.get("active") if isinstance(d.get("active"), list) else None
    items = sorted([e for e in (act or []) if isinstance(e, dict)], key=lambda e: RANK[kind(e)])
    if act is None or age is None or age > STALE_S or age < -300:
        why = "Feed has no valid time." if age is None else f"Feed last updated {ago(age)}."
        return "nodata", "NO DATA", why + " Not an all-clear.", items
    live = [e for e in items if kind(e) != "gone"]
    if not live:
        return "quiet", "ALL QUIET", f"checked {ago(age)}", items
    top = live[0]
    sub = {"red": quiet_line(top) or "Active now", "confirm": "Unconfirmed reports, not yet a RED ALERT", "amber": quiet_line(top) or "Active now"}[kind(top)]
    if len(live) > 1:
        sub += f" · {len(live)} events active"
    return kind(top), LABEL[kind(top)], sub, items


def popup(title, body):
    try:
        if platform.system() == "Linux" and shutil.which("notify-send"):
            subprocess.Popen(["notify-send", "-a", "RED ALERT", title, body[:180]])
            return True
        if platform.system() == "Darwin":
            esc = lambda s: s.replace("\\", "\\\\").replace('"', '\\"')
            subprocess.Popen(["osascript", "-e", f'display notification "{esc(body[:180])}" with title "{esc(title)}"'])
            return True
    except Exception:
        pass
    return False


class Widget:
    def __init__(self):
        self.root = tk.Tk()
        self.root.title("RED ALERT")
        self.root.configure(bg=BG)
        self.root.geometry(f"{WIDTH}x120")
        self.top = tk.BooleanVar(value=True)
        self.root.attributes("-topmost", True)
        self.frame = tk.Frame(self.root, bg=BG, padx=10, pady=8)
        self.frame.pack(fill="both", expand=True)
        self.data, self.err, self.seen = None, None, None
        self.menu = tk.Menu(self.root, tearoff=0)
        self.menu.add_command(label="Open the board", command=lambda: webbrowser.open(BOARD))
        self.menu.add_checkbutton(label="Keep on top", variable=self.top, command=lambda: self.root.attributes("-topmost", self.top.get()))
        self.menu.add_command(label="Quit", command=self.root.destroy)
        for w in (self.root,):
            w.bind("<ButtonPress-1>", self._press)
            w.bind("<B1-Motion>", self._drag)
            w.bind("<Double-Button-1>", lambda e: webbrowser.open(BOARD))
            w.bind("<Button-3>", lambda e: self.menu.tk_popup(e.x_root, e.y_root))
            w.bind("<Button-2>", lambda e: self.menu.tk_popup(e.x_root, e.y_root))  # macOS right-click
        self._poll()
        self._tick()

    def _press(self, e):
        self._dx, self._dy = e.x_root - self.root.winfo_x(), e.y_root - self.root.winfo_y()

    def _drag(self, e):
        self.root.geometry(f"+{e.x_root - self._dx}+{e.y_root - self._dy}")

    def _poll(self):
        def work():
            try:
                d, err = fetch(), None
            except Exception as ex:
                d, err = None, str(ex)[:80]
            self.root.after(0, self._got, d, err)
        threading.Thread(target=work, daemon=True).start()
        self.root.after(REFRESH_S * 1000, self._poll)

    def _got(self, d, err):
        self.data, self.err = (d, None) if d else (self.data, err)
        self.data_failed = bool(err)
        self.render()

    def _tick(self):
        if self.data or self.err:
            self.render()
        self.root.after(20000, self._tick)

    def _notify(self, state, items):
        if state == "nodata":
            return
        keys = {f"{e.get('id') or e.get('title')}|{kind(e)}": e for e in items if kind(e) in ("red", "confirm")}
        if self.seen is None:  # first look: learn what is already showing, do not pop up old news
            self.seen = set(keys)
            return
        for k, e in keys.items():
            if k not in self.seen:
                self.seen.add(k)
                title = ("RED ALERT: " if kind(e) == "red" else "Confirming: ") + str(e.get("title") or "new event")
                if not popup(title, str(e.get("summary") or "")):
                    self.root.bell()
                    self.root.deiconify(); self.root.lift()

    def render(self):
        state, head, sub, items = decide(None if getattr(self, "data_failed", False) else self.data, None)
        if getattr(self, "data_failed", False):
            stale_items = []
            if self.data and isinstance(self.data.get("active"), list):
                stale_items = sorted([e for e in self.data["active"] if isinstance(e, dict)], key=lambda e: RANK[kind(e)])
            state, head, sub, items = "nodata", "NO DATA", f"Feed unreachable ({self.err}). Not an all-clear.", stale_items
        self._notify(state, items)
        for w in self.frame.winfo_children():
            w.destroy()
        col = COL[state]
        if state == "quiet" and not items:
            row = tk.Frame(self.frame, bg=BG); row.pack(fill="x")
            tk.Label(row, text="●", fg=col, bg=BG, font=("TkDefaultFont", 12)).pack(side="left")
            tk.Label(row, text=" ALL QUIET ", fg=col, bg=BG, font=("TkDefaultFont", 11, "bold")).pack(side="left")
            tk.Label(row, text=sub, fg=MUT, bg=BG, font=("TkDefaultFont", 10)).pack(side="left")
        else:
            box = tk.Frame(self.frame, bg=CARD, highlightbackground=COL["amber"] if state == "nodata" else col, highlightthickness=3, padx=8, pady=6)
            box.pack(fill="x")
            tk.Label(box, text=head, fg=col, bg=CARD, font=("TkDefaultFont", 26, "bold")).pack()
            live = [e for e in items if kind(e) != "gone"]
            if live and state != "nodata":
                tk.Label(box, text=str(live[0].get("title") or ""), fg=INK, bg=CARD, wraplength=WIDTH - 50, justify="center",
                         font=("TkDefaultFont", 11, "bold")).pack()
            tk.Label(box, text=sub, fg=MUT, bg=CARD, wraplength=WIDTH - 50, justify="center", font=("TkDefaultFont", 9)).pack()
            if items and state == "nodata":
                tk.Label(self.frame, text="LAST KNOWN · NOT CURRENT", fg=MUT, bg=BG, font=("TkDefaultFont", 8, "bold")).pack(anchor="w", pady=(6, 0))
            for e in items[:MAX_ITEMS]:
                k = kind(e)
                row = tk.Frame(self.frame, bg=CARD, highlightbackground=COL[k], highlightthickness=0)
                row.pack(fill="x", pady=(5, 0))
                tk.Frame(row, bg=COL[k], width=5).pack(side="left", fill="y")
                inner = tk.Frame(row, bg=CARD, padx=6, pady=3); inner.pack(side="left", fill="x", expand=True)
                tier = str(e.get("tier") or "UNKNOWN").upper() if k == "amber" else LABEL[k]
                tk.Label(inner, text=tier + (f" · {e.get('topic')}" if e.get("topic") else ""), fg=COL[k], bg=CARD,
                         font=("TkDefaultFont", 8, "bold")).pack(anchor="w")
                src = [s for s in (e.get("sources") or []) if isinstance(s, dict) and str(s.get("url", "")).startswith(("http://", "https://"))]
                url = src[0]["url"] if src else BOARD
                t = tk.Label(inner, text=str(e.get("title") or "Untitled event"), fg=INK, bg=CARD, cursor="hand2", wraplength=WIDTH - 60,
                             justify="left", font=("TkDefaultFont", 10, "bold"))
                t.pack(anchor="w")
                t.bind("<Button-1>", lambda ev, u=url: webbrowser.open(u))
                q = quiet_line(e)
                if q:
                    tk.Label(inner, text=q, fg=COL["amber"], bg=CARD, font=("TkDefaultFont", 8)).pack(anchor="w")
            if len(items) > MAX_ITEMS:
                tk.Label(self.frame, text=f"+ {len(items) - MAX_ITEMS} more on the board (double-click)", fg=MUT, bg=BG,
                         font=("TkDefaultFont", 9)).pack(anchor="w", pady=(4, 0))
        self.root.update_idletasks()
        self.root.geometry(f"{WIDTH}x{self.frame.winfo_reqheight()}")

    def run(self):
        self.root.mainloop()


if __name__ == "__main__":
    if "--once" in sys.argv:  # print the decision and exit (for testing / scripts)
        try:
            d, err = fetch(), None
        except Exception as ex:
            d, err = None, str(ex)
        s, h, sub, items = decide(d, err)
        print(h, "-", sub)
        for e in items[:MAX_ITEMS]:
            print(f"  [{LABEL.get(kind(e), 'AMBER')}] {e.get('title')}")
        sys.exit(0)
    Widget().run()
