#!/usr/bin/env python3
"""Render the friend-facing Onadit SwiftBar menu.

Pure formatting: reads structured state from the environment and prints a
SwiftBar menu to stdout. No network, no clock except `now`, no CLI calls
of its own. The shell wrapper (`rift.10s.sh`) gathers the inputs and the
repair prompt always comes from `onadit doctor --copy-prompt` — this script
never invents diagnosis or hardcodes a prompt.

The menu answers one question: "Is Onadit working?" Its one standing action
is Open Onadit; any other row appears only when it needs action. Operator
detail (launchd labels, kickstart commands, Node versions, MCP counters)
is deliberately absent.

Inputs (all via env, all optional — missing inputs degrade gracefully):
  RIFT_DOCTOR_JSON   `onadit doctor --json` output (the verdict + issues).
  RIFT_STATUS_JSON   `onadit status --json` output (capture time, update layout).
  RIFT_MCP_JSON      `/stats/mcp-usage` body (today's recall count).
  RIFT_HEALTH        "up" | "down" — coarse /health probe, used only when
                     the doctor report is unavailable (CLI not resolvable).
  RIFT_NODE_BIN      absolute node binary, for menu actions.
  RIFT_JS            absolute path to the rift JS entrypoint.
  RIFT_BIN           absolute rift launcher, fallback when RIFT_JS is unset.
  RIFT_CODEX_BIN     absolute codex binary, for "Sign In to Codex…".
  RIFT_NOW_MS        injected clock for tests (epoch ms); defaults to now.
  OS_APPEARANCE      "Light" | "Dark", set by SwiftBar; picks the broken icon.
"""
import json
import os
import re

# Where a packaged (.pkg) install sends friends to upgrade — `onadit update`
# can't self-upgrade that layout, so the menu links here instead.
RIFT_DOWNLOAD_URL = "https://onadit.com/download"


def env(key, default=""):
    return os.environ.get(key, default)


def parse_json(raw):
    raw = (raw or "").strip()
    if not raw:
        return None
    try:
        return json.loads(raw)
    except Exception:
        return None


def now_ms():
    raw = env("RIFT_NOW_MS")
    if raw:
        try:
            return int(raw)
        except ValueError:
            pass
    import time

    return int(time.time() * 1000)


def parse_iso_ms(iso):
    """Parse an ISO-8601 timestamp to epoch ms, or None."""
    if not isinstance(iso, str) or not iso:
        return None
    s = iso.strip()
    if s.endswith("Z"):
        s = s[:-1] + "+00:00"
    try:
        from datetime import datetime

        return int(datetime.fromisoformat(s).timestamp() * 1000)
    except Exception:
        return None


def plural(n, word):
    return f"{n:,} {word}" + ("" if n == 1 else "s")


def age_ago(iso, now):
    """'just now', '16 min ago', '3 hours ago', '2 days ago' — or None."""
    ms = parse_iso_ms(iso)
    if ms is None:
        return None
    seconds = max(0, (now - ms) // 1000)
    if seconds < 60:
        return "just now"
    minutes = seconds // 60
    if minutes < 60:
        return f"{minutes} min ago"
    hours = minutes // 60
    if hours < 24:
        return plural(hours, "hour") + " ago"
    return plural(hours // 24, "day") + " ago"


def menu_text(text):
    """Make free text (doctor copy) safe for one SwiftBar title.

    `|` would split the title from its params, a newline would start a new
    menu row, a leading `--` would turn the row into a submenu item, and the
    middle dot is banned from menu copy (owner rule).
    """
    s = " ".join(str(text or "").split())
    s = s.replace("|", "/").replace(" · ", ", ").replace("·", ",")
    return s.lstrip("-").strip()


# --- Menu-action line builders -------------------------------------------
#
# SwiftBar runs an item's `shell=` command with a stripped PATH, so every
# action uses absolute binaries. rift subcommands run through node + the
# resolved JS entrypoint (the npm `rift` symlink's `#!/usr/bin/env node`
# shebang can't resolve `node` under a stripped PATH); when only RIFT_BIN
# resolved we fall back to it directly.


def sb_param(value):
    """Quote a SwiftBar parameter value so paths with spaces or SwiftBar
    separators survive parsing.

    SwiftBar splits an item's parameters on whitespace and uses `|` to
    separate the title from its params, so any value carrying a space, tab,
    `|`, or a quote must be wrapped to stay one token. We only quote when
    needed, leaving simple values (and flag args like `--target=claude`)
    untouched.
    """
    s = str(value)
    if s == "" or any(ch in s for ch in " \t|\"'"):
        return '"' + s.replace('"', '\\"') + '"'
    return s


def rift_runnable():
    node = env("RIFT_NODE_BIN")
    js = env("RIFT_JS")
    rift = env("RIFT_BIN")
    # SwiftBar's terminal-mode command builder quotes only the shell binary
    # (argv0) and joins paramN raw, so a space anywhere past argv0 fractures
    # the action — and packaged installs live under "Application Support".
    # Prefer the space-free shim (a self-contained launcher: it execs an
    # absolute node + JS) whenever the node/JS paths carry a space; fall back
    # to node+js only when they're space-free or no shim resolved.
    spaced = bool(node and js) and (" " in node or " " in js)
    if node and js and not spaced:
        return [node, js]
    if rift:
        return [rift]
    if node and js:
        return [node, js]
    return None


def shell_action(label, argv, terminal, refresh=False, extra=""):
    """A menu line that runs `argv` (argv[0] absolute)."""
    line = f"{label} | shell={sb_param(argv[0])}"
    for i, p in enumerate(argv[1:], start=1):
        line += f" param{i}={sb_param(p)}"
    line += f" terminal={'true' if terminal else 'false'}"
    if refresh:
        line += " refresh=true"
    if extra:
        line += f" {extra}"
    return line


def rift_action(label, args, terminal, refresh=False, extra=""):
    """A menu line that runs a rift subcommand, or None if rift is unresolved."""
    base = rift_runnable()
    if base is None:
        return None
    return shell_action(label, base + args, terminal, refresh, extra)


def open_rift_row():
    # `onadit setup` opens or focuses Onadit.app (the browser page is its
    # fallback). No `shortcut=`: SwiftBar 2.1.1 registers an item shortcut as
    # a GLOBAL hotkey while the menu is closed, so ⌘O would hijack every
    # app's Open command.
    return rift_action("Open Onadit", ["setup"], terminal=False)


def copy_prompt_row():
    """The one 'Copy Fix Prompt' row. The prompt itself comes from the CLI."""
    return rift_action(
        "Copy Fix Prompt",
        ["doctor", "--copy-prompt", "--target=claude"],
        terminal=False,
    )


# --- Status rows ----------------------------------------------------------
#
# SwiftBar 2.1.1 always draws an `sfimage=` as a monochrome template and
# ignores `sfcolor` on it; `sfcolor` (a CSS name or hex, never "systemGreen")
# only tints SF Symbols written inline as `:name:` in the title. So colored
# glyphs are inline symbols. A row without an action renders disabled grey,
# which is what the secondary lines want; `color=` keeps the headline at full
# label color (SwiftBar enables a colored row so the color shows) without
# giving it an action.

GREEN = "#34C759,#30D158"  # Apple systemGreen, light/dark
RED = "#FF3B30,#FF453A"  # Apple systemRed, light/dark
GREY = "#8E8E93,#98989D"  # Apple systemGray, light/dark
LABEL = "#000000,#FFFFFF"

CHECK = "checkmark.circle.fill"
TRIANGLE = "exclamationmark.triangle.fill"
QUESTION = "questionmark.circle.fill"


def headline(symbol, text, color):
    return f":{symbol}: {menu_text(text)} | sfcolor={color} color={LABEL}"


# --- Verdict --------------------------------------------------------------


def verdict_of(doctor, health):
    """healthy | warning | broken | unknown."""
    if isinstance(doctor, dict) and "healthy" in doctor:
        if not doctor.get("healthy"):
            return "broken"
        issues = doctor.get("issues") or []
        if any(i.get("severity") == "warning" for i in issues):
            return "warning"
        return "healthy"
    # No diagnosis available — fall back to the coarse health probe.
    if health == "up":
        return "healthy"
    if health == "down":
        return "broken"
    return "unknown"


def has_doctor_report(doctor):
    """True only when RIFT_DOCTOR_JSON parsed into a real doctor report.

    The doctor-powered "Copy Fix Prompt" row is gated on this, never on the
    rift binary merely resolving: if `onadit doctor --json` emitted nothing or
    failed, re-running doctor from the menu would fail the same way.
    """
    return isinstance(doctor, dict) and "healthy" in doctor


# The Onadit brand mark (the pile: 4 slabs of the archive, the 2nd slid out to
# the right), rendered to a 144px PNG and base64-embedded so
# render-menu.py stays a single self-contained file — it is symlinked/copied
# standalone into SwiftBar's plugins dir, so an external asset would add a
# path-resolution surface. Shipped as a `templateImage`: macOS ignores RGB and
# tints the ALPHA mask to the menu-bar color (adapting to light/dark), with no
# background container. DO NOT hand-edit this constant — regenerate from the
# logo: `python3 generate-icon.py` (source of truth: assets/rift-mark.svg).
RIFT_ICON_B64 = "iVBORw0KGgoAAAANSUhEUgAAAJAAAACQCAYAAADnRuK4AAAB6klEQVR42u3dYa3CMBSA0UpAQiVNAhKQUAeTNElIgC78J6F3dFt3TnIV9Mtrst48UgIAAAAAAAAAAK4u15nrLGazedS5XSGeUudl/jLPOnfxmOhMo15bDrffX6LhrrPZwXad4a6yxaF2nSIgIyABCUhAAhKQgARkBORgBSQgAQlIQAIyAjICEpCAPKZ6TD2H7FCtc0QVh2uhTERWWg9xnVmqt1QPAAAAAIe1fmxbP7r5+LjdrB+F8xXiuafP537PHlZIfjY5YBFFri1/efpNHvHqcrD9Zh4toOJQu84iICMgAQlIQAISkIAEZATkYAUkIAEJSEACMgIyAhKQgDymekw9B+sc1jnCLJRZKNvkKvOXSDzh68xSvaV6AAAAAE4gJ//m17/5bVSST/7+0bh4/NTBHteWw/VjK8383JOfewrxg3NWKwQkIAEJSEBGQEZAAhKQgAQkICMgIyABCUhAAhKQGTUgj6keU0OyQ7XOEVUcroUyEVlpPcR1ZqneUj0AAAAAfJWTD4k+JDYqyZODpwzxeEzd49pyuNY5mlkos1AWYqXVSquABCQgAQnICMgISEACEpCABGQEZAQkIAEJSEACMqMG5DHVY2pIdqjWOaKKw7VQJiIrrYe4zizVW6oHAAAAAAAAAAAG8gbs5m+rOTqBgwAAAABJRU5ErkJggg=="
# width/height are required: SwiftBar renders a custom image at its decoded
# pixel size (144px here) unless both are set, which would oversize the icon
# and distort menu-bar spacing. 18pt matches the menu-bar glyph height; the
# 144px source downscales crisply on retina. The title text is empty on
# purpose: the menu bar shows the icon alone, like every other status item.
_RIFT_TITLE = f" | templateImage={RIFT_ICON_B64} width=18 height=18"

# Broken, the pile falls apart: the slid-out slab fallen off, the others knocked
# loose (assets/rift-mark-fallen.svg), in Ember. A colour image is not tinted
# by macOS, so there is one per menu-bar appearance; SwiftBar names the current
# one in OS_APPEARANCE. Regenerated with the brand icon by generate-icon.py.
RIFT_BROKEN_LIGHT_B64 = "iVBORw0KGgoAAAANSUhEUgAAAJAAAACQCAYAAADnRuK4AAAE80lEQVR42u2dzXGkMBCFHQLnPRECIRACVZuAQiAEMpgQCGFCIARC4MSZELzjKmZXawPzox+k7u/wyuXDuMr0Nw/Rei0+5t+/PhB6V1wEBEAIgBAAIQBCCIAQACEAQgCEEAAlrOKmev0JQOihypvMTf1N002flsabGgBCzwKzpx6AAOYVYLbUAhDAuGgBIIBxVQNAAOOiCwABjItGAAIYVxUABDDi10GSgakyAybLdZA0YL56KNf1Ufgzc40ABDDi10EAwzpILEAagcluHQQwaWsAIIABIIA5Tb1mgADGXbUmgABG2e3LFaBi7fQCTJgmoui9sBpoguhry6WTHiirKLRXYPrVyUstofqJwusFxhWgBgh0A+MKUAc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CFcY9kXIhiE/cAIEJnACRVo3QXosj5b7SWAETcI9uNVgpM3AOAEur/VKvMw4hTL9WFKPzzQyTuULSWhlWvLpLnCBBVABTXJWoLiM6CIlQX2QSOfEwA5O4SzYZLDEs6h2GFXlQbAPq38Hx0iasFRK4vfGkCz5NNUgG67LhEn5hLhNYcIf7a5AJQtbHAvH6wwNQmUXGPIzi2XIK3FPopsJjTPbbmvYEkvHopLhQzSYf+79mEdqFrTIAqihr9aUxE3CO1g8M1LaRFhM5inDyK9gGqcnchADpHQ8S4Rw9AsgHKOu4BQOcDlHXoLNY/gI4LWubqQgB0XiMx9ukeI4/xcmQWIWcM0YU+//aV9RlDABRX45M9qhhz9SYEQA3FDQ7OqzmdrOIe7IW5346GdQ15j780Vk7qky5wVqd7ANDPNcIdiu5hNOcORYyYRDYuZFMv+fZxh2LLJU4dDT5woSxCZ/YvuTzKzzsuYSK7hIQzhi4+ASpPTCPaLnG1oEjZJThjaCPSajxBNO8sMI3jApMzhhKLe+yN4HQbIE07LmEvMCm6sldKUSBO93DaaKVAuJBT3IPi4EJOLuQyqmxPoSJ3NU/aD0m+UirFLqn2qVWznPdKqTo0QMATR3UucY/UXqqGjveqkgudvQPQlcKenlqM9UqpIACRmz5n+PCMuEcDQHIBSsqFAChPgGK4EAAJBijGRisACQcodNwDgBQAFMqFOgDSAVAIF3orqQhA+QPke6M1WCMRgNIEyFdthk+iwwAkAyAXF5piBcoAKF2APqnP5GPMGYDkAHR5sbk4+5yPZzM1v83UZ28uGg/AaX3PzBHnyCvO8c44UGeNVTVLoGFLAmV5BcqSE5HWfCKtYgAiVH9OqF4UQAgBEAIgBEAIgBAAIQRACIAQACEAQgiAEAAhAEIAhBAAIQBC6ekPfy6nVzfGSzsAAAAASUVORK5CYII="


def broken_title():
    dark = env("OS_APPEARANCE").lower() == "dark"
    return f" | image={RIFT_BROKEN_DARK_B64 if dark else RIFT_BROKEN_LIGHT_B64} width=18 height=18"

# Menu-bar title per verdict. Onadit still works with warnings, so they keep the
# calm brand mark; the rows inside carry the action. Only a broken Onadit
# changes the mark, to the fallen pile (see broken_title).
TITLES = {
    "healthy": _RIFT_TITLE,
    "warning": _RIFT_TITLE,
    "unknown": f" | sfimage={QUESTION}",
}


# --- Working (healthy / warning) -----------------------------------------


def capture_part(friend, now):
    """'Captured 16 min ago', 'Not captured yet', or None."""
    if not isinstance(friend, dict):
        return None
    capture = friend.get("capture")
    if not isinstance(capture, dict):
        return None
    last = capture.get("last_run_at")
    if last:
        age = age_ago(last, now)
        return f"Captured {age}" if age else None
    daemon = friend.get("daemon")
    # An older daemon omits capture_enabled; it means capture-off there.
    if isinstance(daemon, dict) and daemon.get("capture_enabled") is True:
        return "Not captured yet"
    return None


def recalls_part(mcp):
    """'9 recalls today', '1 recall today', 'no recalls today', or None."""
    today = mcp.get("today") if isinstance(mcp, dict) else None
    hits = today.get("context_hits") if isinstance(today, dict) else None
    if not isinstance(hits, int) or isinstance(hits, bool) or hits < 0:
        return None
    if hits == 0:
        return "no recalls today"
    return plural(hits, "recall") + " today"


def proof_line(friend, mcp, now):
    parts = [p for p in (capture_part(friend, now), recalls_part(mcp)) if p]
    if not parts:
        return None
    line = ", ".join(parts)
    return line[0].upper() + line[1:]


def self_update_supported(friend):
    update = friend.get("update") if isinstance(friend, dict) else None
    return not (
        isinstance(update, dict) and update.get("self_update_supported") is False
    )


def update_row(self_update):
    # Derive the action from the install layout, NEVER doctor's copy: a stale
    # doctor payload could still say "onadit update" while a packaged install
    # can't run it. `self_update_supported` rides the live status payload.
    icon = "sfimage=arrow.down.circle"
    if self_update:
        return rift_action(
            "Update Onadit…", ["update"], terminal=True, refresh=True, extra=icon
        )
    return f"Update Onadit… | href={sb_param(RIFT_DOWNLOAD_URL)} {icon}"


# Warning kinds whose repair a non-technical user may want an AI to walk them
# through. An explicit allowlist: most warnings either have their own row
# (update_available), are managed in the app (mcp_not_installed — installed
# software alone must not create a permanent reminder), or have no action at
# all (capture_daemon_stale's nextAction is literally "Nothing to do"). Add a
# kind here only once `onadit doctor --copy-prompt` produces a genuinely useful
# repair prompt for it.
REPAIRABLE_WARNINGS = {"capture_quarantined"}


def warning_rows(doctor, self_update):
    """One row per warning that needs action; warnings without one are hidden."""
    rows = []
    seen = set()
    issues = doctor.get("issues") if isinstance(doctor, dict) else None
    for issue in issues or []:
        if issue.get("severity") != "warning":
            continue
        kind = issue.get("kind")
        if kind == "update_available":
            key, row = "update", update_row(self_update)
        elif kind in REPAIRABLE_WARNINGS:
            key, row = "copy", copy_prompt_row()
        else:
            continue
        if row and key not in seen:
            seen.add(key)
            rows.append(row)
    return rows


def render_working(doctor, friend, mcp, now):
    rows = [headline(CHECK, "Onadit is working", GREEN)]
    proof = proof_line(friend, mcp, now)
    if proof:
        rows.append(menu_text(proof))
    actions = warning_rows(doctor, self_update_supported(friend))
    if actions:
        rows += ["---"] + actions
    return rows


# --- Needs attention ------------------------------------------------------

# Operator internals a friend must never see, even when the doctor's copy
# carries them (daemon_unreachable's nextAction is a launchctl kickstart).
OPERATOR_INTERNALS = re.compile(
    r"launchctl|kickstart|systemctl|gui/|com\.getrift|\$UID", re.IGNORECASE
)

# Friend copy that replaces the doctor's text for specific kinds. Onadit.app
# restarts a stopped engine when it opens, so Open Onadit is the fix.
SECONDARY_OVERRIDES = {
    "daemon_unreachable": "Open Onadit to restart it.",
    "voyage_key_missing": "Turn on Search by Meaning in Onadit’s Privacy settings.",
}


def primary_broken_issue(doctor):
    primary = doctor.get("primary")
    if isinstance(primary, dict) and primary.get("severity") == "broken":
        return primary
    for issue in doctor.get("issues") or []:
        if issue.get("severity") == "broken":
            return issue
    return primary if isinstance(primary, dict) else None


def secondary_text(issue):
    """The issue's nextAction, else its detail — friend-safe, or None."""
    if not isinstance(issue, dict):
        return None
    override = SECONDARY_OVERRIDES.get(issue.get("kind"))
    if override:
        return override
    for key in ("nextAction", "detail"):
        text = menu_text(issue.get(key))
        if text and not OPERATOR_INTERNALS.search(text):
            return text
    return None


def fix_row(issue):
    """A one-click fix for issue kinds that have one, else None."""
    if not isinstance(issue, dict):
        return None
    if issue.get("kind") == "codex_auth_expired":
        codex = env("RIFT_CODEX_BIN")
        if codex.startswith("/"):
            return shell_action("Sign In to Codex…", [codex, "login"], terminal=True)
    return None


def render_broken(doctor):
    if not has_doctor_report(doctor):
        # Verdict came from the /health probe alone: the engine is down and
        # the CLI couldn't report, so there is no prompt to copy.
        return [headline(TRIANGLE, "Onadit isn't running", RED), "Open Onadit to restart it."]
    issue = primary_broken_issue(doctor)
    title = menu_text(issue.get("title")) if isinstance(issue, dict) else ""
    rows = [headline(TRIANGLE, title or "Onadit needs attention", RED)]
    secondary = secondary_text(issue)
    if secondary:
        rows.append(secondary)
    fixes = [r for r in (fix_row(issue), copy_prompt_row()) if r]
    if fixes:
        rows += ["---"] + fixes
    return rows


# --- Top-level render -----------------------------------------------------


def render(doctor, status, mcp, health, now):
    friend = status.get("friend") if isinstance(status, dict) else None
    verdict = verdict_of(doctor, health)
    lines = [broken_title() if verdict == "broken" else TITLES[verdict], "---"]
    if verdict == "broken":
        lines += render_broken(doctor)
    elif verdict == "unknown":
        lines += [
            headline(QUESTION, "Onadit status unavailable", GREY),
            "Onadit couldn't check itself.",
        ]
    else:
        lines += render_working(doctor, friend, mcp, now)
    open_rift = open_rift_row()
    if open_rift:
        lines += ["---", open_rift]
    return lines


def main():
    doctor = parse_json(env("RIFT_DOCTOR_JSON"))
    status = parse_json(env("RIFT_STATUS_JSON"))
    mcp = parse_json(env("RIFT_MCP_JSON"))
    health = env("RIFT_HEALTH")
    for line in render(doctor, status, mcp, health, now_ms()):
        print(line)


if __name__ == "__main__":
    main()
