#!/usr/bin/env python3
"""optmux-lsp — language servers as a symbol source for optmux Find (`C-l`).

Usage:
  optmux-lsp query [--fast] QUERY symbols matching QUERY, one per line, in optmux Find's `FILE LINE DISPLAY` format.
                                  With nothing to show, rows with a FILE of `!install:LANG` (Enter installs it), `!wait`
                                  or `!note` say why. --fast: only what the running servers answer within a second
  optmux-lsp status               which languages were found, and which servers run, wait or are missing
  optmux-lsp install [--yes] [LANG...]  run the install command of each language that has files but no server (asks first)
  optmux-lsp stop                 shut the project's servers down
  optmux-lsp serve ROOT           the hub itself (started by `query` when needed)
(The project is the git repository of the current directory.)

One hub process per project owns that project's language servers, so each keystroke costs one request on a
unix socket, not a server start. The hub looks at the files git tracks, picks the languages with enough of
them, and starts the first installed server of each (see `+lsp` under `+find` in optmux's defaults, which you can
override in your optmux.yaml: `+servers` per language, `+extensions`, `+enabled`, ...). It sends every query as
LSP `workspace/symbol` to all running servers and merges the answers. It exits after OPTMUX_LSP_IDLE seconds
(default 1800) without queries.

The configuration is $OPTMUX_DIR/find.json, which optmux writes at launch from its merged `+find:` section.
"""

import fcntl
import hashlib
import itertools
import json
import os
import shlex
import shutil
import socket
import subprocess
import sys
import tempfile
import threading
import time
from pathlib import Path
from urllib.parse import unquote, urlparse

SYMBOL_KINDS = (
    "file module namespace package class method property field constructor enum interface function variable "
    "constant string number boolean array object key null enummember struct event operator typeparameter"
).split()
IDLE_SECONDS = float(os.environ.get("OPTMUX_LSP_IDLE", "1800"))
MIN_FILES = 3          # a language needs this many tracked files ...
MIN_SHARE = 0.05       # ... and this share of all the files whose language we know, to get a server
BOOT_TIMEOUT = 90      # seconds a server may take to answer `initialize`
QUERY_TIMEOUT = 4      # seconds a server may take to answer one query
MAX_ROWS = 200
RESCAN_MISSING = float(os.environ.get("OPTMUX_LSP_RESCAN", "3"))  # seconds between looking for servers installed since
RECHECK_NOT_SCRIPT = 24 * 3600  # seconds a file found not to be a script is left alone (unless it changed)
RESCAN_FILES = 60      # seconds between looking for languages the project grew into
RESTART_AFTER = float(os.environ.get("OPTMUX_LSP_RESTART", "30"))  # seconds before a crashed server is started again
# LSP languageId by file extension, for the one file opened on start (else the language's own name)
LANGUAGE_IDS = {"c": "c", "h": "c", "cc": "cpp", "cpp": "cpp", "cxx": "cpp", "hpp": "cpp", "hh": "cpp", "m": "objective-c",
                "mm": "objective-cpp", "ts": "typescript", "mts": "typescript", "cts": "typescript",
                "tsx": "typescriptreact", "js": "javascript", "mjs": "javascript", "cjs": "javascript",
                "jsx": "javascriptreact", "py": "python", "pyi": "python", "go": "go", "rs": "rust", "lua": "lua",
                "sh": "shellscript", "bash": "shellscript"}


# ---- configuration -------------------------------------------------------------------------------------

def config_path():
    return Path(os.environ["OPTMUX_FIND_CONFIG"]) if os.environ.get("OPTMUX_FIND_CONFIG") \
        else Path(os.environ.get("OPTMUX_DIR", ""), "find.json")


def load_config():
    """{language: settings} from find.json's `lsp` (disabled languages dropped)."""
    try:
        lsp = json.loads(config_path().read_text()).get("lsp") or {}
    except (OSError, ValueError, AttributeError):
        return {}
    return {lang: cfg for lang, cfg in lsp.items() if isinstance(cfg, dict) and cfg.get("enabled", True)}


def servers_of(cfg):
    """The language's servers in order of preference, as [{command, install}]. `command` alone is a shorthand."""
    servers = [s for s in cfg.get("servers") or [] if isinstance(s, dict) and s.get("command")]
    if cfg.get("command"):
        servers.insert(0, {"command": cfg["command"], "install": cfg.get("install", "")})
    return servers


def search_path():
    """Homebrew's dirs first, as in a git hook (a tmux popup's PATH often lacks them), and after the PATH the
    places `go install`, `uv tool`, pipx and cargo put what they install, which a login shell would add."""
    home = Path.home()
    gobin = os.environ.get("GOBIN") or str(Path(os.environ.get("GOPATH") or home / "go", "bin"))
    return os.pathsep.join(d for d in ("/opt/homebrew/bin", "/usr/local/bin", os.environ.get("PATH", ""), gobin,
                                       str(home / ".local/bin"), str(home / ".cargo/bin")) if d)


def installed_server(cfg):
    """(argv, server) of the first of the language's servers that is installed, else None."""
    for server in servers_of(cfg):
        argv = shlex.split(server["command"]) if isinstance(server["command"], str) else list(server["command"])
        exe = shutil.which(argv[0], path=search_path()) if argv else None
        if exe:
            return [exe, *argv[1:]], server
    return None


def sh_first(server):
    command = server["command"]
    return (shlex.split(command) if isinstance(command, str) else list(command))[0]


def install_options(server):
    """A server's install commands: `install` is one command, or a list of alternatives (brew, uv, npm, ...)."""
    install = server.get("install") or []
    return [install] if isinstance(install, str) else [c for c in install if isinstance(c, str)]


def best_install(cfg):
    """The install command to offer for a language: the first one, of its servers in order of preference, whose
    installer (brew, uv, npm, ...) is on the PATH. "" when none could run here."""
    for server in servers_of(cfg):
        for cmd in install_options(server):
            if shlex.split(cmd) and shutil.which(shlex.split(cmd)[0], path=search_path()):
                return cmd
    return ""


def brew_link_fallback(how):
    """`brew link PKG...` for a `brew install PKG...`, for a package brew calls "already installed, just not
    linked" (it exits 0 and puts nothing on the PATH). None for any other command."""
    words = shlex.split(how)
    if words[:2] != ["brew", "install"]:
        return None
    packages = [w for w in words[2:] if not w.startswith("-")]
    return ["brew", "link", *packages] if packages else None


def first_install(cfg):
    """The preferred install command, runnable here or not (to tell the user what to do by hand)."""
    return next((cmd for server in servers_of(cfg) for cmd in install_options(server)), "")


def tracked_files(root):
    out = subprocess.run(["git", "ls-files", "-z"], cwd=root, capture_output=True, text=True).stdout
    return [f for f in out.split("\0") if f]


# Scripts have no extension: the interpreter on the first line says what they are, as (language, languageId)
SHEBANG_LANGUAGES = {"python": ("python", "python"), "python3": ("python", "python"), "node": ("typescript", "javascript"),
                     "nodejs": ("typescript", "javascript"), "bash": ("bash", "shellscript"), "sh": ("bash", "shellscript"),
                     "zsh": ("bash", "shellscript"), "lua": ("lua", "lua")}
MAX_SCRIPTS = 50  # per language: each one is opened in the server


def script_language(root, name):
    """(language, languageId) of an extensionless file by its `#!` line (`#!/usr/bin/env python3`, `#!/bin/bash`), or None."""
    try:
        with open(Path(root, name), "rb") as f:
            first = f.readline(200)
    except OSError:
        return None
    if not first.startswith(b"#!"):
        return None
    words = first[2:].decode(errors="replace").split()
    if words and os.path.basename(words[0]) == "env":
        words = [w for w in words[1:] if not w.startswith("-")]
    interpreter = os.path.basename(words[0]).rstrip("0123456789.") if words else ""
    return SHEBANG_LANGUAGES.get(os.path.basename(words[0]) if words else "") or SHEBANG_LANGUAGES.get(interpreter)


def find_scripts(root, files, config, not_scripts=None):
    """{language: [(file, languageId)]} for the tracked files with no extension that a `#!` line says are of a
    language of the project (up to MAX_SCRIPTS each): servers only look at files that have the language's
    extension, so these are told about one by one (see LanguageServer.open_scripts). `not_scripts` ({file: (mtime,
    when checked)}, kept by the caller) remembers the files that were no script, so a rescan does not open them
    again for a day, unless the file changed (a stat is all it costs)."""
    found = {}
    now = time.time()
    for f in files:
        if "." in os.path.basename(f):
            continue
        try:
            mtime = os.stat(Path(root, f)).st_mtime_ns
        except OSError:
            continue
        if not_scripts is not None and f in not_scripts and not_scripts[f][0] == mtime and now - not_scripts[f][1] < RECHECK_NOT_SCRIPT:
            continue
        kind = script_language(root, f)
        if not_scripts is not None:
            if kind:
                not_scripts.pop(f, None)
            else:
                not_scripts[f] = (mtime, now)
        if kind and kind[0] in config and len(found.setdefault(kind[0], [])) < MAX_SCRIPTS:
            found[kind[0]].append((f, kind[1]))
    return found


def detect_languages(files, config):
    """{language: [files]} for the languages with enough of the project (see MIN_FILES and MIN_SHARE)."""
    by_ext = {}
    for lang, cfg in config.items():
        for ext in cfg.get("extensions") or []:
            by_ext[ext.lstrip(".").lower()] = lang
    found = {}
    for f in files:
        lang = by_ext.get(f.rsplit(".", 1)[-1].lower()) if "." in f else None
        if lang:
            found.setdefault(lang, []).append(f)
    total = sum(map(len, found.values()))
    return {lang: fs for lang, fs in sorted(found.items(), key=lambda kv: -len(kv[1]))
            if len(fs) >= MIN_FILES and len(fs) >= MIN_SHARE * total}


def state_dir():
    base = os.environ.get("OPTMUX_DIR")
    d = Path(base, "find") if base else Path(tempfile.gettempdir(), f"optmux-lsp-{os.getuid()}")
    d.mkdir(parents=True, exist_ok=True)
    return d


PROTOCOL = 4  # what rows look like; a hub left running by an older optmux is replaced, not spoken to


def socket_path(root):
    """Short, because unix socket paths are limited to about 100 bytes; per user and project."""
    return str(Path(tempfile.gettempdir(), f"optmux-lsp-{os.getuid()}-{hashlib.sha1(root.encode()).hexdigest()[:10]}.sock"))


# ---- one language server -------------------------------------------------------------------------------

class LanguageServer:
    def __init__(self, lang, cfg, argv, root, files, log, scripts=()):
        self.lang, self.cfg, self.root, self.files, self.scripts = lang, cfg, root, files, list(scripts)
        self.name = f"{lang}: {os.path.basename(argv[0])}"  # what rows say they come from
        self.ids, self.pending, self.ready, self.failed = itertools.count(1), {}, False, None
        self.lock = threading.Lock()
        self.proc = subprocess.Popen(argv, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=log, cwd=root,
                                     env={**os.environ, "PATH": search_path()})  # the server's own `env node` needs it too
        threading.Thread(target=self.read_loop, daemon=True).start()
        threading.Thread(target=self.boot, daemon=True).start()

    # framing: `Content-Length: N\r\n\r\n` and N bytes of JSON
    def send(self, message):
        body = json.dumps(message).encode()
        with self.lock:
            self.proc.stdin.write(b"Content-Length: %d\r\n\r\n" % len(body) + body)
            self.proc.stdin.flush()

    def read_message(self):
        length = None
        while True:
            line = self.proc.stdout.readline()
            if not line:
                return None
            line = line.strip()
            if not line:
                break
            if line.lower().startswith(b"content-length:"):
                length = int(line.split(b":", 1)[1])
        return json.loads(self.proc.stdout.read(length)) if length is not None else {}

    def read_loop(self):
        try:
            while (msg := self.read_message()) is not None:
                if "method" in msg and "id" in msg:  # the server asks us something: answer so it does not wait
                    items = (msg.get("params") or {}).get("items") or []
                    result = [None] * len(items) if msg["method"] == "workspace/configuration" else None
                    self.send({"jsonrpc": "2.0", "id": msg["id"], "result": result})
                elif "id" in msg and msg["id"] in self.pending:
                    waiter = self.pending[msg["id"]]
                    waiter[1] = msg
                    waiter[0].set()
        except (OSError, ValueError):
            pass
        finally:
            self.ready = False
            self.failed = self.failed or "exited"
            for waiter in list(self.pending.values()):
                waiter[0].set()

    def request(self, method, params, timeout):
        rid, waiter = next(self.ids), [threading.Event(), None]
        self.pending[rid] = waiter
        try:
            self.send({"jsonrpc": "2.0", "id": rid, "method": method, "params": params})
            if not waiter[0].wait(timeout) or waiter[1] is None:
                raise TimeoutError(method)
            return waiter[1].get("result") if "error" not in waiter[1] else None
        finally:
            self.pending.pop(rid, None)

    def boot(self):
        uri = Path(self.root).as_uri()
        try:
            self.request("initialize", {
                "processId": os.getpid(), "rootUri": uri, "rootPath": self.root, "clientInfo": {"name": "optmux"},
                "workspaceFolders": [{"uri": uri, "name": Path(self.root).name}],
                "capabilities": {
                    "workspace": {"workspaceFolders": True, "configuration": True,
                                  "symbol": {"symbolKind": {"valueSet": list(range(1, 27))}}},
                    "window": {"workDoneProgress": True},
                },
            }, BOOT_TIMEOUT)
            self.send({"jsonrpc": "2.0", "method": "initialized", "params": {}})
            if self.cfg.get("open_first_file"):  # some servers pick their project from an open file
                self.open_a_file()
            self.open_scripts()
            self.ready = True
        except (OSError, TimeoutError, ValueError) as e:
            self.failed = f"did not start ({e})"

    def open_a_file(self):
        """Tell the server about one file (the first tracked one that is there): a failure here is not a failed boot."""
        for name in self.files:
            path = Path(self.root, name)
            try:
                text = path.read_text(errors="replace")
            except OSError:
                continue
            ext = name.rsplit(".", 1)[-1].lower()
            self.send({"jsonrpc": "2.0", "method": "textDocument/didOpen", "params": {"textDocument": {
                "uri": path.as_uri(), "languageId": LANGUAGE_IDS.get(ext) or self.cfg.get("language_id", self.lang),
                "version": 1, "text": text}}})
            return

    def open_scripts(self):
        """Tell the server about the project's scripts (files with a `#!` line and no extension): it would not know
        they are there. Opened, they are part of what it knows and answers symbol queries from."""
        for name, language_id in self.scripts:
            try:
                text = Path(self.root, name).read_text(errors="replace")
            except OSError:
                continue
            self.send({"jsonrpc": "2.0", "method": "textDocument/didOpen", "params": {"textDocument": {
                "uri": Path(self.root, name).as_uri(), "languageId": language_id, "version": 1, "text": text}}})

    def alive(self):
        return self.failed is None and self.proc.poll() is None

    def symbols(self, query, timeout=QUERY_TIMEOUT):
        return self.request("workspace/symbol", {"query": query}, timeout) or []

    def stop(self):
        try:
            if self.ready:
                self.request("shutdown", None, 2)
                self.send({"jsonrpc": "2.0", "method": "exit"})
        except (OSError, TimeoutError):
            pass
        try:
            self.proc.wait(2)
        except subprocess.TimeoutExpired:
            self.proc.kill()


def short_name(name):
    """A symbol's name without the package that qualifies it: gopls says `github.com/org/repo/pkg/gui.Gui.layout`,
    where `Gui.layout` is the name (the file says where it is)."""
    head, slash, tail = name.rpartition("/")
    return tail.partition(".")[2] or tail if slash and "." in tail else name


def rows_of(symbols, root, source=""):
    """optmux Find rows (`FILE \\t LINE \\t NAME ^_ KIND ^_ CONTAINER ^_ SOURCE`, with ^_ the unit separator, \\x1f) for LSP
    SymbolInformation / WorkspaceSymbol items; SOURCE says which server answered."""
    for sym in symbols:
        loc = sym.get("location") or {}
        if not loc.get("uri"):
            continue
        path = unquote(urlparse(loc["uri"]).path)
        try:
            path = str(Path(path).relative_to(root))
        except ValueError:
            pass  # outside the project (a library): keep the absolute path
        line = ((loc.get("range") or {}).get("start") or {}).get("line", 0) + 1
        kind = SYMBOL_KINDS[sym["kind"] - 1] if isinstance(sym.get("kind"), int) and 0 < sym["kind"] <= 26 else ""
        yield f"{path}\t{line}\t{short_name(sym.get('name', '')) if source.startswith('go:') else sym.get('name', '')}\x1f{kind}\x1f{sym.get('containerName') or ''}\x1f{source}"


# ---- the hub: one per project --------------------------------------------------------------------------

class Hub:
    def __init__(self, root):
        self.root, self.last_used, self.servers, self.missing = root, time.time(), {}, {}
        self.crashed = {}  # language -> (when, why) of a server that died; tried again after RESTART_AFTER
        self.lock = threading.RLock()  # queries come in on several threads
        self.stopping = False
        self.config = load_config()
        self.log = open(state_dir() / "lsp.log", "ab")
        self.lang_files, self.scripts, self.not_scripts = {}, {}, {}
        self.scanned_files = self.scanned_missing = 0.0
        self.rescan()

    def start(self, lang):
        """Start the first installed server of `lang`, or note that there is none (to look again later)."""
        cfg = self.config[lang]
        found = installed_server(cfg)
        if not found:
            self.missing[lang] = {"install": best_install(cfg), "hint": first_install(cfg), "why": "no server installed"}
            return
        argv, server = found
        try:
            self.servers[lang] = LanguageServer(lang, cfg, argv, self.root, self.lang_files.get(lang, []), self.log,
                                                self.scripts.get(lang, []))
            self.missing.pop(lang, None)
        except OSError as e:
            self.missing[lang] = {"install": best_install(cfg), "hint": first_install(cfg), "why": str(e)}

    def rescan(self):
        """Which languages the project has, and servers for them: at start, then again as things change, so a
        server installed (or a language added) while the hub runs is picked up without restarting it, and one
        that died is started again after a while."""
        with self.lock:
            now = time.time()
            for lang, server in list(self.servers.items()):  # the dead: out, then back after RESTART_AFTER
                if not server.alive():
                    self.crashed[lang] = (now, server.failed or "exited")
                    del self.servers[lang]
                    server.stop()
            for lang, (when, _) in list(self.crashed.items()):
                if now - when >= RESTART_AFTER and lang in self.lang_files:
                    del self.crashed[lang]
                    self.start(lang)
            if now - self.scanned_files >= RESCAN_FILES or not self.scanned_files:
                self.scanned_files = self.scanned_missing = now
                files = tracked_files(self.root)
                self.lang_files = detect_languages(files, self.config)
                self.scripts = find_scripts(self.root, files, {l: self.config[l] for l in self.lang_files}, self.not_scripts)
                for lang in list(self.missing):  # no longer a language of this project
                    if lang not in self.lang_files:
                        del self.missing[lang]
                for lang in self.lang_files:
                    if lang not in self.servers and lang not in self.crashed:
                        self.start(lang)
            elif self.missing and now - self.scanned_missing >= RESCAN_MISSING:
                self.scanned_missing = now
                for lang in list(self.missing):
                    self.start(lang)

    def status(self):
        with self.lock:
            out = {lang: {"state": "ready" if s.ready else s.failed or "starting"} for lang, s in self.servers.items()}
            out.update({lang: {"state": why} for lang, (_, why) in self.crashed.items()})
            out.update({lang: {"state": "missing", **info} for lang, info in self.missing.items()})
        return out

    def query(self, query, timeout=QUERY_TIMEOUT):
        self.rescan()
        rows, answers = [], {}

        def ask(lang, server):
            try:
                answers[lang] = list(rows_of(server.symbols(query, timeout), self.root, server.name))
            except (OSError, TimeoutError):
                answers[lang] = []
        with self.lock:
            servers = list(self.servers.items())
        threads = [threading.Thread(target=ask, args=(l, s)) for l, s in servers if s.ready]
        for t in threads:
            t.start()
        for t in threads:
            t.join()
        for lang, _ in servers:  # in the order of how much of the project each language is
            rows.extend(answers.get(lang, []))
        return rows[:MAX_ROWS]

    def handle(self, request):
        self.last_used = time.time()
        if request.get("op") == "query":
            return {"rows": self.query(request.get("q", ""), float(request.get("timeout") or QUERY_TIMEOUT)),
                    "status": self.status(), "protocol": PROTOCOL}
        if request.get("op") == "stop":
            self.stopping = True
        return {"status": self.status(), "protocol": PROTOCOL}

    def shutdown(self):
        with self.lock:
            servers, self.servers = list(self.servers.values()), {}
        for server in servers:
            server.stop()


def serve(root):
    path = socket_path(root)
    lock = open(path + ".lock", "w")  # held while this hub lives: one hub per project, however many start at once
    try:
        fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except OSError:
        return 0
    Path(path).unlink(missing_ok=True)  # a dead hub's leftover; we hold the lock, so nobody else's
    listener = socket.socket(socket.AF_UNIX)
    listener.bind(path)
    os.chmod(path, 0o600)
    listener.listen(8)
    listener.settimeout(5)
    hub = Hub(root)

    def client(conn):
        with conn:
            try:
                data = b""
                while not data.endswith(b"\n"):
                    chunk = conn.recv(65536)
                    if not chunk:
                        return
                    data += chunk
                conn.sendall(json.dumps(hub.handle(json.loads(data))).encode() + b"\n")
            except (OSError, ValueError):
                pass
        if hub.stopping:  # go at once: the next query must find no hub, and start a fresh one
            Path(path).unlink(missing_ok=True)
            listener.close()
    try:
        while not hub.stopping and time.time() - hub.last_used < IDLE_SECONDS:
            try:
                conn, _ = listener.accept()
            except socket.timeout:
                continue
            except OSError:
                break
            threading.Thread(target=client, args=(conn,), daemon=True).start()
    finally:
        listener.close()
        Path(path).unlink(missing_ok=True)
        hub.shutdown()
    return 0


# ---- the client ----------------------------------------------------------------------------------------

def exchange(path, request, timeout):
    with socket.socket(socket.AF_UNIX) as conn:
        conn.settimeout(timeout)
        conn.connect(path)
        conn.sendall(json.dumps(request).encode() + b"\n")
        data = b""
        while not data.endswith(b"\n"):
            chunk = conn.recv(65536)
            if not chunk:
                break
            data += chunk
        return json.loads(data)


def retire_hub(path):
    """Stop the hub at `path` (one from an older optmux) and wait until it is gone."""
    try:
        exchange(path, {"op": "stop"}, 3)
    except (OSError, ValueError):
        pass
    deadline = time.time() + 3
    while time.time() < deadline:
        try:
            exchange(path, {"op": "status"}, 1)
        except (OSError, ValueError):
            return
        time.sleep(0.1)


def ask_hub(root, request, start=True, timeout=12):
    """The hub's answer, starting the hub first if there is none. None if it cannot be reached."""
    path = socket_path(root)
    try:
        answer = exchange(path, request, timeout)
        if answer.get("protocol") == PROTOCOL or request.get("op") == "stop":  # (an old hub is told to stop, too)
            return answer
        if not start:
            return None  # an old hub's rows are not ours to read; the next start replaces it
        retire_hub(path)
    except (OSError, ValueError):
        if not start:
            return None
    subprocess.Popen([os.path.abspath(sys.argv[0]), "serve", root], start_new_session=True,
                     stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=open(state_dir() / "lsp.log", "ab"))
    deadline = time.time() + 5
    while time.time() < deadline:  # it is up when it accepts, not when its socket file exists (a dead hub leaves one)
        try:
            return exchange(path, request, timeout)
        except (OSError, ValueError):
            time.sleep(0.05)
    return None


def hint_rows(status):
    """Rows that say why there may be nothing. Their FILE is a marker, not a path: `!install:LANG` (Enter runs the
    install command), `!wait` (servers still starting), `!note`. optmux Find shows them with an icon of their own."""
    for lang, info in status.items():
        if info["state"] == "missing":
            if info.get("install"):
                yield f"!install:{lang}\t0\t{lang}: no language server installed.  Enter runs: {info['install']}"
            elif info.get("hint"):
                yield (f"!note\t0\t{lang}: no language server installed, and none of the installers is here.  "
                       f"By hand: {info['hint']}")
            else:
                yield f"!note\t0\t{lang}: no language server installed (see +lsp under +find in your optmux config)"
        elif info["state"] == "starting":
            yield f"!wait\t0\t{lang}: language server starting, try again in a moment"
        elif info["state"] != "ready":
            yield f"!note\t0\t{lang}: language server {info['state']}"


def project_root():
    top = subprocess.run(["git", "rev-parse", "--show-toplevel"], capture_output=True, text=True).stdout.strip()
    return os.path.realpath(top or os.getcwd())


def main(argv):
    cmd, rest = (argv[1] if len(argv) > 1 else ""), argv[2:]
    if cmd == "serve" and rest:
        return serve(os.path.realpath(rest[0]))
    if cmd == "query":
        fast = rest[:1] == ["--fast"]
        query = " ".join(rest[1:] if fast else rest)
        if not query.strip():
            return 0
        if not load_config():
            if not fast:
                print(f"!note\t0\tno language server configuration ({config_path()}): restart optmux, which writes it")
            return 0
        if fast:  # for omni: only a hub that is already up, and answers within a second; never wait, never start one
            answer = ask_hub(project_root(), {"op": "query", "q": query, "timeout": 0.8}, start=False, timeout=2)
            for row in (answer or {}).get("rows", []):
                print(row)
            return 0
        answer = ask_hub(project_root(), {"op": "query", "q": query})
        if answer is None:
            print("!note\t0\tlanguage server hub did not start (see lsp.log in the project's optmux find directory)")
            return 0
        for row in answer["rows"]:
            print(row)
        if not answer["rows"]:
            for row in hint_rows(answer["status"]):
                print(row)
        return 0
    if cmd == "status":
        answer = ask_hub(project_root(), {"op": "status"})
        print(json.dumps(answer["status"] if answer else {}, indent=2))
        return 0
    if cmd == "stop":
        ask_hub(project_root(), {"op": "stop"}, start=False)
        return 0
    if cmd == "install":
        yes = "--yes" in rest
        langs = [a for a in rest if a != "--yes"]
        root, config = project_root(), load_config()
        for lang in langs or list(detect_languages(tracked_files(root), config)):
            cfg = config.get(lang)
            if not cfg or installed_server(cfg):
                continue
            how = best_install(cfg)
            if not how:
                print(f"{lang}: no installer here for it. By hand: {first_install(cfg) or 'set `+install:` for its servers under +find: +lsp:'}")
            elif yes or input(f"{lang}: run `{how}`? [y/N] ").strip().lower() == "y":
                print(f"$ {how}", flush=True)
                status = subprocess.run(how, shell=True, env={**os.environ, "PATH": search_path()}).returncode
                if status == 0 and not installed_server(cfg) and (link := brew_link_fallback(how)):
                    print(f"$ {shlex.join(link)}", flush=True)  # installed but not linked, perhaps
                    status = subprocess.run(link, env={**os.environ, "PATH": search_path()}).returncode
                if status != 0:
                    print(f"{lang}: failed (exit {status})")
                elif installed_server(cfg):
                    print(f"{lang}: installed; optmux notices within a few seconds")
                else:
                    print(f"{lang}: the command succeeded, but none of {', '.join(sorted({sh_first(s) for s in servers_of(cfg)}))}"
                          f" is on the PATH optmux searches ({search_path()}). Add its directory to your PATH.")
        return 0
    print(__doc__)
    return 2


if __name__ == "__main__":
    sys.exit(main(sys.argv))
