#!/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.
"""
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 ("glass": a block cut by one slanted rift, left half
# solid, right half an outline), 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 = "iVBORw0KGgoAAAANSUhEUgAAAJAAAACQCAYAAADnRuK4AAAD9ElEQVR42u2dUZHqQBBFRwISIgEJkYCESIiEOEBCJCAhEpCAhEjg8QFV1H69Bnqm+845Vfc/Gc4mzcwtthQAAAAAAAAAAAAAAAAAAAAAAAAAgCwMj8yPbI/sj9xFcjCug/e97881np9rLiHOKiTMe24frEXta1wzizSJPW3+5mJcj1Oj69yfn0U6ee7iWYxrsjS+3gl5YmU0rssW4JrDSzSIv7beYyXCNe/RZ6K1E3muxnU5Brr2NfLT595J1uSv9ZBPobkjgWbj2pyTX38Vto4EOhrX5hrs+reIAu0dCZRxgP47TIejF3msf72jyB8BAv0oZ+fZ8Fpp/REoyWacdWtjRSDtWL8C3yrtFiNQgliHz0OFb3gIxAD9kw8WgRJkMa7JUnF/BoESZHTeXD0jkHa8K6wnBNJNjQrrgEBUWF9YK6x75fVHoMrxPoHfEIgB+psBekEgTuC/WY8RgaiwvvikwnpAICqsLybnb3gIlCyTcS2sJ/AXBKLC+o61wjojEAN0ywEagQIn8gk8AiVI1AorAiWJ9YDz4vwND4GSZTCuQ60KKwIlSOQKKwIxQP/0g0SggFmMa7A4C4pAyWLdn6lZYUWgBIlcYUWg4IleYUWg4PE+gd8brz8COce7wnpBIG2BvAfoBYG0BfK+/xGBdAXKUGFFoMDxPoG/BVh/BHLMZLz3Wj8ihUBJkqHCikAM0AikKFCmE3gEChjr/szi/A0PgZLFu8J6RiBtgQbjfbeqsCJQwGSqsCJQwNT4P6gFgXQF8h6gNwTSFsi6P9P6BB6BgiVThRWBgiVbhRWBgiVbhRWBgiVbhRWBGKARSEkg7/sdEUhXoBon8AcE0hUoY4UVgQJlMt5rhAorAgVKxgorApV+TuBHBNIVKGuFFYFKHyfwVwTSFihrhRWBgmQw3meUCisClT5O4I8IpCtQ5gorAnUwQG8IpC2QdX8m2gk8AjVO5gorAjVOjR+RGhBIV6DsFVYEapzsFVYEYoBGoMwCed/fiEC6AilUWBGoYRQqrAjUMJPx3iJWWBGo6J7AzwikK5BKhRWBhAfogkC6Aln3Z5bie0SCQMkEUqmwIlDRPIGfEEhXIKUKKwI1iFKFFYEEB+gNgbQFsu7PRD+BR6CidQJ/QiBdgWpUWJXrLO7swRfMu8Kq/IskVdiCL5p3hVW5D1WFOfiief+IlHIfvApD6XuAVq6zVGMVeWSPwvKsJTBD0GH6LPY6/mZ4HkpwIn57mUSepLXXAYk+fOffkCeGRHvJt+dxEHxtpZPnfSZq/TroeYBeM8w8/yvS/Pwwaz+VrAecS/KnzfZcawlxAAAAAAAAAAAAAAAAAAAAAAAAAKAH/gGsx7MBalRJ3QAAAABJRU5ErkJggg=="
# 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"

# 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 turns
# the title red — an inline symbol, the one SwiftBar path that takes a color.
TITLES = {
    "healthy": _RIFT_TITLE,
    "warning": _RIFT_TITLE,
    "broken": f":{TRIANGLE}: | sfcolor={RED}",
    "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 = [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()
