"""Plan + preflight for ``hermes gateway migrate --backends --apply --dry-run``: which old backend would
move, to which address, what would be copied, and every reason it cannot happen. Changes nothing.

The old backend (``hermes dashboard`` / ``hermes serve``) is found by the report's own detection
(:func:`hermes_cli.gateway_migrate_backends.collect_backends`); the target address is checked by the
gateway's own ``webapp.host`` validation (``gateway.webapp_listener``), so a specific-IP bind starts
working the day the gateway accepts one, without a change here.
"""

from __future__ import annotations

import ipaddress
import os
import re
import shlex
from dataclasses import dataclass, field
from typing import Optional

from hermes_cli import gateway_migrate_backends_timeouts as _timeouts
from hermes_cli.gateway_migrate_backends import BackendItem

EXIT_OK, EXIT_USAGE, EXIT_BLOCKED, EXIT_UNSUPPORTED = 0, 2, 3, 6
#: The steps of a migration run, in order: the plan's ``steps`` use these names.
APPLY_STEPS = ("preflight", "manifest", "webapp_bundle", "write_config", "gateway_service", "stop_old_backend",
               "start_gateway", "verify")
_NEVER_TOUCHED = frozenset({"desktop-ssh", "desktop-local"})
_AUTH_PREFIX = "HERMES_DASHBOARD_"
_SECRET_KEY = "HERMES_DASHBOARD_BASIC_AUTH_SECRET"
# The HERMES_DASHBOARD_* names the bundled sign-in providers read when they register: the ``_settings`` of
# plugins/dashboard_auth/{basic,self_hosted,nous,drain,session_token} (basic's secret via ``_resolve_secret``).
_SIGN_IN_KEYS = frozenset({
    "HERMES_DASHBOARD_BASIC_AUTH_USERNAME", "HERMES_DASHBOARD_BASIC_AUTH_PASSWORD",
    "HERMES_DASHBOARD_BASIC_AUTH_PASSWORD_HASH", "HERMES_DASHBOARD_BASIC_AUTH_SECRET",
    "HERMES_DASHBOARD_BASIC_AUTH_TTL_SECONDS", "HERMES_DASHBOARD_OAUTH_CLIENT_ID", "HERMES_DASHBOARD_PORTAL_URL",
    "HERMES_DASHBOARD_OIDC_ISSUER", "HERMES_DASHBOARD_OIDC_CLIENT_ID", "HERMES_DASHBOARD_OIDC_SCOPES",
    "HERMES_DASHBOARD_OIDC_CLIENT_SECRET", "HERMES_DASHBOARD_DRAIN_SECRET", "HERMES_DASHBOARD_SESSION_TOKEN",
})

# Supervisors this command cannot drive itself: what the operator does instead.
_UNSUPPORTED = {
    "nix-systemd": "The unit is generated by Nix and read-only. In your Nix configuration disable the "
                   "hermes backend service, set webapp.enabled/host/port (below) in the Hermes settings, "
                   "enable the gateway service, then rebuild (nixos-rebuild / home-manager switch).",
    "nix-launchd": "The plist is generated by Nix (Home Manager) and read-only. Disable the backend agent in "
                   "your Nix configuration, set webapp.enabled/host/port (below), enable the gateway agent, "
                   "then run home-manager switch.",
    "s6": "The backend is an s6 slot declared by the container image. Set webapp.enabled/host/port (below) in "
          "the container's Hermes home, remove the dashboard service from the image/compose definition and "
          "restart the container so its gateway slot serves the address.",
    "container": "The backend runs in a container (Compose sidecar or docker run). Set webapp.enabled/host/port "
                 "(below) in the mounted Hermes home, drop the dashboard service from the Compose file, publish "
                 "the same port on the gateway container, then `docker compose up -d`.",
    "systemd-system": "The backend is a systemd SYSTEM unit: this command changes no system unit, and "
                      "hermes cannot run as root on a per-user install. Run the steps below as yourself; only "
                      "the one `sudo systemctl` line needs root.",
    "launchd-system": "The backend is a system-wide launchd LaunchDaemon: this command changes no system "
                      "daemon, and hermes cannot run as root on a per-user install. Run the steps below as "
                      "yourself; only the one `sudo launchctl` line needs root.",
    "windows": "Automatic migration is not available on Windows. Run the steps below in PowerShell or Command "
               "Prompt, one line at a time; `hermes gateway install` asks how to start the gateway.",
    "unknown": "Its supervisor could not be identified, so it cannot be stopped safely. Stop it yourself, "
               "then run the steps below.",
    "no-service": "The gateway cannot be installed as a service on this host (no systemd user manager or "
                  "launchd). Run the steps below; the last one runs the gateway in the foreground, so start it "
                  "from the supervisor you use on this host (it must restart it on exit and at boot).",
    "unknown-address": "The old backend's command line could not be read, so the address it serves is unknown. "
                       "Find it (the unit's ExecStart or the process's arguments), then run the steps below "
                       "with that address.",
}


@dataclass
class BackendPlan:
    home: str
    candidates: list[BackendItem] = field(default_factory=list)
    item: Optional[BackendItem] = None
    rec: dict = field(default_factory=dict)  # the old backend: supervisor, unit, pid, argv, state
    # None until known: an address that could not be read is never shown as a default one.
    old_host: Optional[str] = None
    old_port: Optional[int] = None
    new_host: Optional[str] = None
    new_port: Optional[int] = None
    keep_webapp: bool = False
    no_service: bool = False
    powershell: bool = False  # Windows: commands in messages are typed in PowerShell
    carry: dict[str, str] = field(default_factory=dict)  # VALUES: never printed; only the names are shown
    old_argv: list[str] = field(default_factory=list)  # the exact argv (in memory only; ``rec`` has it redacted)
    generate_secret: bool = False
    public_url: Optional[str] = None
    auth_before: Optional[dict] = None
    gateway: dict = field(default_factory=dict)
    linger: Optional[bool] = None
    bundle_missing: Optional[str] = None
    running_turns: Optional[int] = None  # None: the old backend's activity has not been read or cannot be read
    turns_unknown: str = ""  # why running_turns is None, for the blocker text (not in the JSON)
    blockers: list[str] = field(default_factory=list)
    forceable: list[str] = field(default_factory=list)  # the blockers --force-interrupt clears (each in blockers)
    takes_over: list[str] = field(default_factory=list)  # what the move stops or replaces besides the old backend
    stray_gateway: Optional[dict] = None  # with --force-interrupt: a gateway outside its service, stopped too
    legacy_units: list[dict] = field(default_factory=list)  # pre-rename hermes.service units the move replaces
    unsupported: list[tuple[Optional[BackendItem], str, list[str]]] = field(default_factory=list)
    notices: list[str] = field(default_factory=list)

    @property
    def nothing_to_do(self) -> bool:
        return not self.candidates and not self.unsupported and not self.blockers

    @property
    def old_probe_host(self) -> str:
        """Where the OLD backend answers: the address it is bound to (a wildcard bind is dialed on
        loopback). Never assume 127.0.0.1: a backend bound to one IP answers only there."""
        return probe_host(self.old_host)

    @property
    def verify_hosts(self) -> list[str]:
        """Every address the gateway must answer on afterwards: the bind itself (a wildcard is dialed
        on loopback) plus, for one specific IP, the loopback companion the listener also binds."""
        from gateway.webapp_listener import loopback_companion
        first = probe_host(self.new_host)
        companion = loopback_companion(self.new_host)
        return [first] + ([companion] if companion and companion != first else [])

    def config_writes(self) -> dict:
        values: dict = {}
        if not self.keep_webapp:
            values.update({"webapp.enabled": True, "webapp.host": self.new_host, "webapp.port": self.new_port})
        if self.public_url:
            values["webapp.public_url"] = self.public_url
        return values

    def step_titles(self) -> list[dict]:
        """The steps a migration runs, in order, each with its name and a one-line title."""
        manual = self.rec.get("supervisor") == "manual"
        titles = {
            "preflight": "check that the move can run (nothing changed yet)",
            "manifest": "record the current state in backend_migration.json (backups of config.yaml and .env)",
            "webapp_bundle": "build the Webapp bundle" if self.bundle_missing else "check the Webapp bundle (built)",
            "write_config": "write .env and webapp.* (" + ", ".join(self.config_writes()) + ")",
            "gateway_service": "make sure the gateway runs as a user service" + "".join(
                f" (replacing {u['unit']}; a copy is kept for --restore)" for u in self.legacy_units),
            "stop_old_backend": "stop the old backend" + ("" if manual else " and disable it (its unit file is kept)")
                                + (", then the gateway running outside its service" if self.stray_gateway else ""),
            "start_gateway": "start or restart the gateway",
            "verify": "verify " + " and ".join(format_address(h, self.new_port) for h in self.verify_hosts)
                      + f": /api/status 200 from the gateway and the Webapp page served, within {int(_timeouts.VERIFY_SECONDS)} s",
        }
        return [{"name": n, "title": titles[n]} for n in APPLY_STEPS]

    def exit_code(self) -> int:
        if self.blockers:  # a by-hand move with a blocker prints no steps, so it is blocked, not manual
            return EXIT_BLOCKED
        return EXIT_UNSUPPORTED if self.unsupported else EXIT_OK

    @property
    def shows_steps(self) -> bool:
        """The automatic move's steps are shown only for a move that could run: none while anything blocks
        it, and none when the move is by hand (its own steps are under ``unsupported``)."""
        return bool(self.rec) and self.new_host is not None and not self.blockers and not self.unsupported

    def to_dict(self) -> dict:
        return {
            "home": self.home, "old_backend": self.rec or None,
            "old_address": format_address(self.old_host, self.old_port) if self.old_host is not None else None,
            "new_address": format_address(self.new_host, self.new_port) if self.new_host is not None else None,
            "keep_webapp_address": self.keep_webapp,
            "copy_env_keys": sorted(self.carry), "generate_secret": self.generate_secret,
            "public_url": self.public_url, "auth_before": self.auth_before, "gateway": self.gateway,
            "linger": self.linger, "webapp_bundle_missing": self.bundle_missing,
            "running_turns": self.running_turns, "blockers": list(self.blockers),
            "forceable_blockers": list(self.forceable), "takes_over": list(self.takes_over),
            "unsupported": [{"supervisor": i.supervisor if i else None, "unit": i.unit if i else None,
                             "pid": i.pid if i else None, "instructions": t, "steps": list(s)}
                            for i, t, s in self.unsupported],
            "notices": list(self.notices), "nothing_to_do": self.nothing_to_do,
            "steps": self.step_titles() if self.shows_steps else [],
        }


def probe_host(bind: str) -> str:
    """The address to dial for a listener bound to *bind*: a wildcard or ``localhost`` on loopback,
    anything else (a loopback or one specific IP) on itself."""
    if bind in ("0.0.0.0", "localhost", ""):
        return "127.0.0.1"
    if bind == "::":
        return "::1"
    return bind


def format_address(host: str, port: int) -> str:
    return f"[{host}]:{port}" if ":" in host else f"{host}:{port}"


def parse_address(value: str) -> Optional[tuple[str, int]]:
    """``HOST:PORT`` / ``[v6]:PORT`` -> (host, port), None when malformed."""
    host, sep, port = value.strip().rpartition(":")
    if not sep or not port.isdigit() or not host:
        return None
    host = host[1:-1] if host.startswith("[") and host.endswith("]") else host
    return (host, int(port)) if 0 < int(port) < 65536 else None


def _canonical(host: str) -> str:
    try:
        return ipaddress.ip_address(host.strip("[]")).compressed
    except ValueError:
        return host.lower()


def backend_address(argv: list[str]) -> Optional[tuple[str, int]]:
    """``(host, port)`` a ``hermes dashboard`` / ``serve`` argv listens on (its defaults when it names
    none), or None when *argv* is empty or not such a command."""
    from hermes_cli.main_dashboard import _parse_dashboard_runtime
    parsed = _parse_dashboard_runtime(argv) if argv else None
    # --port 0 asks for a free port: the command line does not say which one it got.
    return (parsed[1], parsed[2]) if parsed and parsed[2] else None


def _address_of(item: BackendItem, host) -> Optional[tuple[str, int]]:
    """Where *item* listens, from its argv (a unit's ExecStart when it is not running); None when its
    command line cannot be read. Never a guess: an unread command line is not ``127.0.0.1:9119``."""
    return backend_address(_argv_of(item, host))


def _address_text(address: Optional[tuple[str, int]]) -> str:
    return format_address(*address) if address else "an address that could not be read"


# PowerShell reads these as single quotes too, so each is doubled inside a single-quoted string.
_PS_SINGLE_QUOTES = ("'", "\u2018", "\u2019", "\u201a", "\u201b")


def pin_hermes_home(root, command: str, *, powershell: bool = False) -> str:
    """*command* (``hermes …``) run with ``HERMES_HOME`` set to *root*, quoted for a POSIX shell
    (``HERMES_HOME='…' hermes …``) or PowerShell (``$env:HERMES_HOME='…'; hermes …``). A relative *root*
    is made absolute against this process's cwd first: a fresh shell starts somewhere else."""
    import ntpath
    import posixpath
    flavour = ntpath if powershell else posixpath  # the shell the line is printed for
    root = str(root)
    if not flavour.isabs(root):
        root = flavour.normpath(flavour.join(os.getcwd(), root))
    if not powershell:
        return f"HERMES_HOME={shlex.quote(root)} {command}"
    for mark in _PS_SINGLE_QUOTES:
        root = root.replace(mark, mark * 2)
    return f"$env:HERMES_HOME='{root}'; {command}"


def hermes_command(home: Optional[str], *, powershell: bool = False) -> str:
    """How to type ``hermes`` for *home* in a fresh shell, so every printed step targets this home.

    - A profile of the standard root: ``hermes -p NAME``; also ``-p default``, since a bare ``hermes``
      would follow a sticky ``hermes profile use`` choice.
    - A profile of any other root (``HERMES_HOME=/srv/team-hermes``, or a root nested inside the standard
      one such as ``~/.hermes/team``): ``-p`` resolves against the root the shell's own ``HERMES_HOME``
      names (``profiles.resolve_profile_env``), so that root is pinned too: ``HERMES_HOME=ROOT hermes -p
      NAME`` (:func:`pin_hermes_home`).
    - A home that is no profile: ``HERMES_HOME=HOME hermes``.
    *powershell* quotes the pin for PowerShell."""
    from hermes_constants import profile_name_for_home
    if not home:
        return "hermes -p default"
    name = profile_name_for_home(home)
    root = _profile_root(home, name)
    if not name or root is None:
        return pin_hermes_home(home, "hermes", powershell=powershell)
    command = f"hermes -p {name}"
    return command if _is_standard_root(root) else pin_hermes_home(root, command, powershell=powershell)


def _profile_root(home: str, name: Optional[str]) -> Optional[str]:
    """The root ``-p NAME`` resolves *home* under: the home itself for ``default``, else the parent of its
    ``profiles/NAME`` directory (never a broader root it happens to sit inside). None when the path has no
    such shape."""
    from pathlib import Path
    if name == "default":
        return home
    for candidate in (Path(home), Path(home).resolve(strict=False)):
        if candidate.name == name and candidate.parent.name == "profiles":
            return str(candidate.parent.parent)
    return None


def _is_standard_root(root) -> bool:
    """Whether *root* is exactly the root a fresh shell's ``hermes`` (no HERMES_HOME) uses: resolved-path
    equality, never "inside it"."""
    from pathlib import Path
    from hermes_constants import _get_platform_default_hermes_home

    def resolved(path) -> str:
        return os.path.normcase(str(Path(path).resolve(strict=False)))
    return resolved(root) == resolved(_get_platform_default_hermes_home())


_SECRET_NAME = re.compile(r"pass(word|wd)?|secret|token|api[-_]?key|credential", re.IGNORECASE)
_ENV_ASSIGNMENT = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*=", re.DOTALL)
_URL_USERINFO = re.compile(r"(\w+://)[^/@\s]+@")
_PYTHON_EXE = re.compile(r"^pythonw?(\d+(\.\d+)*)?(\.exe)?$", re.IGNORECASE)
_SHORT_C_CLUSTER = re.compile(r"^-[A-Za-z]+c$")


def redacted_argv(argv: list[str]) -> list[str]:
    """*argv* for printing: inline ``NAME=value`` environment assignments, the value of a flag named like
    a credential (``--password …``, ``--token=…``), URL credentials (userinfo and query-string secrets) and
    inline ``-c`` (or Python short-option cluster ending in ``c``, e.g. ``-Ic``) launcher source are redacted."""
    from agent.redact import redact_sensitive_text
    out: list[str] = []
    next_placeholder: Optional[str] = None
    seen_python = False
    for token in argv:
        if next_placeholder is not None:
            out.append(next_placeholder)
            next_placeholder = None
        elif token == "-c" or (seen_python and _SHORT_C_CLUSTER.match(token)):
            out.append(token)
            next_placeholder = "<inline launcher source>"
        elif _ENV_ASSIGNMENT.match(token) or (token.startswith("-") and _SECRET_NAME.search(token.split("=", 1)[0])
                                              and "=" in token):
            out.append(token.split("=", 1)[0] + "=<redacted>")
        elif (token.startswith("-") and "=" not in token and _SECRET_NAME.search(token)
              and not token.endswith(("-stdin", "-file"))):
            out.append(token)
            next_placeholder = "<redacted>"
        else:
            if _PYTHON_EXE.match(token.replace("\\", "/").rsplit("/", 1)[-1]):
                seen_python = True
            out.append(redact_sensitive_text(_URL_USERINFO.sub(r"\1<redacted>@", token),
                                             force=True, redact_url_credentials=True))
    return out


def _for_this_home(item: BackendItem, host, plan: Optional[BackendPlan] = None) -> bool:
    """Whether *item* serves this home. A stopped (Nix) systemd unit is judged by the account it runs as
    (``User=``; root when unset, a user unit runs as the caller) and the environment systemd would give it
    (``host.unit_environment``: the manager's environment, ``Environment=``, then every ``EnvironmentFile=``,
    later wins), not by the report's ``this_home`` or the shell's own HERMES_HOME. When that cannot be
    told (an unreadable environment, an ``env`` launcher that may set its home: :func:`env_line`, a profile
    chosen on its command line) the plan is blocked."""
    if not item.running and item.unit and item.scope and item.supervisor in ("systemd", "nix-systemd"):
        if item.scope != "user":
            user = host.unit_props(item.unit, item.scope).get("User") or "root"
            if user != host.username():
                if plan is not None:
                    plan.notices.append(f"Skipped {item.unit}: it runs as {user}, not as {host.username()}; "
                                        f"its HERMES_HOME is that account's.")
                return False
        env, problem = host.unit_environment(item.unit, item.scope)
        if problem is None and (launcher := env_line(host, item.unit, item.scope)[0]):
            if plan is not None:
                user = "--user " if item.scope == "user" else ""
                plan.blockers.append(f"Cannot tell which Hermes home {item.unit} serves: its ExecStart starts it "
                                     f"through env, {launcher}. Put HERMES_HOME in the unit's Environment= rather "
                                     f"than on the env line, or stop and disable that unit by hand (systemctl "
                                     f"{user}disable --now {item.unit}), then re-run. Nothing changed.")
            return False
        if problem is None and _profile_flag(_argv_of(item, host)):
            problem = "its command line picks a profile (-p/--profile), which moves it to that profile's home"
        if problem:
            if plan is not None:
                plan.blockers.append(f"Cannot tell which Hermes home {item.unit} serves: {problem}. Identify the "
                                     f"owner (systemctl cat {item.unit}) and move it by hand, or give it one "
                                     f"readable EnvironmentFile= or an Environment=HERMES_HOME that no file "
                                     f"overrides, then re-run. Nothing changed.")
            return False
        if env.get("HERMES_HOME"):
            return host.same_home(env["HERMES_HOME"])
        mine = host.default_home(env)  # a unit that pins no HERMES_HOME runs its own default home
        if mine is None and plan is not None:
            plan.blockers.append(f"Cannot tell which Hermes home {item.unit} serves: it sets HOME to something "
                                 f"other than a plain absolute path. Identify the owner (systemctl cat "
                                 f"{item.unit}) and move it by hand, or set Environment=HERMES_HOME, then re-run. "
                                 f"Nothing changed.")
        return bool(mine)
    if item.this_home is not None:
        return item.this_home
    return not item.running and item.hermes_home is None and host.default_home()


_PAIR = re.compile(r"[A-Za-z_][A-Za-z0-9_]*=")  # a token that may be env(1)'s NAME=value
# env(1) options that leave the environment alone; ``-C``/``--chdir`` also takes the next argument.
_ENV_INERT = frozenset({"-0", "--null", "-v", "--debug", "--list-signal-handling"})
_ENV_SIGNALS = ("--block-signal", "--default-signal", "--ignore-signal")


def env_line(host, unit: str, scope: str) -> tuple[Optional[str], frozenset[str], frozenset[str]]:
    """Read a leading ``env`` launcher in *unit*'s ExecStart: ``(why the unit's home cannot be told from its
    environment, or None; the names its NAME=VALUE pairs set; its -u/-C/-S options)``. ``systemctl show``
    joins the arguments with spaces and systemd expands ``$`` in them when it runs the command, so this reads only what that line
    cannot hide: a home variable (``HERMES_HOME``, ``HOME``, ...) set or unset there, an option that changes
    the environment as a whole (``-i``, ``-S``) or one not read here, or a ``$`` anywhere but inside the value
    of a NAME=value pair (an option, its operand, a name: systemd may expand it to a home variable). Without
    those, the home is the unit environment's, as when there is no launcher. Nothing is expanded. Which
    other variables a -u/-C/-S option leaves set cannot be told (``-C "/srv/b -u AUX"`` shows as
    ``-C /srv/b -u AUX``), so the template check treats every outside variable as unknown then."""
    from hermes_cli.gateway_migrate_backends_host import _HOME_KEYS
    value = host.unit_props(unit, scope).get("ExecStart", "")
    # systemd prints the arguments unquoted, so whitespace is the only split that hides nothing
    shown = value.split("argv[]=", 1)[1].split(" ;", 1)[0].split() if "argv[]=" in value else []
    names: set[str] = set()
    opaque: set[str] = set()
    if not (shown and os.path.basename(shown[0]) == "env"):
        return None, frozenset(), frozenset()
    for tok in shown:
        if tok.split("=", 1)[0] in _HOME_KEYS and "=" in tok:
            return f"which sets {tok.split('=', 1)[0]} on that line", frozenset(names), frozenset(opaque)
    rest = list(shown)
    problem = None
    while rest and os.path.basename(rest[0]) == "env" and problem is None:
        rest, problem = _env_line_args(rest[1:], names, opaque)
    if problem is None and rest and "$" in rest[0]:
        problem = "whose command is a $ substitution that could hold an assignment"
    # The pairs end at the first other token, but a quoted value with a space ("NOTE=two words") ends them
    # early in the joined line: a NAME= token anywhere after it may still be a pair, so it counts as set.
    names.update(t.split("=", 1)[0] for t in rest if _PAIR.match(t))
    return problem, frozenset(names), frozenset(opaque)


def _env_line_args(args: list[str], names: set[str], opaque: set[str]) -> tuple[list[str], Optional[str]]:
    """One ``env`` invocation's options and pairs (*args*, without ``env`` itself): ``(the command after them,
    why the home cannot be told or None)``; the names its pairs set go into *names*, its -u/-C/-S options
    into *opaque*."""
    from hermes_cli.gateway_migrate_backends_host import _HOME_KEYS
    i = 0
    while i < len(args) and args[i].startswith("-"):
        arg = args[i]
        if arg == "--":
            i += 1
            break
        if arg.startswith(("-u", "--unset", "-C", "--chdir", "-S", "--split-string")):
            opaque.add(arg)
        value = arg[2:] if arg.startswith("-u") and arg != "-u" else (
            arg.split("=", 1)[1] if arg.startswith("--unset=") else None)
        if arg in ("-u", "--unset", "-C", "--chdir"):
            value, i = (args[i + 1] if i + 1 < len(args) else ""), i + 1
        if "$" in arg or "$" in (value or ""):
            return [], f"with a $ substitution in an option ({arg} {value or ''}), which may name any variable"
        if arg.startswith(("-u", "--unset")) and value in _HOME_KEYS:
            return [], f"which unsets {value} there (-u)"
        if not (value is not None or arg.startswith(("-C", "--chdir=")) or arg in _ENV_INERT
                or arg.startswith(_ENV_SIGNALS)):
            return [], f"with {arg}, which changes the environment as a whole or is not read here"
        i += 1
    while i < len(args) and "=" in args[i] and not args[i].startswith("="):
        name = args[i].split("=", 1)[0]
        if "$" in name:
            return [], "with a $ substitution that could hold an assignment"
        names.add(name)
        i += 1
    return args[i:], None


def _profile_flag(argv: list[str]) -> bool:
    return any(a in ("-p", "--profile") or a.startswith("--profile=") for a in argv or [])


_SYSTEM_LAUNCHD_DIRS = ("/Library/LaunchDaemons/", "/System/Library/LaunchDaemons/")


def is_system_launchd(scope: Optional[str], unit_path: Optional[str]) -> bool:
    """Whether a launchd target is a system-domain LaunchDaemon rather than a per-user LaunchAgent."""
    if (unit_path or "").strip().startswith(_SYSTEM_LAUNCHD_DIRS):
        return True
    return not (scope or "").strip().startswith(("gui/", "user/"))


def _is_system_launchd(item: BackendItem) -> bool:
    """Whether a launchd backend is a system-domain LaunchDaemon rather than a per-user LaunchAgent."""
    return is_system_launchd(getattr(item, "scope", None), getattr(item, "unit_path", None))


def _launchd_manual_stop(item: Optional[BackendItem]) -> Optional[str]:
    """The stop+disable shell line for a launchd backend (with ``sudo`` for a system LaunchDaemon)."""
    if not item or item.supervisor != "launchd" or not item.unit:
        return None
    is_system = _is_system_launchd(item)
    domain = (getattr(item, "scope", None) or "system") if is_system else item.scope
    prefix = ["sudo"] if is_system else []
    target = f"{domain}/{item.unit}"
    return (f"{shlex.join([*prefix, 'launchctl', 'bootout', target])}; "
            f"{shlex.join([*prefix, 'launchctl', 'disable', target])}")


def _supervisor_kind(item: BackendItem, host) -> str:
    """``systemd`` / ``launchd`` / ``manual`` when this command drives it, else an _UNSUPPORTED key."""
    if host.os_family() == "win32":
        return "windows"
    if item.supervisor == "systemd":
        # A system unit is never driven, root or not: `sudo hermes` refuses a per-user checkout, and
        # the gateway would have to become a system service of the unit's User= (not this caller's).
        return "systemd" if item.scope == "user" else "systemd-system"
    if item.supervisor == "launchd":
        # A system LaunchDaemon (/Library/LaunchDaemons, domain `system`) needs root to bootout/disable;
        # hermes cannot run as root on a per-user install, and the gateway is a per-user LaunchAgent.
        return "launchd-system" if _is_system_launchd(item) else "launchd"
    if item.supervisor in ("manual", "detached"):
        return "manual"
    return item.supervisor if item.supervisor in _UNSUPPORTED else "unknown"


# What `hermes gateway status` prints for each case, quoted from its output (systemd and launchd here,
# the Scheduled Task on Windows): the step tells the user which line to look for, first match first.
_STATUS_LINES = {
    "posix": ("'Gateway is not running' (no service installed)",
              "'service is stopped', 'service is not loaded' or 'registered with launchd'",
              "'service is running', 'supervised by launchd' or 'Running manually'"),
    # `hermes gateway status` on Windows: with no Scheduled Task or Startup entry it prints the shared
    # "Gateway is not running" / "Running manually" lines; with one, gateway_windows.status() prints the rest.
    "windows": ("'Gateway is not running' (no service installed)", "'No gateway process detected'",
                "'Gateway process running' or 'Running manually'"),
}
# A gateway just installed, started or restarted takes a few seconds to bind before `webapp --status` sees it.
WEBAPP_STATUS_WAIT = ("# the gateway takes a few seconds to serve the address: if the next line prints "
                      "'The gateway is not running', wait 5 seconds and run it again")


def gateway_tail(hermes: str, *, install: str = "install", windows: bool = False) -> list[str]:
    """The last steps of every by-hand move: run the gateway with the new webapp.* settings (a running
    gateway reads them only on restart), then check what serves the address."""
    missing, stopped, running = _STATUS_LINES["windows" if windows else "posix"]
    return [f"{hermes} gateway status",
            f"# then by what it prints: {missing} -> {hermes} gateway {install}; {stopped} -> {hermes} gateway "
            f"start; {running} -> {hermes} gateway restart",
            WEBAPP_STATUS_WAIT, f"{hermes} webapp --status"]


def public_url_steps(hermes: str, public_url) -> list[str]:
    """*public_url*: ``(url, problem)`` from :func:`resolve_public_url`. A refused URL is never printed."""
    url, problem = public_url or (None, None)
    if url:
        return [f"{hermes} config set webapp.public_url {shlex.quote(url)}"]
    if problem:
        return [f"# {problem} is not a URL the gateway accepts (http:// or https://, no credentials, query or "
                f"fragment): set webapp.public_url yourself (the value is not printed here)"]
    return []


def manual_steps(old_host: Optional[str], old_port: Optional[int], item: Optional[BackendItem], *, env_keys=(),
                 home: Optional[str] = None, no_service: bool = False, public_url=None,
                 keep_address: bool = False) -> list[str]:
    """The steps an operator runs by hand, in order, one shell line each (prose lines start with ``#``).
    Every ``hermes`` command names *home* (``-p PROFILE`` or ``HERMES_HOME=``).

    The old backend is always stopped before the gateway is (re)started, so the two never hold the port at
    once; the gateway is then installed, started or restarted by what ``hermes gateway status`` says, and
    ``hermes webapp --status`` checks the result. For a systemd SYSTEM unit everything runs as the user who
    owns the Hermes install except exactly one line, ``sudo systemctl disable --now UNIT``, and the next
    line shows the unit is no longer active. *no_service*: the gateway cannot be a service here; the last
    line runs it in the foreground for the operator's own supervisor. *public_url*: ``(url, problem)``,
    copied into ``webapp.public_url`` when the gateway accepts it. Without an address (*old_host* None)
    the settings lines say to use the old backend's address instead of inventing one."""
    hermes = hermes_command(home)
    env = f"{home}/.env" if home else "the Hermes .env"
    if env_keys:
        copy = (f"# copy {', '.join(sorted(env_keys))} from the old launcher's environment into {env}, "
                f"then: chmod 600 {env}  (values are never printed here)")
    else:
        copy = (f"# copy every HERMES_DASHBOARD_* line from the old launcher's environment that {env} does not "
                f"already set, if any, into {env} (chmod 600)")
    known = old_host is not None and old_port is not None
    where = f"webapp.host: {old_host}, webapp.port: {old_port}" if known else \
        "webapp.host and webapp.port to the old backend's address"
    settings = f"webapp.enabled: true, {where}"
    url, url_problem = public_url or (None, None)
    if url:
        settings += f", webapp.public_url: {url}"
    url_note = public_url_steps("hermes", (None, url_problem))
    if item is not None and item.supervisor in ("nix-systemd", "nix-launchd"):
        # A Nix-managed install refuses `hermes config set`; the settings and services live in the Nix config.
        rebuild = "nixos-rebuild switch or home-manager switch" if item.supervisor == "nix-systemd" else \
            "home-manager switch"
        keys = ", ".join(sorted(env_keys)) if env_keys else "every HERMES_DASHBOARD_* variable the backend had"
        return [f"# in your Nix configuration: disable the hermes backend service and set {settings} "
                f"in the Hermes settings", *url_note,
                f"# give the gateway {keys} through the environment file your Nix configuration provides "
                f"(values are never printed here)",
                f"# enable the gateway service there, then run {rebuild}"]
    if item is not None and item.supervisor in ("s6", "container"):
        # The image ships the Webapp built, and the gateway is the container's own slot or Compose service.
        port = old_port if known else "the old backend's port"
        return [f"# in the mounted Hermes home's config.yaml set {settings}", *url_note, copy,
                "# remove the dashboard: recreate the container without HERMES_DASHBOARD=1, or drop the Compose "
                "`dashboard` service and run: docker compose up -d --remove-orphans",
                f"# publish {port} on the gateway's container and restart it, so its gateway serves the address"]
    steps = [f"{hermes} webapp --build-only", f"{hermes} config set webapp.enabled true"]
    if keep_address:
        pass  # --keep-webapp-address: the Webapp stays where webapp.host/webapp.port already put it
    elif known:
        steps += [f"{hermes} config set webapp.host {old_host}", f"{hermes} config set webapp.port {old_port}"]
    else:
        steps.append(f"# set the old backend's address: {hermes} config set webapp.host HOST, then webapp.port PORT")
    steps += public_url_steps(hermes, public_url)
    steps.append(copy)
    if item is not None and item.supervisor == "systemd" and item.scope != "user" and item.unit:
        return steps + [f"sudo systemctl disable --now {item.unit}",
                        f"systemctl is-active {item.unit}  # must print inactive (or failed) before the next line",
                        *gateway_tail(hermes)]
    stop = {"systemd": f"systemctl --user disable --now {item.unit}" if item and item.unit else None,
            "launchd": _launchd_manual_stop(item)}
    steps.append(stop.get(item.supervisor if item else "", None)
                 or "# stop the old backend through its supervisor and keep it from starting at boot")
    if no_service:
        return steps + ["# run the next line from your own supervisor (restart on exit and at boot):",
                        f"{hermes} gateway run", WEBAPP_STATUS_WAIT, f"{hermes} webapp --status"]
    return steps + gateway_tail(hermes)


def _unsupported_entry(item: Optional[BackendItem], kind: str, host) -> tuple:
    """``(item, why, steps)`` for a backend this command will not drive (exit 6)."""
    address = _address_of(item, host) if item else None
    old_host, old_port = address if address else (None, None)
    why = _UNSUPPORTED[kind] if address or item is None else _UNSUPPORTED[kind] + " " + _UNSUPPORTED["unknown-address"]
    env = _manual_launcher_env(item, kind, host)  # names only leave this function
    keys: list[str] = []
    if kind in ("windows", "launchd-system") or (
        item is not None and item.supervisor == "systemd" and item.unit and item.scope
    ):
        keys = list(_keys_to_copy({k: v for k, v in env.items() if k.startswith(_AUTH_PREFIX) and v}, host.dotenv()))
    url = resolve_public_url(host.effective_config(), backend_url_env(host, env))
    if kind == "windows":
        from hermes_cli.gateway_migrate_backends_windows import manual_steps as windows_steps
        return item, why, windows_steps(old_host, old_port, item, env_keys=keys, home=str(host.home), public_url=url)
    return item, why, manual_steps(old_host, old_port, item, env_keys=keys, home=str(host.home), public_url=url)


def _manual_launcher_env(item: Optional[BackendItem], kind: str, host) -> dict:
    """The environment a by-hand backend was launched with (in memory only): a systemd unit's own,
    else its process's (falling back to a launchd plist's EnvironmentVariables); empty when neither can be read."""
    if item is None:
        return {}
    if kind != "windows" and item.supervisor == "systemd" and item.unit and item.scope:
        return host.unit_launcher_env(item.unit, item.scope) or {}
    env = (host.process_env(item.pid) if item.pid else None) or {}
    if not env and item.supervisor == "launchd" and (plist_path := getattr(item, "unit_path", None)):
        from hermes_cli.gateway_migrate_backends_host import plist_environment
        env = plist_environment(plist_path)
    return env


def _manual_public_url(plan: BackendPlan, host) -> None:
    """A by-hand plan copies the old backend's public URL too: one the gateway refuses blocks it, with
    the automatic plan's words, until webapp.public_url is set to an accepted one. Its steps copy no key the
    ``.env`` sets either, so a ``.env`` template the move would resolve differently blocks it the same way."""
    item = plan.unsupported[0][0]
    if item is None:
        return
    env = _manual_launcher_env(item, _supervisor_kind(item, host), host)
    if problem := resolve_public_url(host.effective_config(), backend_url_env(host, env))[1]:
        plan.blockers.append(_url_blocker(problem))
    if blocker := launcher_template_blocker(host, env or None, *_env_line_names(item, host, from_unit=True)):
        plan.blockers.append(blocker)


def _select(plan: BackendPlan, items: list[BackendItem], address, host) -> None:
    """Fill ``candidates`` / ``unsupported`` with this home's backends (Desktop-owned never)."""
    mine = [i for i in items if i.supervisor not in _NEVER_TOUCHED and _for_this_home(i, host, plan)]
    for i in items:
        if i.running and i.this_home is None and i.supervisor not in _NEVER_TOUCHED:
            plan.notices.append(f"Skipped pid {i.pid}: its HERMES_HOME could not be read.")
    if address is not None:
        want = (_canonical(address[0]), address[1])
        found = [_address_text(_address_of(i, host)) for i in mine]
        mine = [i for i in mine if (a := _address_of(i, host)) is not None and _key(a) == want]
        if not mine:
            plan.blockers.append(f"No old backend of this home listens on {format_address(*address)}; "
                                 f"found: {', '.join(found) or 'none'}.")
    if len(mine) > 1:
        where = ", ".join(_address_text(_address_of(i, host)) for i in mine)
        hint = "Pick one with --address HOST:PORT." if address is None else "The supplied address is not unique."
        plan.blockers.append(f"More than one old backend serves this home ({where}). {hint}")
        return
    for item in mine:
        kind = _supervisor_kind(item, host)
        if kind in _UNSUPPORTED:
            plan.unsupported.append(_unsupported_entry(item, kind, host))
        else:
            plan.candidates.append(item)


def _key(address: tuple[str, int]) -> tuple[str, int]:
    return _canonical(address[0]), address[1]


def _argv_of(item: BackendItem, host) -> list[str]:
    if item.argv:
        return list(item.argv)
    if item.supervisor in ("systemd", "nix-systemd") and item.unit and item.scope:
        from hermes_cli.gateway_migrate_backends_host import exec_start_argv
        return exec_start_argv(host.unit_props(item.unit, item.scope).get("ExecStart", ""))
    return []


def _record(item: BackendItem, host) -> tuple[dict, Optional[dict]]:
    """What the plan records about *item* (its argv redacted), plus its launcher environment (in memory only)."""
    kind = _supervisor_kind(item, host)
    rec = {"supervisor": kind, "report_supervisor": item.supervisor, "unit": item.unit, "scope": item.scope,
           "unit_path": item.unit_path, "pid": item.pid, "argv": redacted_argv(_argv_of(item, host)),
           "start_time": host.start_time(item.pid) if item.pid else None,
           "cwd": host.process_cwd(item.pid) if item.pid else None,
           "unit_file_state": item.state, "was_active": bool(item.running)}
    env = host.process_env(item.pid) if item.pid else None
    if kind == "systemd" and item.unit and item.scope:
        props = host.unit_props(item.unit, item.scope)
        rec["unit_file_state"] = props.get("UnitFileState") or item.state
        rec["was_active"] = props.get("ActiveState") == "active"
        rec["control_group"] = props.get("ControlGroup") or None
        if env is None:
            env = host.unit_launcher_env(item.unit, item.scope)
    if kind == "launchd":
        rec["was_loaded"] = True  # the report lists only launchd jobs that are loaded
        if env is None and item.unit_path:
            from hermes_cli.gateway_migrate_backends_host import plist_environment
            env = plist_environment(item.unit_path)  # a loaded job that is not running right now
    return rec, env


def _keys_to_copy(launcher: dict, dotenv: dict) -> dict:
    """The launcher's keys whose value the old backend uses and the home's ``.env`` lacks. ``load_hermes_dotenv``
    loads the ``.env`` over the launch environment, so a key the ``.env`` sets (even empty) already holds the
    value in use; only a parent-minted ``_SPAWN_CREDENTIAL_KEYS`` key keeps its exported value over the ``.env``."""
    from hermes_cli.env_loader import _SPAWN_CREDENTIAL_KEYS
    return {k: v for k, v in launcher.items()
            if k not in dotenv or (k in _SPAWN_CREDENTIAL_KEYS and dotenv[k] != v)}


def _credentials(plan: BackendPlan, env: Optional[dict], host, cfg: dict) -> None:
    dotenv = host.dotenv()
    launcher = {k: v for k, v in (env or {}).items() if k.startswith(_AUTH_PREFIX) and v}
    plan.carry = _keys_to_copy(launcher, dotenv)
    basic = ((cfg.get("dashboard") or {}).get("basic_auth") or {}) if isinstance(cfg.get("dashboard"), dict) else {}
    has_secret = bool(launcher.get(_SECRET_KEY) or dotenv.get(_SECRET_KEY) or os.environ.get(_SECRET_KEY)
                      or (isinstance(basic, dict) and basic.get("secret")))
    plan.generate_secret = not has_secret
    item = plan.item
    from_unit = not (item.pid and host.process_env(item.pid) is not None)  # as _record reads it
    if blocker := launcher_template_blocker(host, env, *_env_line_names(item, host, from_unit=from_unit)):
        plan.blockers.append(blocker)


def _env_line_names(item: Optional[BackendItem], host, *, from_unit: bool) -> tuple[frozenset, frozenset]:
    """``(the names an env launcher in item's systemd unit sets, its -u/-C/-S options)`` (:func:`env_line`),
    when the plan read its launch environment from the unit (*from_unit*) rather than from its running
    process, which already reflects them."""
    if not from_unit or item is None or item.supervisor != "systemd" or not (item.unit and item.scope):
        return frozenset(), frozenset()
    return env_line(host, item.unit, item.scope)[1:]


def launcher_template_blocker(host, launcher: Optional[dict], env_line_names: frozenset = frozenset(),
                              env_line_opaque: frozenset = frozenset()) -> Optional[str]:
    """Why the move would change a sign-in setting (:data:`_SIGN_IN_KEYS`) that the home's ``.env`` sets as a
    ``${VAR}`` template, or None. The ``.env`` loads over the launch environment with ``${VAR}`` read from that
    environment (``env_loader``), so the old backend resolved it against its launcher's (*launcher*; None
    when unreadable) and the gateway resolves it against its service's (``host.gateway_environment``). Only a
    value that depends on a variable from outside the ``.env`` (:func:`_outside_reads`) can differ; an unknown
    environment refuses only such a value. A key the managed ``.env`` sets is not the home ``.env``'s. Since
    the plan copies no key the ``.env`` sets, a template that resolves differently (a blank password: the
    Webapp's sign-in no longer accepts the old credential) refuses the move. A variable the old unit's ``env``
    launcher sets (*env_line_names*) has a value not read here, so a template reading one is refused too, and
    one with a -u/-C/-S option (*env_line_opaque*) leaves no outside variable knowable, so every such
    template is refused."""
    from hermes_cli.env_loader import _parse_dotenv_file, _resolve_dotenv_assignments
    try:
        assignments = _parse_dotenv_file(host.home / ".env")
    except OSError:
        return None
    managed = host.managed_env()
    outside = _outside_reads(assignments)
    reads = {name: outside[name] for name, _value in assignments
             if name in _SIGN_IN_KEYS and name not in managed and outside[name]}
    if not reads:
        return None
    gateway_env, why = host.gateway_environment()
    old = _resolve_dotenv_assignments(assignments, launcher, override=True) if launcher is not None else {}
    new = _resolve_dotenv_assignments(assignments, gateway_env, override=True)
    keys = sorted(k for k in reads if launcher is None or why is not None or env_line_opaque
                  or reads[k] & env_line_names or old.get(k) != new.get(k))
    if not keys:
        return None
    variables = sorted({v for k in keys for v in reads[k]})
    on_line = sorted(set(variables) & env_line_names)
    unknown = ("the old backend's launch environment cannot be read" if launcher is None
               else f"the env line of the old backend's ExecStart ({', '.join(sorted(env_line_opaque))}) changes "
                    f"the environment in a way this check cannot read" if env_line_opaque
               else f"{', '.join(on_line)} is set on the env line of the old backend's ExecStart, whose value is "
                    f"not read here" if on_line
               else f"{why}, so its value there cannot be told" if why else "")
    reason = f" ({unknown})" if unknown else ""
    env_file = host.home / ".env"
    return (f"{', '.join(keys)} in {env_file} is a ${{...}} template that reads {', '.join(variables)} from the "
            f"environment the backend starts with, and the gateway would not start with the old backend's value"
            f"{reason}: after the move it would resolve differently, and the Webapp's sign-in would not take the "
            f"old credential. Put the literal value in {env_file} (chmod 600), or set {', '.join(variables)} where "
            f"the gateway runs (its service's environment), then re-run. Nothing changed.")


def _outside_reads(assignments: list) -> dict[str, set[str]]:
    """For each name the ``.env`` *assignments* set, the variables from outside the file its final value reads,
    followed the way the loader resolves them (``env_loader._resolve_dotenv_assignments`` with override): a
    line sees the lines before it, which win over the environment, so ``${VAR}`` or ``${VAR:-default}`` of a
    name set earlier reads only what that line read; any other name comes from the environment."""
    from dotenv.variables import Variable, parse_variables
    outside: dict[str, set[str]] = {}
    for name, value in assignments:
        reads: set[str] = set()
        for atom in parse_variables(value or ""):
            if isinstance(atom, Variable):
                reads |= outside.get(atom.name, {atom.name})
        outside[name] = reads
    return outside


def resolve_public_url(cfg: dict, env: Optional[dict]) -> tuple[Optional[str], Optional[str]]:
    """``(url, problem)``: the public URL the old backend serves, picked the way the backend picks it
    (``dashboard_auth.prefix.resolve_public_url``: its ``HERMES_DASHBOARD_PUBLIC_URL`` first, blank or
    malformed counting as unset, then ``dashboard.public_url`` of the resolved *cfg*), when
    ``webapp.public_url`` is unset and the gateway accepts it (``webapp.public_url`` rules). Otherwise
    ``problem`` names where the refused value is. The refused value is never returned: it may carry
    ``user:password@``."""
    from gateway.webapp_listener import _public_url as accepted_public_url
    from hermes_cli.dashboard_auth.prefix import _normalise_public_url
    webapp, dashboard = cfg.get("webapp"), cfg.get("dashboard")
    if isinstance(webapp, dict) and webapp.get("public_url"):
        return None, None
    from_env = _normalise_public_url((env or {}).get("HERMES_DASHBOARD_PUBLIC_URL"))
    configured = dashboard.get("public_url") if isinstance(dashboard, dict) else None
    value = from_env or _normalise_public_url(str(configured) if configured else "")
    if not value:
        return None, None
    source = "HERMES_DASHBOARD_PUBLIC_URL" if from_env else "dashboard.public_url"
    url = accepted_public_url(value)
    return (url, None) if url else (None, f"The old backend's public URL ({source})")


_URL_KEY = "HERMES_DASHBOARD_PUBLIC_URL"


def backend_url_env(host, launch_env: Optional[dict]) -> dict:
    """``{HERMES_DASHBOARD_PUBLIC_URL: value}`` as the old backend's process has it after startup, from the
    environment it was launched with: ``load_hermes_dotenv`` (hermes_cli/main.py) loads the home's ``.env``
    over it (override), clears a profile-managed key the ``.env`` lacks, and applies the managed ``.env``
    last. External secret sources are not modelled: ``secret_source_blocker`` stops the plan when one is on.
    Empty when the backend has no such variable."""
    from hermes_cli.env_loader import _PROFILE_MANAGED_ENV_KEYS
    managed = host.managed_env()
    if _URL_KEY in managed:
        return {_URL_KEY: managed[_URL_KEY]}
    dotenv = host.dotenv()
    if _URL_KEY in dotenv:
        return {_URL_KEY: dotenv[_URL_KEY]}
    if host.dotenv_exists() and _URL_KEY in _PROFILE_MANAGED_ENV_KEYS:
        return {}
    value = (launch_env or {}).get(_URL_KEY)
    return {_URL_KEY: value} if value is not None else {}


def _loopback_public_url(address: Optional[tuple[str, int]]) -> str:
    """A valid loopback ``webapp.public_url`` matching *address*'s host/IP family and port, or a placeholder."""
    if address is None:
        return "http://127.0.0.1:<port>"
    from gateway.webapp_listener import dial_origin
    return dial_origin(_canonical(address[0].strip()), address[1])


def _secret_source_address(item: Optional[BackendItem], host, keep_webapp: bool) -> Optional[tuple[str, int]]:
    """Where the Webapp would serve after the move (:func:`_target`); None while that is unknown or blocked,
    since the old backend's port is wrong once the Webapp is already enabled on another address."""
    old = _address_of(item, host) if item is not None else None
    return _target(host, old, keep_webapp)[0] if old is not None else None


def secret_source_blocker(host, *, address: Optional[tuple[str, int]] = None, nix: bool = False) -> Optional[str]:
    """An enabled external secret source (``secrets:``) may set or override HERMES_DASHBOARD_PUBLIC_URL
    after the ``.env`` loads, so which public URL the old backend serves cannot be told, unless
    ``webapp.public_url`` is already set (the plan then copies none)."""
    cfg = host.effective_config()
    webapp, secrets = cfg.get("webapp"), cfg.get("secrets")
    if isinstance(webapp, dict) and webapp.get("public_url"):
        return None
    if not (isinstance(secrets, dict) and any(isinstance(v, dict) and v.get("enabled") is True
                                                for v in secrets.values())):
        return None
    from hermes_constants import get_managed_system

    local_url = _loopback_public_url(address)
    managed = get_managed_system(host.home)
    if nix or managed in ("nix", "nixos", "home-manager"):
        where = (f"Set webapp.public_url in your Nix configuration to the URL you open in a browser, "
                 f"or {local_url} for local/Desktop-only use")
    elif managed:
        where = (f"Set webapp.public_url in your {managed} configuration to the URL you open in a browser, "
                 f"or {local_url} for local/Desktop-only use")
    else:
        where = f"Set webapp.public_url to the URL you open in a browser, or {local_url} for local/Desktop-only use"
        if address is not None:  # saved as is, the <port> placeholder would keep the Webapp off
            hermes = hermes_command(str(host.home), powershell=host.os_family() == "win32")
            where += f" (e.g. `{hermes} config set webapp.public_url {shlex.quote(local_url)}`)"
    return ("An external secret source is enabled (secrets: in config.yaml), and it may set or override the old "
            "backend's HERMES_DASHBOARD_PUBLIC_URL; Hermes never reads vault values to guess it. "
            "webapp.public_url is simply the browser-facing http:// or https:// address the Webapp uses for "
            "sign-in callbacks and Host/Origin checks — it does not need to be internet-routable (a LAN "
            f"hostname/IP or loopback address works). {where}, then re-run. Nothing changed.")


def _public_url(plan: BackendPlan, cfg: dict, env: Optional[dict]) -> None:
    plan.public_url, problem = resolve_public_url(cfg, env)
    if problem:
        plan.blockers.append(_url_blocker(problem))


def _url_blocker(problem: str) -> str:
    return (f"{problem} is not one the gateway accepts as webapp.public_url: it must be http:// or https:// "
            f"with no credentials, query or fragment. Fix it, or set webapp.public_url yourself (its value is "
            f"not printed here).")


def _address(plan: BackendPlan, host, keep_webapp: bool) -> None:
    """Rule 1 (never widen exposure) and rule 10 (never guess between addresses)."""
    address = backend_address(plan.old_argv)
    if address is None:
        plan.blockers.append("The old backend's command line could not be read, or it asks for a free port "
                             "(--port 0), so the address it serves is unknown and nothing can be planned for it. "
                             "Nothing changed.")
        return
    plan.old_host, plan.old_port = address
    target, problems = _target(host, address, keep_webapp)
    plan.blockers += problems
    if target is not None:
        plan.keep_webapp = keep_webapp
        plan.new_host, plan.new_port = target


def _target(host, old: tuple[str, int], keep_webapp: bool) -> tuple[Optional[tuple[str, int]], list[str]]:
    """Where the Webapp would serve, and why it cannot: the same rules for an automatic and a by-hand move."""
    settings = host.webapp_settings()
    if keep_webapp:
        if not settings.enabled:
            return None, ["--keep-webapp-address needs the Webapp already enabled (webapp.enabled: true); "
                          "it is off in this home."]
        return (settings.host, settings.port), []
    accepted = host.accepted_webapp_host(old[0])
    if accepted is None:
        return None, [f"The old backend binds {old[0]}; the gateway's webapp.host takes only loopback, a wildcard "
                      f"or one IP address, and widening the bind is never done. Nothing changed."]
    if settings.enabled and (_canonical(settings.host), settings.port) != (_canonical(accepted), old[1]):
        return None, [f"The Webapp is already enabled on {format_address(settings.host, settings.port)}, not on the "
                      f"old backend's {format_address(*old)}. Re-run with --keep-webapp-address to retire the old "
                      f"backend and keep the Webapp where it is."]
    return (accepted, old[1]), []


def _proposed_webapp(plan: BackendPlan, host) -> None:
    """The webapp: block the move would leave, judged by the gateway itself: an existing value the plan
    does not set (a refused webapp.public_url) keeps the Webapp off and blocks the move."""
    reason = host.proposed_webapp_reason(plan.new_host, plan.new_port, plan.public_url)
    if reason:
        plan.blockers.append(f"After the move the gateway would still refuse the Webapp: {reason}. Fix it in "
                             f"config.yaml and re-run. Nothing changed.")


def _manual_turns(plan: BackendPlan, host, force_interrupt: bool) -> None:
    """Read activity once for the selected by-hand backend; block on active or unknown turns unless forced."""
    item, why, steps = plan.unsupported[0]
    if item is None or not item.running:
        plan.running_turns = 0
        return
    if not _manual_activity(plan, item, host):
        why += f" {_OUTSIDE_CONTAINER}"
    plan.unsupported[0] = (item, why + _turns_note(plan.running_turns, force_interrupt), steps)
    _turns_blocker(plan, force_interrupt)


def _turns_note(turns: Optional[int], force_interrupt: bool) -> str:
    """What a by-hand recipe says above its stop steps about the old backend's running turns."""
    if turns:
        return f" {turns} turn(s) are running on it now: stopping it interrupts them, so let them finish first."
    if turns is None and force_interrupt:
        return " Its turn activity could not be read, so turns may be running on it now: stopping it interrupts them."
    return ""


_OUTSIDE_CONTAINER = ("Its Hermes version could not be checked from outside its container, and a Hermes older "
                      "than v2026.7.30 does not record running chats: check inside the container that no reply "
                      "is being written before you stop it.")


def _manual_activity(plan: BackendPlan, item: BackendItem, host) -> bool:
    """Turns running on a by-hand backend, read the way the automatic plan reads them: a backend with no
    GET /api/health (older than v2026.7.30) writes no turn markers, so finding none there is unknown.
    The health answer counts only from a backend in the planner's own network namespace: for a container
    seen from the host, the argv's address on this machine's loopback is another process (Docker
    publishes the port elsewhere). Then only the markers are read, and False says its version is unchecked."""
    start = host.start_time(item.pid) if item.pid else None
    local = bool(item.pid) and host.same_network_namespace(item.pid, container=item.supervisor == "container")
    address = _address_of(item, host) if local else None
    status = host.health_status(probe_host(address[0]), address[1]) if address else None
    old = status is not None and status.get("health") == "missing"
    plan.running_turns = _turns_before_restart(host, item.pid, start) if old else \
        host.running_turns(item.pid, start) if item.pid else None
    if plan.running_turns is None:
        plan.turns_unknown = _turns_unknown(host, item.pid, start, old=old)
    return local or not item.pid


def _turns_unknown(host, pid: Optional[int], start_time, *, old: bool = False) -> str:
    """Why the turns of the old backend *pid* cannot be told: each marker file at fault (path only:
    a marker holds the turn's prompt), a Hermes that writes none, or no pid."""
    if not pid:
        return "its process id is not known"
    why = ("it runs a Hermes older than v2026.7.30, which has no GET /api/health and writes no turn markers, "
           "so finding none does not mean it is idle") if old else ""
    if files := host.unknown_turn_files(pid, start_time):
        found = (f"these turn-marker files cannot be read, or hold a marker whose writer cannot be checked: "
                 f"{', '.join(files)}")
        why = f"{why}; {found}" if why else found
    return why or "its turn activity could not be read"


def _manual_target(plan: BackendPlan, host, keep_webapp: bool) -> None:
    """A by-hand move prints webapp.host/port commands: they pass the same checks as an automatic move."""
    item, why, _steps = plan.unsupported[0]
    address = _address_of(item, host) if item else None
    if address is None:
        return
    if keep_webapp:
        problems = ["--keep-webapp-address is not planned for a by-hand move: its printed steps set the Webapp "
                    "to the old backend's address. Stop the old backend through its supervisor and leave webapp.* "
                    "as it is."]
    else:
        target, problems = _target(host, address, False)
        if target is not None:
            reason = host.proposed_webapp_reason(*target, None)
            problems = [f"After the move the gateway would still refuse the Webapp: {reason}. Fix it in "
                        f"config.yaml and re-run. Nothing changed."] if reason else []
    if problems:
        plan.blockers += problems
        plan.unsupported[0] = (item, why, [])  # no steps that would set a refused or conflicting address


def _gateway(plan: BackendPlan, host, force_interrupt: bool) -> None:
    gs = host.gateway_state()
    plan.gateway, plan.linger = gs, host.linger()
    if gs["kind"] is None:
        plan.no_service = True  # its by-hand steps are built once every check has run (build_plan)
        return
    _legacy(plan, host)
    if gs["running_pid"] and not gs["active"]:
        _stray_gateway(plan, host, gs["running_pid"], force_interrupt)
    if reason := host.gateway_preflight():
        plan.blockers.append(f"The gateway's user service cannot be driven from this shell: {reason}")


def _forceable(plan: BackendPlan, blocker: str, consent: str, force_interrupt: bool) -> None:
    """Something the move may stop only with the user's consent: *consent* says what (the dashboard's Move asks
    once for all of it), and without --force-interrupt *blocker* holds the move."""
    plan.takes_over.append(consent)
    if not force_interrupt:
        plan.blockers.append(blocker)
        plan.forceable.append(blocker)


def _stray_gateway(plan: BackendPlan, host, pid: int, force_interrupt: bool) -> None:
    """A gateway of this home running outside its service: one the dashboard's chat started (it ends itself
    when idle) or one started by hand, which may run messaging bots. With consent the move stops it right after
    the old backend, so the gateway service can take over; a legacy ``hermes.service`` is replaced instead."""
    stray = host.stray_gateway(pid)
    if any(u.get("main_pid") == pid or u["unit"] == stray.get("unit") for u in plan.legacy_units):
        return  # the legacy unit's own gateway: replaced, not stopped by hand
    what = ("started by a chat window; it ends by itself when idle" if stray["idle_exit"]
            else "started by hand or by another program")
    chats = {None: "; its chats cannot be read", 0: ""}.get(stray["chats"], f"; {stray['chats']} chat(s) running on it")
    stop = f"{hermes_command(plan.home, powershell=plan.powershell)} gateway stop"
    _forceable(plan, f"A gateway for this home runs outside its service (pid {pid}, {what}{chats}). The move stops "
                     f"it and runs the gateway as a service in its place; re-run with --force-interrupt to allow that "
                     f"(or stop it first: {stop}).",
               f"Stops the gateway running outside its service (pid {pid}, {what}{chats}); the gateway service "
               f"takes over its chats and messaging bots.", force_interrupt)
    if force_interrupt:
        plan.stray_gateway = stray


_LEGACY_ENV_DROPIN = "hermes-legacy-environment.conf"


def _legacy(plan: BackendPlan, host) -> None:
    """A pre-rename ``hermes.service`` gateway unit: the move replaces it with the gateway service, keeping its
    extra ``Environment=``/``EnvironmentFile=`` lines in a drop-in and its unit file for a rollback or --restore.
    Bot tokens and pairings live in this home, so nothing signs in again. One it cannot replace blocks."""
    for unit in host.legacy_unit_records():
        if unit["system"]:
            plan.blockers.append(
                f"A legacy system-wide gateway unit is installed ({unit['path']}), and this command changes no system "
                f"unit. Remove it as root (sudo systemctl disable --now {unit['unit']}; sudo rm {unit['path']}; sudo "
                f"systemctl daemon-reload), then run this again; your bots keep their logins (they are in this home). "
                f"Nothing changed.")
        elif (problem := _legacy_home_problem(unit, host)) is not None:
            plan.blockers.append(f"A legacy gateway unit ({unit['unit']}) is installed, but {problem}, so the move "
                                 f"cannot replace it. Remove it from the home it serves (hermes gateway migrate-legacy "
                                 f"there), then run this again. Nothing changed.")
        elif os.path.lexists(dropin := host.gateway_env_dropin_path(_LEGACY_ENV_DROPIN)):
            plan.blockers.append(f"{dropin} already exists; move it aside before migrating. Nothing changed.")
        else:
            plan.legacy_units.append(unit)
            plan.takes_over.append(f"Replaces the old {unit['unit']} with the gateway service, which keeps its "
                                   f"environment settings; its messaging bots keep their logins.")


def _legacy_home_problem(unit: dict, host) -> Optional[str]:
    """Why *unit* may serve another Hermes home (``hermes gateway install`` deletes it whichever home it serves),
    else None: read the way the old backend's unit is (:func:`_for_this_home`)."""
    from hermes_cli.gateway_migrate_backends_host import exec_start_argv
    env, problem = host.unit_environment(unit["unit"], "user")
    if problem is None and _profile_flag(exec_start_argv(host.unit_props(unit["unit"], "user").get("ExecStart", ""))):
        problem = "its command line picks a profile (-p/--profile)"
    if problem:
        return f"which Hermes home it serves cannot be told ({problem})"
    if env.get("HERMES_HOME"):
        return None if host.same_home(env["HERMES_HOME"]) else f"it serves another Hermes home ({env['HERMES_HOME']})"
    mine = host.default_home(env)  # a unit that pins no HERMES_HOME runs its own default home
    if mine is None:
        return "which Hermes home it serves cannot be told (its HOME is not a plain absolute path)"
    return None if mine else "it serves another Hermes home (the default one)"


def _restart_hint(plan: BackendPlan) -> str:
    rec = plan.rec
    if rec.get("supervisor") == "systemd" and rec.get("unit"):
        user = " --user" if rec.get("scope") == "user" else ""
        return f"{'sudo ' if not user else ''}systemctl{user} restart {rec['unit']}"
    if rec.get("supervisor") == "launchd" and rec.get("unit") and rec.get("scope"):
        prefix = ["sudo"] if is_system_launchd(rec.get("scope"), rec.get("unit_path")) else []
        return shlex.join([*prefix, "launchctl", "kickstart", "-k", f"{rec['scope']}/{rec['unit']}"])
    return "stop it and start it again the way it was started"


def _turns_before_restart(host, pid: Optional[int], start_time) -> Optional[int]:
    """Turns found running on a backend whose health cannot be read; None when none can be shown (no pid,
    an unreadable marker, or none found: a Hermes before v2026.7.30 writes no turn markers)."""
    if not pid:
        return None
    try:
        return host.running_turns(pid, start_time) or None
    except OSError:
        return None


def _turns_blocker(plan: BackendPlan, force_interrupt: bool) -> None:
    if plan.running_turns is None:
        why = plan.turns_unknown or "its turn activity could not be read"
        _forceable(plan, f"Cannot tell whether turns are running on the old backend: {why}. To move it, confirm it "
                         f"is idle, then re-run with --force-interrupt (any running turn is interrupted).",
                   "Cuts off any reply being written on the old backend (its chat activity cannot be read).",
                   force_interrupt)
    elif plan.running_turns > 0:
        _forceable(plan, f"{plan.running_turns} turn(s) are running on the old backend. Wait for them to finish, or "
                         f"re-run with --force-interrupt (they are interrupted).",
                   f"Cuts off the {plan.running_turns} reply(ies) being written on the old backend.", force_interrupt)


def _auth_and_turns(plan: BackendPlan, host, force_interrupt: bool) -> None:
    if not plan.rec["was_active"]:
        plan.running_turns = 0
        return
    status = host.http_status(plan.old_probe_host, plan.old_port)
    if status is not None and status.get("health") == "missing":
        plan.running_turns = _turns_before_restart(host, plan.item.pid if plan.item else None,
                                                   plan.rec.get("start_time"))
        if plan.running_turns:
            first = (f"{plan.running_turns} turn(s) are running on it now: let them finish before you restart it, "
                     f"or the reply being written is cut off. Then restart")
        else:  # a Hermes this old writes no turn markers, so none found is not proof that it is idle
            first = ("Its activity cannot be read: confirm no reply is being written in it (it is idle) before "
                     "you restart it. Then restart")
        plan.blockers.append(
            f"The old backend on {format_address(plan.old_probe_host, plan.old_port)} runs a Hermes older than "
            f"v2026.7.30: it has no GET /api/health, so its sign-in state and running turns cannot be read "
            f"without changing files. {first} the old backend with the updated hermes "
            f"({_restart_hint(plan)}), then re-run the dry run. Nothing changed.")
        return
    if status is None:
        plan.blockers.append(f"The old backend runs but does not return a usable GET /api/health response on "
                             f"{format_address(plan.old_probe_host, plan.old_port)}, so its working state cannot "
                             f"be recorded before a move.")
    else:
        providers = status.get("auth_providers")
        plan.auth_before = {"auth_required": bool(status.get("auth_required")),
                            "providers": provider_names(providers) if isinstance(providers, list) else None}
    pid, start = (plan.item.pid if plan.item else None), plan.rec.get("start_time")
    plan.running_turns = host.running_turns(pid, start) if pid else None
    if plan.running_turns is None:
        plan.turns_unknown = _turns_unknown(host, pid, start)
    _turns_blocker(plan, force_interrupt)


def provider_names(raw) -> list[str]:
    names = [p if isinstance(p, str) else (p or {}).get("name") for p in (raw or [])]
    return sorted(n for n in names if n)


def _own_cgroup_inside(plan: BackendPlan) -> bool:
    from hermes_cli.update_cmd_posix_pause import _inside, _pid_cgroup
    return _inside(_pid_cgroup(), plan.rec.get("control_group"))


def build_plan(host, *, address=None, keep_webapp=False, force_interrupt=False) -> BackendPlan:
    plan = _build_plan(host, address=address, keep_webapp=keep_webapp, force_interrupt=force_interrupt)
    if plan.no_service:  # built last, from the selected target, once every check has run
        steps = [] if plan.blockers else manual_steps(
            plan.new_host, plan.new_port, plan.item, home=plan.home, no_service=True,
            public_url=(plan.public_url, None), keep_address=plan.keep_webapp)
        plan.unsupported.append((None, _UNSUPPORTED["no-service"] + _turns_note(plan.running_turns, force_interrupt),
                                 steps))
    if plan.blockers:  # no step, in text or JSON, while anything blocks the move
        plan.unsupported = [(item, why, []) for item, why, _steps in plan.unsupported]
    return plan


def _owner_problem(host) -> Optional[str]:
    """Why this profile's move is not planned here: another home's gateway serves it, or which gateway
    serves it is not known. None for a home whose own gateway would serve the Webapp."""
    from hermes_constants import profile_name_for_home
    kind, owner = host.gateway_owner()
    name = profile_name_for_home(str(host.home))
    if kind == "other":
        return (f"Profile {name} is served by another home's gateway ({owner}), whose Webapp settings are that "
                f"home's, so this dry run does not plan the move. Stop the old backend through its supervisor "
                f"and turn on the Webapp in the profile that runs that gateway. Nothing changed.")
    if kind == "unknown":
        return (f"Cannot tell which gateway serves profile {name}: it has no gateway service of its own and no "
                f"running gateway serves it. Identify which gateway serves this profile "
                f"({hermes_command(str(host.home), powershell=host.os_family() == 'win32')} gateway status), then "
                f"re-run. Nothing changed.")
    return None


def _build_plan(host, *, address=None, keep_webapp=False, force_interrupt=False) -> BackendPlan:
    plan = BackendPlan(home=str(host.home))
    plan.powershell = host.os_family() == "win32"
    if problem := host.config_problem():
        plan.blockers.append(f"{problem}: fix it and re-run the dry run. Nothing changed.")
        return plan
    _select(plan, host.backends(), address, host)
    from hermes_cli.profiles_run_elsewhere import run_elsewhere_refusal
    if (plan.unsupported or plan.candidates) and (elsewhere := run_elsewhere_refusal(host.home)) is not None:
        # A plugin runs this profile elsewhere. The gateway a move starts would refuse the profile, and
        # the backend found for its home may be the one the plugin runs: the plan lists none, to move
        # here or by hand.
        plan.blockers.append(f"{elsewhere} Nothing changed.")
        plan.unsupported, plan.candidates = [], []
        return plan
    if (plan.unsupported or plan.candidates) and (problem := _owner_problem(host)):
        plan.blockers.append(problem)
        plan.unsupported = [(item, why, []) for item, why, _steps in plan.unsupported]
        plan.candidates = []
        return plan
    if plan.unsupported or plan.candidates:
        selected = plan.candidates[0] if plan.candidates else plan.unsupported[0][0]
        if problem := secret_source_blocker(
            host,
            address=_secret_source_address(selected, host, keep_webapp and bool(plan.candidates)),
            nix=selected is not None and selected.supervisor in ("nix-systemd", "nix-launchd"),
        ):
            plan.blockers.append(problem)
    if plan.unsupported:
        _manual_target(plan, host, keep_webapp)
        _manual_public_url(plan, host)
        if not plan.blockers:
            _manual_turns(plan, host, force_interrupt)
        return plan
    if not plan.candidates:
        return plan

    plan.item = plan.candidates[0]
    plan.rec, env = _record(plan.item, host)
    plan.old_argv = _argv_of(plan.item, host)
    cfg = host.effective_config()
    _address(plan, host, keep_webapp)
    if plan.old_host is None:
        return plan
    _credentials(plan, env, host, cfg)
    _public_url(plan, cfg, backend_url_env(host, env))
    if plan.new_host is not None:
        _proposed_webapp(plan, host)
    _gateway(plan, host, force_interrupt)
    _auth_and_turns(plan, host, force_interrupt)
    plan.bundle_missing = host.bundle_missing()
    if plan.rec["supervisor"] == "systemd" and _own_cgroup_inside(plan):
        plan.blockers.append(f"This command runs inside {plan.rec['unit']} itself, so stopping that unit would end "
                             f"the run. Run it from a terminal that is not part of that unit, or re-run with "
                             f"--detach.")
    return plan


def _gateway_line(plan: BackendPlan) -> str:
    gs = plan.gateway
    if not gs.get("installed") and gs.get("kind") == "launchd":
        hermes = hermes_command(plan.home, powershell=plan.powershell)
        return f"not installed → install the launchd agent ({hermes} gateway install; it starts at login)"
    if not gs.get("installed"):
        linger = {True: "lingering is on", False: "lingering is off; install tries to enable it",
                  None: "lingering unknown"}[plan.linger]
        hermes = hermes_command(plan.home, powershell=plan.powershell)
        return f"not installed → install the user service ({hermes} gateway install; {linger})"
    state = "running" if gs.get("active") else "installed, stopped"
    return f"{state} ({gs.get('unit') or gs.get('kind')}) → {'restart' if gs.get('active') else 'start'} it"


def format_plan(plan: BackendPlan, *, dry_run: bool) -> list[str]:
    head = "Backend migration plan (dry run — nothing changed)" if dry_run else "Backend migration plan"
    lines = [head, f"  home:          {plan.home}"]
    if plan.nothing_to_do:
        return lines + ["  ✓ No old backend (hermes dashboard / serve) serves this home: nothing to migrate."]
    for item, text, steps in plan.unsupported:
        where = f"{item.supervisor} {item.unit or ''}".strip() if item else "gateway service"
        lines += [f"  ✗ {where} cannot be migrated automatically. Nothing changed.", f"    {text}",
                  "    Steps, in this order (one command per line):"]
        lines += [f"      {s}" for s in steps]
    if plan.rec:
        lines += _plan_body(plan)
    if plan.takes_over:
        lines += ["", "  The move also:", *[f"    • {t}" for t in plan.takes_over]]
    if plan.blockers:
        lines += ["", "  ✗ Blockers (nothing will be changed):", *[f"    • {b}" for b in plan.blockers]]
    if plan.notices:
        lines += ["", "  Notices:", *[f"    • {n}" for n in plan.notices]]
    return lines


def _plan_body(plan: BackendPlan) -> list[str]:
    rec = plan.rec
    who = {"systemd": f"systemd {rec['scope']} unit {rec['unit']}", "launchd": f"launchd job {rec['unit']}",
           "manual": "a process started by hand"}[rec["supervisor"]]
    pid = f", pid {rec['pid']}" if rec.get("pid") else ", not running"
    auth = plan.auth_before
    choices = (", ".join(auth["providers"]) or "none") if auth and auth["providers"] is not None else "unknown"
    signin = (f"required (interactive providers: {choices})" if auth and auth["auth_required"]
              else "not required" if auth
              else "unknown (health probe failed)" if rec.get("was_active") else "unknown (backend not running)")
    copy = ", ".join(sorted(plan.carry)) or "none needed"
    old = format_address(plan.old_host, plan.old_port) if plan.old_host is not None else \
        "an address that could not be read"
    lines = [f"  old backend:   {who}{pid} on {old}"]
    if plan.old_host is None:  # nothing else is known yet: the blockers say why
        return lines
    if plan.new_host is not None:
        lines.append(f"  new backend:   the gateway's Webapp on {format_address(plan.new_host, plan.new_port)}"
                     + (" (kept where it is)" if plan.keep_webapp else " (same bind and port: exposure unchanged)"))
    lines += [f"  sign-in:       {signin}", f"  .env copies:   {copy} (names only; values are never printed)"]
    if plan.generate_secret:
        lines.append("  signing key:   generate HERMES_DASHBOARD_BASIC_AUTH_SECRET so sign-ins survive restarts")
    if plan.public_url:
        lines.append(f"  public URL:    copy to webapp.public_url: {plan.public_url}")
    lines += [f"  gateway:       {_gateway_line(plan)}",
              f"  webapp bundle: {'missing → build it first' if plan.bundle_missing else 'present'}",
              f"  running turns: {'unknown' if plan.running_turns is None else plan.running_turns}"]
    if plan.shows_steps:
        steps = [s["title"] for s in plan.step_titles() if s["name"] != "preflight"]
        lines += ["", "  Steps:", *[f"    {n}. {s}" for n, s in enumerate(steps, 1)]]
    lines += ["  Any failure after step 1 undoes what was changed and verifies the old backend answers again.",
              "  After a move, clients notice: one re-sign-in (new cookies); the browser gets the Webapp instead of the old "
              "dashboard UI; old-protocol WebSocket clients and loopback page-token clients stop working."]
    return lines
