#!/usr/bin/python3
"""Crash notifications, history and diagnosis on top of systemd-coredump and the journal.

  lili-crash list                       programs that crashed, newest first, as JSON
  lili-crash mark <binary> <state> [summary]
  lili-crash notify <pid|boot|steam-id|launch-id>  desktop notification for one crash, freeze, Steam game
                                        that closed early, or app that exited with an error as it opened
  lili-crash watch                      notify every new crash, a Steam game that closes within 2 minutes,
                                        an app that fails within 20 seconds of opening, and a freeze from
                                        the last boot (run by the lili-crash service)
  lili-crash open                       Lili's window: usage and crash history
  lili-crash tray                       Lili in the system tray, for desktops other than KDE Plasma
  lili-crash diagnose <pid|boot|steam-id|launch-id>...  open Claude in a terminal to find out why
  lili-crash config [set <key> <value>] settings shared with the tray widget
  lili-crash install <agent>            run the agent's official installer in a terminal
  lili-crash skill <path|view|edit|reset>  this distro's notes for the diagnosis skill
  lili-crash setup [--if-needed]        per-user setup after installing a package: service, tray, skill
                                        (packages run it by themselves at each user's first login)
  lili-crash local setup                get the local AI ready: OpenCode, Ollama (in your home folder,
                                        unless you point Lili at your own Ollama server) and the model

A state (new, diagnosed, resolved, ignored) covers the crashes up to the moment it
was saved. If the program crashes again afterwards, it is new again.
"""

import configparser
import functools
import gettext
import json
import locale
import os
import re
import shlex
import shutil
import subprocess
import sys
import tempfile
import threading
import time
import urllib.parse
import urllib.request
from datetime import date, datetime, timedelta
from pathlib import Path

# A checkout keeps the skill next to bin/; a package puts Lili's data in /usr/share/lili-crash.
ROOT = Path(__file__).resolve().parent.parent
if not (ROOT / "skill").is_dir():
    ROOT = ROOT / "share" / "lili-crash"
LOCALEDIR = ROOT / "locale"
try:
    # Same rule as the rest of the desktop: glibc ignores LANGUAGE when the
    # configured locale isn't generated, so KDE stays in English, and so do we.
    locale.setlocale(locale.LC_MESSAGES, "")
    _ = gettext.translation("lili", LOCALEDIR if LOCALEDIR.is_dir() else None, fallback=True).gettext
except locale.Error:
    _ = gettext.NullTranslations().gettext

COREDUMP_MESSAGE_ID = "fc2e22bc6ee647b6b90729ab34a250b1"
STATE_DIR = Path(os.environ.get("XDG_STATE_HOME") or Path.home() / ".local/state") / "lili"
STATE_FILE = STATE_DIR / "state.json"
STATES = ("new", "diagnosed", "resolved", "ignored")
CONFIG_FILE = Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config") / "lili" / "config.json"


def reason(signal):
    return {
        "SIGSEGV": _("Touched memory it didn't own"),
        "SIGABRT": _("Gave up on an internal error"),
        "SIGBUS": _("Read memory that was no longer there"),
        "SIGFPE": _("Hit a math error, like dividing by zero"),
        "SIGILL": _("Tried to run an invalid instruction"),
        "SIGTRAP": _("Stopped at a debugger trap"),
        "SIGSYS": _("Made a forbidden system call"),
    }.get(signal) or _("Got signal {signal}").format(signal=signal)


def when(ts):
    moment = datetime.fromtimestamp(ts)
    hour = moment.strftime("%H:%M")
    if moment.date() == date.today():
        return _("today at {time}").format(time=hour)
    if moment.date() == date.today() - timedelta(days=1):
        return _("yesterday at {time}").format(time=hour)
    # Translators: strftime format for day and month, without the year.
    return _("on {date} at {time}").format(date=moment.strftime(_("%m/%d")), time=hour)


def data_dirs():
    dirs = [os.environ.get("XDG_DATA_HOME") or str(Path.home() / ".local/share"),
            str(Path.home() / ".local/share/flatpak/exports/share"), "/var/lib/flatpak/exports/share"]
    dirs += (os.environ.get("XDG_DATA_DIRS") or "").split(":") + ["/usr/local/share", "/usr/share"]
    return list(dict.fromkeys(d for d in dirs if d))


def read_desktop(path):
    parser = configparser.RawConfigParser(strict=False, interpolation=None)
    parser.optionxform = str
    try:
        parser.read(path, encoding="utf-8")
        return parser["Desktop Entry"]
    except (configparser.Error, KeyError, UnicodeDecodeError):
        return None


def desktop_by_id(app_id):
    for d in data_dirs():
        path = Path(d) / "applications" / f"{app_id}.desktop"
        if path.is_file():
            return read_desktop(path)
    return None


@functools.cache
def desktop_entries():
    # Parsing every .desktop file takes a tenth of a second; once per run is enough.
    return [entry for d in data_dirs() for path in sorted((Path(d) / "applications").glob("*.desktop"))
            if (entry := read_desktop(path))]


def desktop_by_exec(base):
    pattern = re.compile(rf"^([^ ]*/)?{re.escape(base)}( |$)")
    return next((entry for entry in desktop_entries() if pattern.match(entry.get("Exec", ""))), None)


def localized(entry, key):
    langs = (os.environ.get("LANGUAGE") or os.environ.get("LANG") or "").split(":")
    for lang in langs:
        lang = lang.split(".")[0]
        for variant in (lang, lang.split("_")[0]):
            if variant and entry.get(f"{key}[{variant}]"):
                return entry[f"{key}[{variant}]"]
    return entry.get(key)


def identity(comm, exe, unit):
    base = os.path.basename(exe) if exe else comm
    entry = None
    match = re.match(r"^app-flatpak-(.+)-\d+\.scope$", unit or "")
    if match:
        entry = desktop_by_id(match.group(1))
    else:
        # Anything started from a terminal lands in the terminal's scope, so the
        # scope only counts when the .desktop actually runs this binary.
        match = re.match(r"^app-(.+?)(@[^.]*\.service|-\d+\.scope)$", unit or "")
        if match:
            entry = desktop_by_id(match.group(1))
            if entry and base not in entry.get("Exec", ""):
                entry = None
    entry = entry or desktop_by_exec(base)
    if not entry:
        return comm or base, "application-x-executable"
    return localized(entry, "Name") or comm, entry.get("Icon") or "application-x-executable"


def crashes():
    fields = "COREDUMP_COMM,COREDUMP_EXE,COREDUMP_PID,COREDUMP_SIGNAL_NAME,COREDUMP_USER_UNIT,COREDUMP_TIMESTAMP,COREDUMP_UID"
    out = subprocess.run(["journalctl", "-o", "json", "--no-pager", f"--output-fields={fields}",
                          f"MESSAGE_ID={COREDUMP_MESSAGE_ID}"], capture_output=True, text=True).stdout
    for line in out.splitlines():
        try:
            e = json.loads(line)
            if e.get("COREDUMP_UID") != str(os.getuid()):
                continue
            yield {
                "pid": int(e["COREDUMP_PID"]),
                "comm": e.get("COREDUMP_COMM") or "",
                "exe": e.get("COREDUMP_EXE") or "",
                "signal": e.get("COREDUMP_SIGNAL_NAME") or "",
                "unit": e.get("COREDUMP_USER_UNIT") or "",
                "time": int(e.get("COREDUMP_TIMESTAMP") or e["__REALTIME_TIMESTAMP"]) // 1_000_000,
            }
        except (ValueError, KeyError, TypeError):
            continue


# logind says this whenever the system is asked to reboot or power off. A past boot
# without it ended some other way: the power button held down, a hard reset, a dead
# battery.
SHUTDOWN_MESSAGE_ID = "98268866d1d54a499c4e98921d93bc40"
FREEZE_KEY = "freeze"
BOOTS_FILE = STATE_DIR / "boots.json"
# Only the last stretch of a boot matters: drivers log harmless errors at startup,
# and a freeze always starts close to the end.
FREEZE_WINDOW = 30 * 60
FREEZE_SIGNS = [
    ("gpu", "nvidia", re.compile(r"NVRM: (Xid|GPU\d.*(fail|timeout|Timeout|stuck))|[Pp]age ?flip.*timed out|nvidia-modeset: ERROR")),
    ("gpu", "amdgpu", re.compile(r"amdgpu.*(ring \S+ timeout|GPU reset|GPU recovery|page fault)")),
    ("gpu", "i915", re.compile(r"i915.*(GPU HANG|[Rr]esetting)")),
    ("gpu", "xe", re.compile(r"\bxe\b.*(GPU hang|[Tt]imedout job|[Rr]eset)")),
    ("panic", "panic", re.compile(r"Kernel panic|Oops:|BUG: unable to handle")),
    ("lockup", "soft lockup", re.compile(r"soft lockup|hard LOCKUP|rcu.*detected stalls|blocked for more than \d+ seconds")),
    ("oom", "OOM", re.compile(r"Out of memory: Killed process")),
]


def freeze_reason(kind, tag):
    return {
        "gpu": _("The graphics driver ({driver}) stopped responding").format(driver=tag),
        "panic": _("The kernel crashed"),
        "lockup": _("The kernel got stuck"),
        "oom": _("It ran out of memory"),
    }.get(kind) or _("Nothing was logged before it stopped")


def journal(*args):
    return subprocess.run(["journalctl", "--no-pager", *args], capture_output=True, text=True).stdout


def inspect_boot(boot, last):
    """Returns how a past boot froze, or None if it shut down properly."""
    if journal("-b", boot, "-o", "cat", f"MESSAGE_ID={SHUTDOWN_MESSAGE_ID}").strip():
        return None
    freeze = {"boot": boot, "time": last, "kind": "unknown", "tag": "", "lines": []}
    shapes = set()
    out = journal("-b", boot, f"--since=@{last - FREEZE_WINDOW}", "-o", "json",
                  "--output-fields=MESSAGE,SYSLOG_IDENTIFIER")
    for line in out.splitlines():
        try:
            e = json.loads(line)
            message = e["MESSAGE"] if isinstance(e["MESSAGE"], str) else ""
        except (ValueError, KeyError):
            continue
        for kind, tag, pattern in FREEZE_SIGNS:
            if pattern.search(message):
                # The first sign is the cause; what follows is usually the fallout.
                if freeze["kind"] == "unknown":
                    freeze.update(kind=kind, tag=tag, time=int(e["__REALTIME_TIMESTAMP"]) // 1_000_000)
                seen = f"{e.get('SYSLOG_IDENTIFIER', '')}: {message[:300]}"
                # Hangs repeat the same complaint every few seconds; numbers aside, once is enough.
                shape = re.sub(r"\d+", "#", seen)
                if len(freeze["lines"]) < 6 and shape not in shapes:
                    shapes.add(shape)
                    freeze["lines"].append(seen)
                break
    return freeze


def load_boots():
    try:
        return json.loads(BOOTS_FILE.read_text())
    except (OSError, ValueError):
        return {}


def save_boots(boots):
    STATE_DIR.mkdir(parents=True, exist_ok=True)
    tmp = BOOTS_FILE.with_suffix(".tmp")
    tmp.write_text(json.dumps(boots, ensure_ascii=False, indent=1))
    tmp.replace(BOOTS_FILE)


def freezes():
    """Past boots that ended without a shutdown. A finished boot's journal doesn't
    change, so each one is read once and remembered."""
    try:
        listed = json.loads(journal("--list-boots", "-o", "json"))
    except ValueError:
        return []
    known = load_boots()
    changed = False
    for b in listed:
        if b["index"] == 0 or b["boot_id"] in known:
            continue
        known[b["boot_id"]] = {"freeze": inspect_boot(b["boot_id"], b["last_entry"] // 1_000_000)}
        changed = True
    if changed:
        save_boots(known)
    present = {b["boot_id"] for b in listed}
    return [v["freeze"] for k, v in known.items() if k in present and v.get("freeze")]


# A game that closes on its own right after starting leaves no core dump: Proton or
# the game gives up and exits cleanly, often after a message box. Steam's own logs
# are the only record, so a short run is the sign.
EARLY_EXIT = 120
STEAM_ROOTS = [Path.home() / ".local/share/Steam", Path.home() / ".steam/steam",
               Path.home() / ".var/app/com.valvesoftware.Steam/.local/share/Steam"]
STEAM_LINE = re.compile(r"^\[(\d{4}-\d\d-\d\d \d\d:\d\d:\d\d)\] (.*)")
STEAM_STATE = re.compile(r"AppID (\d+) state changed : (.*)")
# Noise every Proton launch prints: Steam preloads both overlay builds and one always misses.
STEAM_NOISE = re.compile(r"gameoverlayrenderer\.so.*wrong ELF class|ThreadGetProcessExitCode|Shader update|"
                         r"breakpad exception handler")
STEAM_TROUBLE = re.compile(r"\b(err|errors?|fail(ed|ure)?|fatal|exception|crash(ed)?|abort(ed)?|timed out|timeout|"
                           r"Logged Off|disconnect(ed)?)\b", re.I)


def steam_root():
    return next((r for r in STEAM_ROOTS if (r / "logs/content_log.txt").is_file()), None)


def steam_time(stamp):
    return int(datetime.strptime(stamp, "%Y-%m-%d %H:%M:%S").timestamp())


def steam_lines(root, name):
    # Steam starts a fresh log once it grows, keeping the old one as .previous.
    for path in (root / f"logs/{name}.previous.txt", root / f"logs/{name}.txt"):
        try:
            with open(path, errors="replace") as f:
                for line in f:
                    match = STEAM_LINE.match(line.rstrip("\n"))
                    if match:
                        yield steam_time(match.group(1)), match.group(2)
        except OSError:
            continue


class SteamRuns:
    """Pairs 'App Running' with the state change that clears it, line by line."""

    def __init__(self):
        self.started = {}

    def feed(self, ts, text):
        match = STEAM_STATE.match(text)
        if not match:
            return None
        appid, running = match.group(1), "App Running" in match.group(2)
        if running:
            self.started.setdefault(appid, ts)
        elif appid in self.started:
            start = self.started.pop(appid)
            return {"appid": appid, "start": start, "time": ts, "seconds": ts - start}
        return None


def steam_game(root, appid):
    libraries = [root]
    try:
        libraries += [Path(p) for p in re.findall(r'"path"\s+"([^"]+)"', (root / "steamapps/libraryfolders.vdf").read_text())]
    except OSError:
        pass
    for library in dict.fromkeys(libraries):
        try:
            name = re.search(r'"name"\s+"([^"]+)"', (library / f"steamapps/appmanifest_{appid}.acf").read_text())
        except OSError:
            continue
        if name:
            return name.group(1)
    return f"AppID {appid}"


def steam_icon(appid):
    # Steam drops one of these for every game with a desktop shortcut.
    for d in data_dirs():
        if list(Path(d).glob(f"icons/hicolor/*/apps/steam_icon_{appid}.png")):
            return f"steam_icon_{appid}"
    return "steam"


def early_exits():
    root = steam_root()
    if not root:
        return []
    runs, found = SteamRuns(), []
    for ts, text in steam_lines(root, "content_log"):
        run = runs.feed(ts, text)
        if run and run["seconds"] < EARLY_EXIT:
            found.append(run)
    return found


def steam_id(run):
    return f"steam-{run['appid']}-{run['start']}"


def is_steam(target):
    return bool(re.fullmatch(r"steam-\d+-\d+", target))


def find_early_exit(target):
    for run in early_exits():
        if steam_id(run) == target:
            return run
    sys.exit(_("No early exit recorded for {id}").format(id=target))


def steam_evidence(root, run):
    """What Steam logged while the game ran: how it was launched, and what went wrong."""
    command, trouble, shapes = "", [], set()
    for log in ("console_log", "console-linux", "connection_log"):
        for ts, text in steam_lines(root, log):
            if not run["start"] - 2 <= ts <= run["time"] + 5:
                continue
            if not command and f"Game process added : AppID {run['appid']} " in text:
                command = text.split('"', 1)[-1].rstrip('"')
            elif STEAM_TROUBLE.search(text) and not STEAM_NOISE.search(text):
                shape = re.sub(r"\d+", "#", text)
                if len(trouble) < 12 and shape not in shapes:
                    shapes.add(shape)
                    trouble.append(f"{log}: {text[:300]}")
    tool = re.search(r"common/([^/']+)'?/proton ", command)
    return (tool.group(1) if tool else ""), command, trouble


# Plasma starts everything it opens (the menu, a double click in Dolphin, KRunner) as a
# user service of its own, so an app that gives up before its window appears (an
# AppImage without FUSE, a missing library) still leaves its output and systemd's
# verdict in the user journal. A crash is left to its core dump; this is the error exit.
UNIT_STARTED_MESSAGE_ID = "39f53479d3a045ac8e11786248231fbf"
UNIT_FAILED_MESSAGE_ID = "d9b373ed55a64feb8242e02dbe79a49c"
UNIT_EXITED_MESSAGE_ID = "98e322203f7a4ed290d09fe03c09fe15"
APP_UNIT = re.compile(r"^app-(.+?)@([^.]+)\.service$")
# Tighter than a game's two minutes: an app that shows its window and is then closed
# with an error (a wizard cancelled after a minute exits 1) did open.
LAUNCH_EXIT = 20


def journal_json(*args):
    for line in journal("--user", "-o", "json", *args).splitlines():
        try:
            yield json.loads(line)
        except ValueError:
            continue


def unescape_unit(name):
    return re.sub(rb"\\x([0-9a-f]{2})", lambda m: bytes([int(m.group(1), 16)]), name.encode()).decode(errors="replace")


def launch_identity(app):
    """A launch runs either a .desktop id or, for a file opened directly, its path."""
    base = os.path.basename(app)
    entry = desktop_by_exec(base) if app.startswith("/") else desktop_by_id(app)
    if not entry:
        return base, "application-x-executable"
    return localized(entry, "Name") or base, entry.get("Icon") or "application-x-executable"


def failed_launches():
    failed = {}
    for e in journal_json("--output-fields=USER_UNIT,USER_INVOCATION_ID",
                          f"MESSAGE_ID={UNIT_FAILED_MESSAGE_ID}", "UNIT_RESULT=exit-code"):
        match = APP_UNIT.match(e.get("USER_UNIT", ""))
        # Login items fail on their own schedule; nobody clicked them and waited.
        if not match or match.group(2) == "autostart" or not e.get("USER_INVOCATION_ID"):
            continue
        failed[e["USER_INVOCATION_ID"]] = {"unit": e["USER_UNIT"], "app": unescape_unit(match.group(1)),
                                           "time": int(e["__REALTIME_TIMESTAMP"]) // 1_000_000}
    if not failed:
        return []
    found = []
    for e in journal_json("--output-fields=USER_INVOCATION_ID", f"MESSAGE_ID={UNIT_STARTED_MESSAGE_ID}",
                          *(f"USER_INVOCATION_ID={i}" for i in failed)):
        run = failed.get(e.get("USER_INVOCATION_ID"))
        if run and "start" not in run:
            run.update(id=launch_id(e["USER_INVOCATION_ID"]), start=int(e["__REALTIME_TIMESTAMP"]) // 1_000_000)
            run["seconds"] = run["time"] - run["start"]
            if run["seconds"] < LAUNCH_EXIT:
                found.append(run)
    if found:
        for e in journal_json("--output-fields=USER_INVOCATION_ID,EXIT_STATUS", f"MESSAGE_ID={UNIT_EXITED_MESSAGE_ID}",
                              *(f"USER_INVOCATION_ID={r['id'].removeprefix('launch-')}" for r in found)):
            run = failed.get(e.get("USER_INVOCATION_ID"))
            if run:
                run["status"] = e.get("EXIT_STATUS", "")
    return sorted(found, key=lambda r: r["time"])


def launch_id(invocation):
    return f"launch-{invocation}"


def is_launch(target):
    return bool(re.fullmatch(r"launch-[0-9a-f]{32}", target))


def find_launch(target):
    for run in failed_launches():
        if run["id"] == target:
            return run
    sys.exit(_("No failed start recorded for {id}").format(id=target))


def launch_output(run):
    """What the app printed before it gave up."""
    return [line for line in journal("--user", "-o", "cat", f"_SYSTEMD_USER_UNIT={run['unit']}").splitlines()
            if line.strip()][:20]


def launch_reason(seconds):
    if seconds < 1:
        return _("Exited with an error as soon as it started")
    return _("Exited with an error {seconds} seconds after starting").format(seconds=seconds)


def load_state():
    try:
        return json.loads(STATE_FILE.read_text())
    except (OSError, ValueError):
        return {}


def mark(exe, state, summary=""):
    if state not in STATES:
        sys.exit(_("Unknown state: {state}. Use one of: {states}").format(state=state, states=", ".join(STATES)))
    saved = load_state()
    # Resolving or ignoring keeps the summary the diagnosis wrote.
    saved[exe] = {"state": state, "until": int(time.time()), "summary": summary or saved.get(exe, {}).get("summary", "")}
    STATE_DIR.mkdir(parents=True, exist_ok=True)
    tmp = STATE_FILE.with_suffix(".tmp")
    tmp.write_text(json.dumps(saved, ensure_ascii=False, indent=1))
    tmp.replace(STATE_FILE)


def programs():
    saved = load_state()
    grouped = {}
    for c in crashes():
        grouped.setdefault(c["exe"] or c["comm"], []).append(c)
    result = []
    for exe, items in grouped.items():
        items.sort(key=lambda c: c["time"])
        last = items[-1]
        name, icon = identity(last["comm"], last["exe"], last["unit"])
        state = saved.get(exe, {})
        fresh = [c for c in items if c["time"] > state.get("until", 0)]
        result.append({
            "exe": exe,
            "name": name,
            "icon": icon,
            "state": "new" if fresh else state.get("state", "new"),
            "summary": state.get("summary", ""),
            "count": len(items),
            "fresh": len(fresh),
            "last": {**last, "id": str(last["pid"]), "reason": reason(last["signal"]), "when": when(last["time"])},
            "crashes": items,
        })
    frozen = sorted(freezes(), key=lambda f: f["time"])
    if frozen:
        state = saved.get(FREEZE_KEY, {})
        fresh = [f for f in frozen if f["time"] > state.get("until", 0)]
        last = frozen[-1]
        result.append({
            "exe": FREEZE_KEY,
            "name": _("The computer froze"),
            "icon": "computer",
            "state": "new" if fresh else state.get("state", "new"),
            "summary": state.get("summary", ""),
            "count": len(frozen),
            "fresh": len(fresh),
            "last": {"id": last["boot"], "signal": last["tag"] or _("no log"), "time": last["time"],
                     "reason": freeze_reason(last["kind"], last["tag"]), "when": when(last["time"])},
            "crashes": frozen,
        })
    games = {}
    for run in early_exits():
        games.setdefault(run["appid"], []).append(run)
    root = steam_root()
    for appid, runs in games.items():
        key = f"steam:{appid}"
        state = saved.get(key, {})
        fresh = [r for r in runs if r["time"] > state.get("until", 0)]
        last = runs[-1]
        tool, _command, _trouble = steam_evidence(root, last)
        result.append({
            "exe": key,
            "name": steam_game(root, appid),
            "icon": steam_icon(appid),
            "state": "new" if fresh else state.get("state", "new"),
            "summary": state.get("summary", ""),
            "count": len(runs),
            "fresh": len(fresh),
            "last": {"id": steam_id(last), "signal": tool or "Steam", "time": last["time"],
                     "reason": early_exit_reason(last["seconds"]), "when": when(last["time"])},
            "crashes": runs,
        })
    apps = {}
    for run in failed_launches():
        apps.setdefault(run["app"], []).append(run)
    for app, runs in apps.items():
        key = f"launch:{app}"
        state = saved.get(key, {})
        fresh = [r for r in runs if r["time"] > state.get("until", 0)]
        last = runs[-1]
        name, icon = launch_identity(app)
        status = last.get("status")
        result.append({
            "exe": key,
            "name": name,
            "icon": icon,
            "state": "new" if fresh else state.get("state", "new"),
            "summary": state.get("summary", ""),
            "count": len(runs),
            "fresh": len(fresh),
            "last": {"id": last["id"], "signal": f"exit {status}" if status else "exit", "time": last["time"],
                     "reason": launch_reason(last["seconds"]), "when": when(last["time"])},
            "crashes": runs,
        })
    return sorted(result, key=lambda p: p["last"]["time"], reverse=True)


def early_exit_reason(seconds):
    return _("Closed by itself {seconds} seconds after starting").format(seconds=seconds)


def find(pid):
    for p in programs():
        for c in p["crashes"]:
            if c.get("pid") == pid:
                return p, c
    sys.exit(_("No core dump with PID {pid}").format(pid=pid))


def find_freeze(boot):
    for f in freezes():
        if f["boot"] == boot:
            return f
    sys.exit(_("No freeze recorded for boot {boot}").format(boot=boot))


def notify(target):
    if is_boot(target):
        freeze = find_freeze(target)
        icon, title = "computer", _("The computer froze")
        text = _("{reason}, {when}. It had to be forced off.").format(
            reason=freeze_reason(freeze["kind"], freeze["tag"]), when=when(freeze["time"]))
    elif is_steam(target):
        run = find_early_exit(target)
        root = steam_root()
        tool, _command, _trouble = steam_evidence(root, run)
        icon, title = steam_icon(run["appid"]), _("{name} closed by itself").format(name=steam_game(root, run["appid"]))
        text = _("{reason}, {when}.").format(reason=early_exit_reason(run["seconds"]), when=when(run["time"]))
        if tool:
            text += " " + _("It ran with {tool}.").format(tool=tool)
    elif is_launch(target):
        run = find_launch(target)
        name, icon = launch_identity(run["app"])
        title = _("{name} didn't open").format(name=name)
        text = _("{reason}, {when}.").format(reason=launch_reason(run["seconds"]), when=when(run["time"]))
        output = launch_output(run)
        # The first line it printed is usually the whole story (a missing library).
        if output:
            text += "\n" + output[0][:160]
    else:
        program, crash = find(int(target))
        icon, title = program["icon"], _("{name} crashed").format(name=program["name"])
        text = _("{reason} ({signal}), {when}.").format(reason=reason(crash["signal"]), signal=crash["signal"],
                                                        when=when(crash["time"]))
    # The configured locale may not be generated, and notify-send then refuses
    # anything that isn't ASCII.
    env = {**os.environ, "LC_ALL": "C.UTF-8"}
    button = _("Find out why")
    # "default" is a click on the notification body; Plasma doesn't draw it as a button.
    action = subprocess.run(
        ["notify-send", "--app-name=Lili Crash", f"--icon={icon}", "--hint=string:desktop-entry:lili-crash", "--hint=boolean:transient:true", "--urgency=normal", "--expire-time=0",
         f"--action=default={button}", f"--action=diagnose={button}", "--", title, text],
        env=env, capture_output=True, text=True).stdout.strip()
    if action in ("default", "diagnose"):
        diagnose([target])


def is_boot(target):
    return bool(re.fullmatch(r"[0-9a-f]{32}", target))


def notify_last_freeze():
    """A freeze can't be announced while it happens (the screen is usually gone), so
    the next login tells about the boot before it, once."""
    found = freezes()
    boots = load_boots()
    frozen = [f for f in found if not boots[f["boot"]].get("notified")]
    if not frozen or load_state().get(FREEZE_KEY, {}).get("state") == "ignored":
        return
    for f in frozen:
        boots[f["boot"]]["notified"] = True
    save_boots(boots)
    last = max(frozen, key=lambda f: f["time"])
    # Only a freeze from the last day is news; older ones wait in the list.
    if time.time() - last["time"] < 86400:
        subprocess.Popen([sys.argv[0], "notify", last["boot"]], start_new_session=True,
                         stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)


def watch_steam(root):
    """Follows Steam's content log and notifies each game that closed too soon."""
    runs = SteamRuns()
    # -F keeps following when Steam rotates the log to content_log.previous.txt.
    follow = subprocess.Popen(["tail", "-F", "-n", "0", str(root / "logs/content_log.txt")],
                              stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, errors="replace")
    for line in follow.stdout:
        match = STEAM_LINE.match(line.rstrip("\n"))
        run = match and runs.feed(steam_time(match.group(1)), match.group(2))
        if not run or run["seconds"] >= EARLY_EXIT:
            continue
        if load_state().get(f"steam:{run['appid']}", {}).get("state") == "ignored":
            continue
        subprocess.Popen([sys.argv[0], "notify", steam_id(run)], start_new_session=True,
                         stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)


def watch_launches():
    """Follows the user journal and notifies each app that failed right after starting."""
    follow = subprocess.Popen(["journalctl", "--user", "-f", "-n", "0", "-o", "json",
                               "--output-fields=USER_UNIT,USER_INVOCATION_ID,UNIT_RESULT",
                               f"MESSAGE_ID={UNIT_FAILED_MESSAGE_ID}"], stdout=subprocess.PIPE, text=True)
    last_seen = {}
    for line in follow.stdout:
        try:
            e = json.loads(line)
        except ValueError:
            continue
        match = APP_UNIT.match(e.get("USER_UNIT", ""))
        invocation = e.get("USER_INVOCATION_ID", "")
        if e.get("UNIT_RESULT") != "exit-code" or not match or match.group(2) == "autostart" or not invocation:
            continue
        app = unescape_unit(match.group(1))
        if load_state().get(f"launch:{app}", {}).get("state") == "ignored":
            continue
        # Double clicking again and again on something that won't open is one problem.
        if time.time() - last_seen.get(app, 0) < 60:
            continue
        run = next((r for r in failed_launches() if r["id"] == launch_id(invocation)), None)
        if not run:
            continue
        last_seen[app] = time.time()
        subprocess.Popen([sys.argv[0], "notify", run["id"]], start_new_session=True,
                         stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)


def watch():
    """Follows the journal and notifies each new crash of this user's programs."""
    notify_last_freeze()
    root = steam_root()
    if root:
        threading.Thread(target=watch_steam, args=(root,), daemon=True).start()
    threading.Thread(target=watch_launches, daemon=True).start()
    last_seen = {}
    follow = subprocess.Popen(["journalctl", "-f", "-n", "0", "-o", "json", "--output-fields=COREDUMP_PID,COREDUMP_EXE,"
                               "COREDUMP_COMM,COREDUMP_UID", f"MESSAGE_ID={COREDUMP_MESSAGE_ID}"],
                              stdout=subprocess.PIPE, text=True)
    for line in follow.stdout:
        try:
            e = json.loads(line)
            pid = int(e["COREDUMP_PID"])
        except (ValueError, KeyError, TypeError):
            continue
        if e.get("COREDUMP_UID") != str(os.getuid()):
            continue
        exe = e.get("COREDUMP_EXE") or e.get("COREDUMP_COMM") or ""
        if load_state().get(exe, {}).get("state") == "ignored":
            continue
        # A program stuck in a crash loop would otherwise bury the screen in toasts.
        if time.time() - last_seen.get(exe, 0) < 60:
            continue
        last_seen[exe] = time.time()
        subprocess.Popen([sys.argv[0], "notify", str(pid)], start_new_session=True,
                         stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)


def open_window():
    setup_if_needed()
    if shutil.which("plasmawindowed"):
        os.execvp("plasmawindowed", ["plasmawindowed", "lili"])
    if not tray_running() and tray_toolkit():
        tray()
    # Without Plasma there's no panel to show, so the history goes to a terminal.
    open_terminal("Lili Crash", f"{shlex.quote(sys.argv[0])} list | python3 -m json.tool\n")


def tray_toolkit():
    # AppIndicator is what GNOME, XFCE, Cinnamon and MATE panels show, and every
    # distribution packages it; PySide6 is missing from Ubuntu 24.04 and Debian 12.
    try:
        import gi
        gi.require_version("Gtk", "3.0")
        gi.require_version("AyatanaAppIndicator3", "0.1")
        from gi.repository import AyatanaAppIndicator3, GLib, Gtk
        return AyatanaAppIndicator3, GLib, Gtk
    except (ImportError, ValueError):
        return None


def tray():
    # Plasma has the panel widget; everywhere else this is Lili's place next to the clock.
    toolkit = tray_toolkit()
    if not toolkit:
        sys.exit(_("The tray icon needs AppIndicator: install gir1.2-ayatanaappindicator3-0.1 on Debian and "
                   "Ubuntu, libayatana-appindicator-gtk3 on Fedora, libayatana-appindicator on Arch."))
    AppIndicator, GLib, Gtk = toolkit
    GLib.set_prgname("lili-crash")
    GLib.set_application_name("Lili Crash")
    indicator = AppIndicator.Indicator.new("lili-crash", "lili-crash-symbolic",
                                           AppIndicator.IndicatorCategory.APPLICATION_STATUS)
    indicator.set_title("Lili Crash")
    # Inside the source checkout the icons aren't in any theme yet.
    logo = ROOT / "plasma" / "lili" / "contents" / "images"
    if (logo / "logo-symbolic.svg").is_file() and not any(
            (Path(d) / "icons/hicolor/scalable/apps/lili-crash-symbolic.svg").is_file()
            for d in [os.environ.get("XDG_DATA_HOME") or str(Path.home() / ".local/share"), *data_dirs()]):
        indicator.set_icon_theme_path(str(logo))
        indicator.set_icon_full("logo-symbolic", "Lili Crash")
    indicator.set_attention_icon_full("lili-crash", _("Something crashed"))
    me = str(Path(sys.argv[0]).absolute())
    run = lambda *args: subprocess.Popen([me, *args], start_new_session=True,
                                         stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)

    def item(menu, text, handler=None, enabled=True):
        entry = Gtk.MenuItem(label=text)
        entry.set_sensitive(enabled)
        if handler:
            entry.connect("activate", lambda _w: handler())
        menu.append(entry)
        return entry

    def submenu(menu, text):
        sub = Gtk.Menu()
        item(menu, text).set_submenu(sub)
        return sub

    def set_state(key, state):
        mark(key, state)
        refresh()

    def choose_agent(agent):
        set_config("agent", agent)
        refresh()

    def refresh():
        found = programs()
        new = [p for p in found if p["state"] == "new"]
        indicator.set_status(AppIndicator.IndicatorStatus.ATTENTION if new else AppIndicator.IndicatorStatus.ACTIVE)
        menu = Gtk.Menu()
        item(menu, _("Lili Crash: {count} new").format(count=len(new)) if new else _("Lili Crash: nothing new"),
             enabled=False)
        if len(new) > 1:
            item(menu, _("Find out why, all {count}").format(count=len(new)),
                 lambda: run("diagnose", *[p["last"]["id"] for p in new]))
        menu.append(Gtk.SeparatorMenuItem())
        for p in found[:10]:
            mark_ = {"new": "● ", "diagnosed": "✓ ", "resolved": "✓ ", "ignored": "– "}.get(p["state"], "")
            sub = submenu(menu, f"{mark_}{p['name']}, {p['last']['when']}")
            item(sub, p["summary"] or p["last"]["reason"], enabled=False)
            item(sub, _("Find out why"), lambda i=p["last"]["id"]: run("diagnose", i))
            item(sub, _("Mark as resolved"), lambda k=p["exe"]: set_state(k, "resolved"))
            if p["state"] == "ignored":
                item(sub, _("Stop ignoring"), lambda k=p["exe"]: set_state(k, "new"))
            else:
                item(sub, _("Ignore from now on"), lambda k=p["exe"]: set_state(k, "ignored"))
        if not found:
            item(menu, _("No crashes yet"), enabled=False)
        menu.append(Gtk.SeparatorMenuItem())
        settings = load_config()
        ai = submenu(menu, _("Diagnose with"))
        ready = {a: local_ready(settings) if a == "ollama" else bool(which(spec["command"])) for a, spec in AGENTS.items()}
        group = []
        for agent, spec in AGENTS.items():
            if ready[agent]:
                choice = Gtk.RadioMenuItem.new_with_label(group, spec["name"])
                group = choice.get_group()
                choice.set_active(settings["agent"] == agent)
                choice.connect("toggled", lambda w, a=agent: w.get_active() and choose_agent(a))
                ai.append(choice)
        ai.append(Gtk.SeparatorMenuItem())
        for agent, spec in AGENTS.items():
            if not ready[agent]:
                item(ai, _("Install {agent}").format(agent=spec["name"]), lambda a=agent: run("install", a))
        item(menu, _("Quit"), Gtk.main_quit)
        menu.show_all()
        indicator.set_menu(menu)
        return True

    refresh()
    GLib.timeout_add_seconds(20, refresh)
    Gtk.main()


def user_language():
    for var in ("LANGUAGE", "LC_ALL", "LC_MESSAGES", "LANG"):
        value = os.environ.get(var, "").split(":")[0].split(".")[0]
        if value and value not in ("C", "POSIX"):
            return value
    return "en"


# A bare code like pt_BR is enough for a large model; a small local one needs the name,
# or it answers in the language's other variant.
LANGUAGE_NAMES = {"pt_BR": "Brazilian Portuguese", "pt_PT": "European Portuguese", "pt": "Portuguese",
                  "es": "Spanish", "fr": "French", "de": "German", "it": "Italian", "en": "English"}


def language_name(code):
    name = LANGUAGE_NAMES.get(code) or LANGUAGE_NAMES.get(code.split("_")[0])
    return f"{name} ({code})" if name else code


def diagnose(targets):
    facts, names, frozen = [], [], []
    for target in targets:
        if is_boot(target):
            f = find_freeze(target)
            stamp = datetime.fromtimestamp(f["time"]).strftime("%Y-%m-%d %H:%M:%S")
            seen = "\n".join(f"    {line}" for line in f["lines"]) or "    (nothing matched)"
            facts.append(f"- The whole computer froze and was forced off: boot {target}, around {stamp}, "
                         f"no shutdown recorded. First warning signs Lili matched in its last "
                         f"{FREEZE_WINDOW // 60} minutes (key '{FREEZE_KEY}'):\n{seen}")
            names.append(_("The computer froze"))
            frozen.append(target)
            continue
        if is_steam(target):
            run, root = find_early_exit(target), steam_root()
            name = steam_game(root, run["appid"])
            tool, command, trouble = steam_evidence(root, run)
            fmt = "%Y-%m-%d %H:%M:%S"
            seen = "\n".join(f"    {line}" for line in trouble) or "    (nothing matched)"
            facts.append(f"- Steam game {name} (AppID {run['appid']}) closed by itself {run['seconds']} seconds "
                         f"after starting, from {datetime.fromtimestamp(run['start']).strftime(fmt)} to "
                         f"{datetime.fromtimestamp(run['time']).strftime(fmt)}, with no core dump. "
                         f"Compatibility tool: {tool or 'none found (native, or the launch line was not logged)'}. "
                         f"Launch command: {command or 'not found'}. Steam's logs are in {root / 'logs'}; "
                         f"lines Lili matched in that window (key 'steam:{run['appid']}'):\n{seen}")
            names.append(name)
            continue
        if is_launch(target):
            run = find_launch(target)
            name, _icon = launch_identity(run["app"])
            status, output = run.get("status"), launch_output(run)
            seen = "\n".join(f"    {line}" for line in output) or "    (it printed nothing)"
            facts.append(f"- {name} ({run['app']}) was started from the desktop and exited with status "
                         f"{status or 'unknown'} {run['seconds']} seconds later, at "
                         f"{datetime.fromtimestamp(run['time']).strftime('%Y-%m-%d %H:%M:%S')}, with no core dump. "
                         f"It ran as the user service {run['unit']}; what it printed "
                         f"(key 'launch:{run['app']}'):\n{seen}")
            names.append(name)
            continue
        program, crash = find(int(target))
        stamp = datetime.fromtimestamp(crash["time"]).strftime("%Y-%m-%d %H:%M:%S")
        facts.append(f"- {program['name']}: PID {target}, binary {program['exe']}, signal {crash['signal']}, "
                     f"{stamp}, {program['count']} crash(es) of this program in the journal")
        names.append(program["name"])

    where = f"{distro()[1]}, {os.environ.get('XDG_CURRENT_DESKTOP') or 'Linux desktop'}"
    virt = virtualization()
    if virt:
        where += f", a {virt} virtual machine"
    if len(targets) == 1 and frozen:
        ask = f"This computer ({where}) froze and had to be forced off, and I'd like to know why."
        title = _("Diagnosis: {name}").format(name=names[0])
    elif len(targets) == 1 and is_steam(targets[0]):
        ask = f"A Steam game closed by itself right after starting on this machine ({where}), and I'd like to know why."
        title = _("Diagnosis: {name}").format(name=names[0])
    elif len(targets) == 1 and is_launch(targets[0]):
        ask = f"An app wouldn't open on this machine ({where}): it exited with an error right away, and I'd like to know why."
        title = _("Diagnosis: {name}").format(name=names[0])
    elif len(targets) == 1:
        ask = f"A program crashed on this machine ({where}) and I'd like to know why."
        title = _("Diagnosis: {name}").format(name=names[0])
    else:
        ask = (f"Several things crashed on this machine ({where}). Go through them one at a time, "
               "in order, and check whether they share a cause.")
        title = _("Diagnosis: {count} programs").format(count=len(targets))
    prompt = (f"{ask}\n\nWhat the journal recorded:\n" + "\n".join(facts) +
              f"\n\nUse the lili-diagnose-crash skill (if your tool has no skills, read {SKILL_FILE}), "
              f"and the notes for this distro in {notes_path()}. "
              "Start by deciding whether this affected me at all: if it's harmless, say so in a few sentences "
              "and stop. Give me a first answer after about five commands rather than running many in a row. "
              "Don't change anything on the system; if there's a fix, propose it and ask before applying it. "
              f"Reply in the user's language: {language_name(user_language())}.")

    settings = load_config()
    agent = AGENTS.get(settings["agent"], AGENTS["claude"])
    binary = which(agent["command"])
    if not binary:
        sys.exit(_("{agent} isn't installed: {url}").format(agent=agent["name"], url=agent["url"]))
    model = settings.get(f"{settings['agent']}_model", "default")
    argv = [binary]
    before = ""
    if settings["agent"] == "ollama":
        # Getting the model ready is quick when it already is, and shows its progress when it isn't.
        name = local_model_name(settings)
        before = (f"{shlex.quote(str(Path(sys.argv[0]).absolute()))} local setup || exit\n"
                  f"export OPENCODE_CONFIG_CONTENT={shlex.quote(json.dumps(opencode_config(settings)))}\n")
        argv += [agent["model_flag"], f"ollama/{name}"]
    elif agent["model_flag"] and model != "default":
        argv += [agent["model_flag"], model]
    argv += agent["prompt"]

    STATE_DIR.mkdir(parents=True, exist_ok=True)
    fd, prompt_file = tempfile.mkstemp(dir=STATE_DIR, prefix="prompt-")
    with os.fdopen(fd, "w") as f:
        f.write(prompt)
    command = " ".join('"$prompt"' if a is PROMPT else shlex.quote(a) for a in argv)
    open_terminal(title, f"prompt=$(cat {shlex.quote(prompt_file)})\n"
                         f"rm -f {shlex.quote(prompt_file)}\n"
                         f"{before}{command}\n")


LOCAL_MODEL = "qwen3.5:4b"
# Ollama gives cards under 24 GB a 4k window, and OpenCode needs 64k, so Lili keeps
# its own copy of the model with the bigger window. It shares the weights, not a copy.
LOCAL_CONTEXT = 65536


def local_model(settings):
    chosen = settings["ollama_model"]
    return LOCAL_MODEL if chosen == "default" else chosen


def local_model_name(settings):
    return "lili-" + re.sub(r"[^a-z0-9._-]", "-", local_model(settings).lower())


# Commands that only read what a diagnosis needs run without asking; anything else
# still asks, and nothing gets edited. Otherwise the user spends the session clicking "allow".
READ_ONLY_COMMANDS = ("journalctl", "coredumpctl", "systemctl status", "systemctl --user status",
                      "lili-crash", "cat", "head", "tail", "grep", "ls", "uname", "lspci", "lsusb",
                      "free", "df", "uptime", "dmesg", "systemd-detect-virt", "pacman -Q", "rpm -q",
                      "dpkg -l", "dpkg -s", "flatpak list", "nvidia-smi", "file", "stat", "date", "echo",
                      "wc", "sort", "uniq", "which", "id", "whoami", "hostnamectl", "lsblk", "findmnt")


def opencode_config(settings):
    name = local_model_name(settings)
    bash = {"*": "ask", **{f"{c} *": "allow" for c in READ_ONLY_COMMANDS}, **{c: "allow" for c in READ_ONLY_COMMANDS}}
    return {"provider": {"ollama": {"npm": "@ai-sdk/openai-compatible", "name": "Ollama",
                                    "options": {"baseURL": settings["ollama_url"].rstrip("/") + "/v1"},
                                    # A small model that thinks before every step takes many minutes
                                    # per step; without it each step takes seconds.
                                    "models": {name: {"name": f"{local_model(settings)} (Lili)", "tools": True,
                                                      "options": {"reasoningEffort": "none"}}}}},
            "permission": {"edit": "deny", "external_directory": "allow", "bash": bash}}


def ollama(settings, path, body=None, timeout=5):
    request = urllib.request.Request(settings["ollama_url"].rstrip("/") + path,
                                     data=None if body is None else json.dumps(body).encode(),
                                     headers={"Content-Type": "application/json"})
    return urllib.request.urlopen(request, timeout=timeout)


def ollama_models(settings, timeout=5):
    try:
        with ollama(settings, "/api/tags", timeout=timeout) as r:
            return {m["name"] for m in json.load(r).get("models", [])}
    except (OSError, ValueError):
        return None


def local_ready(settings, timeout=0.5):
    names = ollama_models(settings, timeout)
    return bool(which("opencode")) and names is not None and f"{local_model_name(settings)}:latest" in names


def is_localhost(url):
    host = urllib.parse.urlsplit(url).hostname or ""
    return host in ("localhost", "127.0.0.1", "::1")


OLLAMA_UNIT = """[Unit]
Description=Ollama, the local AI for Lili Crash

[Service]
ExecStart={binary} serve
Restart=on-failure

[Install]
WantedBy=default.target
"""


def local_setup():
    settings = load_config()
    url = settings["ollama_url"]
    step = lambda text: print(f"\n>> {text}", flush=True)
    sh = lambda command: subprocess.run(["sh", "-c", command]).returncode == 0

    if not which("opencode"):
        step(_("Installing OpenCode"))
        if not sh(AGENTS["opencode"]["install"]) or not which("opencode"):
            sys.exit(_("OpenCode didn't install; see the messages above."))

    if ollama_models(settings) is None:
        if not is_localhost(url):
            sys.exit(_("No Ollama answering at {url}. Start it there, or set the address back to "
                       "http://localhost:11434 to run it on this computer.").format(url=url))
        binary = which("ollama")
        if not binary:
            step(_("Installing Ollama in your home folder (about 2 GB, it brings its own GPU libraries)"))
            home = Path.home() / ".local"
            arch = {"x86_64": "amd64", "aarch64": "arm64"}.get(os.uname().machine, "amd64")
            if not shutil.which("zstd"):
                sys.exit(_("Ollama comes as a .tar.zst file; install your distribution's zstd package and try again."))
            if not sh(f"curl -fL --progress-bar https://ollama.com/download/ollama-linux-{arch}.tar.zst "
                      f"| tar --zstd -x -C {shlex.quote(str(home))}"):
                sys.exit(_("Ollama didn't download; see the messages above."))
            binary = str(home / "bin" / "ollama")
        step(_("Starting Ollama as a service of your user"))
        unit = Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config") / "systemd/user/lili-ollama.service"
        unit.parent.mkdir(parents=True, exist_ok=True)
        unit.write_text(OLLAMA_UNIT.format(binary=binary))
        sh("systemctl --user daemon-reload && systemctl --user enable --now lili-ollama.service")
        for _i in range(30):
            if ollama_models(settings) is not None:
                break
            time.sleep(1)
        else:
            sys.exit(_("Ollama didn't start: journalctl --user -u lili-ollama"))

    names = ollama_models(settings) or set()
    model, name = local_model(settings), local_model_name(settings)
    if model not in names and f"{model}:latest" not in names:
        step(_("Downloading {model}; this happens once").format(model=model))
        with ollama(settings, "/api/pull", {"model": model}, timeout=None) as r:
            shown = ""
            for line in r:
                event = json.loads(line)
                if event.get("error"):
                    sys.exit(event["error"])
                done, total = event.get("completed"), event.get("total")
                text = f"{event.get('status', '')} {100 * done // total}%" if done and total else event.get("status", "")
                if text != shown:
                    print(f"\r   {text:<60}", end="", flush=True)
                    shown = text
        print()
    if f"{name}:latest" not in names:
        step(_("Giving the model room to read logs ({size}k tokens)").format(size=LOCAL_CONTEXT // 1024))
        with ollama(settings, "/api/create", {"model": name, "from": model, "stream": False,
                                              "parameters": {"num_ctx": LOCAL_CONTEXT}}, timeout=None) as r:
            if json.load(r).get("status") != "success":
                sys.exit(_("Ollama couldn't prepare the model."))
    print(_("The local AI is ready: {model} through Ollama at {url}.").format(model=model, url=url), flush=True)


def install(name):
    agent = AGENTS.get(name) or sys.exit(_("Unknown agent: {agent}").format(agent=name))
    done = _("Done. You can close this window.")
    open_terminal(_("Installing {agent}").format(agent=agent["name"]),
                  f"echo {shlex.quote('$ ' + agent['install'])}\n{agent['install']}\necho\necho {shlex.quote(done)}\n")


def open_terminal(title, script):
    settings = load_config()
    shell = shutil.which(settings["shell"]) or os.environ.get("SHELL") or "/bin/sh"
    # Agents won't remember trust for the whole home directory, so they run here.
    STATE_DIR.mkdir(parents=True, exist_ok=True)
    # Terminals mangle command lines in their own ways (Konsole expands $VARS before
    # passing them on), so the terminal only ever gets "sh <file>" and the real work
    # happens in a script it can't reinterpret. The shell stays open afterwards.
    fd, launcher = tempfile.mkstemp(dir=STATE_DIR, prefix="launch-", suffix=".sh")
    with os.fdopen(fd, "w") as f:
        f.write(f"rm -f {shlex.quote(launcher)}\n{script}exec {shlex.quote(shell)} -i\n")
    argv = terminal_command(settings["terminal"], str(STATE_DIR), title, ["sh", launcher])
    # Started from inside another agent session, these would make the new agent
    # think it's that session's child (Claude Code then stops saving transcripts).
    env = {k: v for k, v in os.environ.items() if k not in SESSION_MARKERS}
    os.execvpe(argv[0], argv, env)


SESSION_MARKERS = {"CLAUDECODE", "CLAUDE_PID", "CLAUDE_EFFORT", "CLAUDE_AGENT_SDK_VERSION", "CLAUDE_CODE_CHILD_SESSION",
                   "CLAUDE_CODE_SESSION_ID", "CLAUDE_CODE_SESSION_ATTENDED", "CLAUDE_CODE_ENTRYPOINT",
                   "CLAUDE_CODE_EXECPATH", "CLAUDE_CODE_MESSAGING_SOCKET", "CLAUDE_CODE_MESSAGING_TOKEN",
                   "CLAUDE_CODE_ENABLE_TASKS", "CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING", "CODEX_SANDBOX",
                   "CODEX_SANDBOX_NETWORK_DISABLED"}


PROMPT = object()

# How each agent opens an interactive session seeded with a prompt, without the
# flags that make it act without asking: diagnosis reads, the user decides.
AGENTS = {
    "claude": {"name": "Claude Code", "command": "claude", "model_flag": "--model", "prompt": ["--", PROMPT],
               "url": "https://code.claude.com", "install": "curl -fsSL https://claude.ai/install.sh | bash"},
    "codex": {"name": "Codex", "command": "codex", "model_flag": "-m", "prompt": ["--", PROMPT],
              "url": "https://github.com/openai/codex", "install": "curl -fsSL https://chatgpt.com/codex/install.sh | sh"},
    "opencode": {"name": "OpenCode", "command": "opencode", "model_flag": "-m", "prompt": ["--prompt", PROMPT],
                 "url": "https://opencode.ai", "install": "curl -fsSL https://opencode.ai/install | bash"},
    "gemini": {"name": "Gemini CLI", "command": "gemini", "model_flag": "-m", "prompt": ["-i", PROMPT],
               "url": "https://github.com/google-gemini/gemini-cli", "install": "npm install -g @google/gemini-cli"},
    "agy": {"name": "Antigravity CLI", "command": "agy", "model_flag": None, "prompt": ["--prompt-interactive", PROMPT],
            "url": "https://antigravity.google", "install": "curl -fsSL https://antigravity.google/cli/install.sh | bash"},
    "copilot": {"name": "GitHub Copilot CLI", "command": "copilot", "model_flag": "--model",
                "prompt": ["--interactive", PROMPT],
                "url": "https://github.com/github/copilot-cli", "install": "curl -fsSL https://gh.io/copilot-install | bash"},
    # A bare prompt naming a subcommand (update, login) would run it, so the agent subcommand is explicit.
    "cursor": {"name": "Cursor CLI", "command": "cursor-agent", "model_flag": "--model", "prompt": ["agent", "--", PROMPT],
               "url": "https://cursor.com/cli", "install": "curl -fsS https://cursor.com/install | bash"},
    "grok": {"name": "Grok CLI", "command": "grok", "model_flag": None, "prompt": ["--", PROMPT],
             "url": "https://x.ai/cli", "install": "curl -fsSL https://x.ai/cli/install.sh | bash"},
    # Nothing leaves the machine (or the user's own server): OpenCode driving a model
    # that Ollama serves. "installed" means the model is ready to answer, not just the binary.
    "ollama": {"name": "Ollama (local AI)", "command": "opencode", "model_flag": "-m", "prompt": ["--prompt", PROMPT],
               "url": "https://ollama.com", "install": f"{shlex.quote(str(Path(sys.argv[0]).absolute()))} local setup"},
}
SKILL_FILE = ROOT / "skill" / "lili-diagnose-crash" / "SKILL.md"
DISTRO_NOTES = SKILL_FILE.parent / "distros"
USER_NOTES = CONFIG_FILE.parent / "skills"


def os_release():
    try:
        text = Path("/etc/os-release").read_text()
    except OSError:
        return {}
    return {k: v.strip('"') for k, _, v in (line.partition("=") for line in text.splitlines()) if v}


def distro():
    info = os_release()
    candidates = [info.get("ID", "")] + info.get("ID_LIKE", "").split()
    for candidate in candidates:
        key = "opensuse" if candidate.startswith("opensuse") else candidate
        # Bazzite, Silverblue and friends update as one image, not package by package.
        if key == "fedora" and Path("/run/ostree-booted").exists():
            key = "fedora-atomic"
        if key and (DISTRO_NOTES / f"{key}.md").is_file():
            return key, info.get("PRETTY_NAME") or info.get("NAME") or key
    return "generic", info.get("PRETTY_NAME") or "Linux"


def virtualization():
    # A VM switched off from outside ends its boot like a freeze; the AI should know.
    try:
        out = subprocess.run(["systemd-detect-virt", "--vm"], capture_output=True, text=True).stdout.strip()
    except OSError:
        return ""
    return "" if out in ("", "none") else out


def notes_path():
    key, _name = distro()
    edited = USER_NOTES / f"{key}.md"
    return edited if edited.is_file() else DISTRO_NOTES / f"{key}.md"


def skill(action):
    key, _name = distro()
    edited = USER_NOTES / f"{key}.md"
    if action == "path":
        print(notes_path())
    elif action == "view":
        # The default notes live in the install; hand out a read-only copy so a
        # "view" can't turn into an accidental edit of the shipped file.
        source = notes_path()
        if source != edited:
            fd, copy = tempfile.mkstemp(prefix=f"lili-{key}-", suffix=".md")
            with os.fdopen(fd, "w") as f:
                f.write(source.read_text())
            os.chmod(copy, 0o444)
            source = copy
        subprocess.Popen(["xdg-open", str(source)], start_new_session=True)
    elif action == "edit":
        if not edited.is_file():
            USER_NOTES.mkdir(parents=True, exist_ok=True)
            edited.write_text((DISTRO_NOTES / f"{key}.md").read_text())
        subprocess.Popen(["xdg-open", str(edited)], start_new_session=True)
    elif action == "reset":
        edited.unlink(missing_ok=True)
    else:
        sys.exit(__doc__.strip())


TERMINALS = {
    "konsole": lambda cwd, title, cmd: ["konsole", "--workdir", cwd, "-p", f"tabtitle={title}", "-e", *cmd],
    "kitty": lambda cwd, title, cmd: ["kitty", "--directory", cwd, "--title", title, *cmd],
    "alacritty": lambda cwd, title, cmd: ["alacritty", "--working-directory", cwd, "--title", title, "-e", *cmd],
    "wezterm": lambda cwd, title, cmd: ["wezterm", "start", "--cwd", cwd, "--", *cmd],
    "foot": lambda cwd, title, cmd: ["foot", f"--working-directory={cwd}", f"--title={title}", *cmd],
    "gnome-terminal": lambda cwd, title, cmd: ["gnome-terminal", f"--working-directory={cwd}", f"--title={title}", "--", *cmd],
}


def which(command):
    # Agent installers drop their binary in ~/.local/bin (OpenCode's in ~/.opencode/bin),
    # which a systemd user service doesn't have on PATH on every distro.
    extra = [str(Path.home() / d) for d in (".local/bin", ".opencode/bin")]
    return shutil.which(command, path=os.pathsep.join([os.environ.get("PATH", ""), *extra]))


def installed_terminals():
    return [t for t in TERMINALS if shutil.which(t)]


def terminal_command(choice, cwd, title, cmd):
    if choice == "auto" or not shutil.which(choice):
        preferred = os.path.basename(os.environ.get("TERMINAL", ""))
        desktop = os.environ.get("XDG_CURRENT_DESKTOP", "")
        order = [preferred, "konsole" if "KDE" in desktop else "gnome-terminal", *TERMINALS]
        choice = next((t for t in order if t in TERMINALS and shutil.which(t)), None)
        if not choice:
            sys.exit(_("No supported terminal found: {terminals}").format(terminals=", ".join(TERMINALS)))
    return TERMINALS[choice](cwd, title, cmd)


DEFAULTS = {"avatar": "logo", "agent": "claude", "terminal": "auto", "shell": "fish",
            "ollama_url": "http://localhost:11434",
            **{f"{a}_model": "default" for a, spec in AGENTS.items() if spec["model_flag"]}}


def load_config():
    try:
        saved = json.loads(CONFIG_FILE.read_text())
    except (OSError, ValueError):
        saved = {}
    return {**DEFAULTS, **{k: v for k, v in saved.items() if k in DEFAULTS and isinstance(v, str)}}


def set_config(key, value):
    if key not in DEFAULTS:
        sys.exit(_("Unknown setting: {key}. Use one of: {keys}").format(key=key, keys=", ".join(DEFAULTS)))
    settings = load_config()
    settings[key] = value
    CONFIG_FILE.parent.mkdir(parents=True, exist_ok=True)
    CONFIG_FILE.write_text(json.dumps(settings, indent=1))
    if key == "avatar":
        point_icon(value)


ICON_DIR = Path(os.environ.get("XDG_DATA_HOME") or Path.home() / ".local/share") / "icons/hicolor/128x128/apps"


def point_icon(avatar):
    # The themed icon follows the chosen avatar, so the taskbar, the widget list
    # and the notifications all show the same Lili.
    name = f"lili-crash-{avatar}.png"
    target = ICON_DIR / name
    if not target.is_file():
        # A package installs the avatars for everyone; the choice stays per user.
        target = next((p for d in data_dirs() if (p := Path(d) / "icons/hicolor/128x128/apps" / name).is_file()), None)
        if target is None:
            return
    ICON_DIR.mkdir(parents=True, exist_ok=True)
    link = ICON_DIR / "lili-crash.png"
    tmp = ICON_DIR / ".lili-crash.png.new"
    tmp.unlink(missing_ok=True)
    tmp.symlink_to(target.name if target.parent == ICON_DIR else target)
    tmp.replace(link)
    ICON_DIR.parent.parent.touch()


# Puts Lili in every system tray, always shown. Plasma saves it with the panel,
# so she comes back on every login without anyone opening her.
TRAY_SCRIPT = """
for (const panel of panels())
  for (const widget of panel.widgets())
    if (widget.type == "org.kde.plasma.systemtray") {
      widget.currentConfigGroup = ["General"];
      for (const key of ["extraItems", "shownItems"]) {
        let items = widget.readConfig(key);
        if (!Array.isArray(items)) items = items ? String(items).split(",") : [];
        if (items.indexOf("lili") < 0) items.push("lili");
        widget.writeConfig(key, items);
      }
    }
"""


def setup():
    """What a package can't do as root: this user's service, tray, skill and window icons."""
    for agent_dir in (Path.home() / ".claude", Path.home() / ".codex"):
        if not agent_dir.is_dir():
            continue
        target = agent_dir / "skills" / "lili-diagnose-crash"
        target.parent.mkdir(exist_ok=True)
        # A real directory at that path would get the link created inside it.
        if target.is_dir() and not target.is_symlink():
            target.rename(target.with_name(f"{target.name}.bak-{datetime.now():%Y%m%d%H%M%S}"))
        target.unlink(missing_ok=True)
        target.symlink_to(SKILL_FILE.parent)
        print(_("skill: linked for {agent}").format(agent=agent_dir.name.lstrip(".")))
    point_icon(load_config()["avatar"])
    run = lambda *cmd: subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode == 0
    run("systemctl", "--user", "daemon-reload")
    if run("systemctl", "--user", "enable", "lili-crash.service") and run("systemctl", "--user", "restart", "lili-crash.service"):
        print(_("service: running, and it starts with every login"))
    else:
        print(_("service: couldn't start it; try: systemctl --user enable --now lili-crash"))
    if shutil.which("kwriteconfig6"):
        # Wayland taskbars pick a window's icon from its owner's .desktop file, and Lili's
        # windows belong to plasmashell or plasmawindowed. This KWin rule claims them.
        rule = ["kwriteconfig6", "--file", "kwinrulesrc", "--group", "lili-crash"]
        for key, value in (("Description", "Lili Crash windows"), ("title", "Lili Crash"), ("titlematch", "2"),
                           ("desktopfile", "lili-crash"), ("desktopfilerule", "2")):
            run(*rule, "--key", key, value)
        rules = subprocess.run(["kreadconfig6", "--file", "kwinrulesrc", "--group", "General", "--key", "rules"],
                               capture_output=True, text=True).stdout.strip()
        if "lili-crash" not in rules.split(","):
            rules = ",".join(filter(None, [rules, "lili-crash"]))
            run("kwriteconfig6", "--file", "kwinrulesrc", "--group", "General", "--key", "rules", rules)
            run("kwriteconfig6", "--file", "kwinrulesrc", "--group", "General", "--key", "count", str(len(rules.split(","))))
        run("dbus-send", "--session", "--type=method_call", "--dest=org.kde.KWin", "/KWin", "org.kde.KWin.reconfigure")
    if "KDE" not in os.environ.get("XDG_CURRENT_DESKTOP", "").split(":"):
        tray_autostart()
    elif shutil.which("qdbus6") and run("qdbus6", "org.kde.plasmashell", "/PlasmaShell",
                                        "org.kde.PlasmaShell.evaluateScript", TRAY_SCRIPT):
        print(_("tray: Lili is next to the clock"))
    else:
        print(_("tray: right-click the system tray, choose Configure System Tray, open Entries and set Lili Crash to Always show"))
    STATE_DIR.mkdir(parents=True, exist_ok=True)
    SETUP_DONE.touch()


# A package can't reach anyone's home folder, so it ships an autostart entry that
# runs the setup at each user's first login; nobody has to open a terminal.
SETUP_DONE = STATE_DIR / "setup-done"


def setup_if_needed():
    if not SETUP_DONE.exists():
        setup()


# Plasma has the panel widget; on every other desktop the tray icon starts with the session.
TRAY_AUTOSTART = """[Desktop Entry]
Type=Application
Name=Lili Crash
Exec={command} tray
Icon=lili-crash
NotShowIn=KDE;
X-GNOME-Autostart-enabled=true
NoDisplay=true
"""


def tray_running():
    return subprocess.run(["pgrep", "-u", str(os.getuid()), "-f", "lili-crash tray$"],
                          stdout=subprocess.DEVNULL).returncode == 0


def tray_autostart():
    # Written even without AppIndicator, so installing it later is enough.
    autostart = Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config") / "autostart" / "lili-crash-tray.desktop"
    autostart.parent.mkdir(parents=True, exist_ok=True)
    autostart.write_text(TRAY_AUTOSTART.format(command=shlex.quote(str(Path(sys.argv[0]).absolute()))))
    if not tray_toolkit():
        print(_("tray: the tray icon needs AppIndicator (gir1.2-ayatanaappindicator3-0.1); notifications work without it"))
        return
    if not tray_running() and (os.environ.get("DISPLAY") or os.environ.get("WAYLAND_DISPLAY")):
        subprocess.Popen([sys.argv[0], "tray"], start_new_session=True,
                         stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    print(_("tray: Lili is in the system tray, and she starts with every login"))


def main(args):
    command, rest = (args[0], args[1:]) if args else ("", [])
    if command == "list" and not rest:
        found = programs()
        for p in found:
            p.pop("crashes")
        print(json.dumps({"programs": found, "pending": sum(p["state"] == "new" for p in found)}, ensure_ascii=False))
    elif command == "config" and not rest:
        key, name = distro()
        print(json.dumps({**load_config(), "terminals": installed_terminals(),
                          "agents": [{"id": a, "name": spec["name"], "models": bool(spec["model_flag"]),
                                      "installed": local_ready(load_config()) if a == "ollama" else bool(which(spec["command"]))}
                                     for a, spec in AGENTS.items()],
                          "distro": {"key": key, "name": name, "edited": (USER_NOTES / f"{key}.md").is_file()}}))
    elif command == "config" and len(rest) == 3 and rest[0] == "set":
        set_config(rest[1], rest[2])
    elif command == "mark" and len(rest) >= 2:
        mark(rest[0], rest[1], " ".join(rest[2:]))
    elif command == "notify" and len(rest) == 1 and (rest[0].isdigit() or is_boot(rest[0]) or is_steam(rest[0]) or is_launch(rest[0])):
        notify(rest[0])
    elif command == "open" and not rest:
        open_window()
    elif command == "tray" and not rest:
        tray()
    elif command == "watch" and not rest:
        watch()
    elif command == "skill" and len(rest) == 1:
        skill(rest[0])
    elif command == "setup" and not rest:
        setup()
    elif command == "setup" and rest == ["--if-needed"]:
        setup_if_needed()
    elif command == "install" and len(rest) == 1:
        install(rest[0])
    elif command == "local" and rest == ["setup"]:
        local_setup()
    elif command == "diagnose" and rest and all(r.isdigit() or is_boot(r) or is_steam(r) or is_launch(r) for r in rest):
        diagnose(rest)
    else:
        sys.exit(__doc__.strip())


if __name__ == "__main__":
    main(sys.argv[1:])
