"""``hermes gateway migrate --backends``: a report, changing no service, of the serve/dashboard
background services on this machine and their current ownership.

Hermes never installs a ``hermes serve`` / ``hermes dashboard`` service itself, so every one found
here was set up by someone else: a systemd unit copied from the docs, a hand-written launchd plist,
the Nix ``hermes-backend`` unit (NixOS and Home Manager), the Docker image's s6 ``dashboard``
longrun or the Compose ``dashboard`` sidecar, a Desktop SSH ``serve`` backend, or a process started
by hand. The report says which supervisor owns each backend, by what the process runs and which
unit's ``MainPID`` it is, never by unit name (Nix calls it ``hermes-backend``). On Windows without
``wmic`` (11 24H2 and later) the scan reads the process table through psutil and names the Task
Scheduler task or Startup-folder entry that starts a backend (``gateway_migrate_backends_windows``).

The report itself never stops, restarts or kills anything, never edits or writes a service file,
unit, plist or ledger, and opens no network connection: it only runs ``ps``, reads ``/proc`` and
plists, and issues ``systemctl show`` / ``list-unit-files`` / ``launchctl print`` / ``schtasks /Query``
queries. The spawn
ledger is deliberately not read, because reading a corrupt ledger quarantines (renames) it.

Normal Hermes startup still runs first, exactly as for any other ``hermes`` command (e.g.
``hermes gateway migrate --dry-run``): it creates the ``HERMES_HOME`` layout and a default
``SOUL.md`` when missing, records the install under ``HERMES_HOME/installs/<id>/``, opens
``logs/agent.log`` / ``logs/errors.log`` and prunes ``cache/scratch``.
"""

from __future__ import annotations

import contextlib
import json
import os
import shlex
import subprocess
import sys
from dataclasses import asdict, dataclass, field
from pathlib import Path
from typing import Optional

from hermes_platform.host.facts import os_family

# Unit-name patterns for installed-but-not-running units. Running backends are found by argv, so a
# unit with any other name is still reported while it runs.
_UNIT_PATTERNS = ("hermes-serve*", "hermes-dashboard*", "hermes-backend*")
_ENABLED_STATES = frozenset({"enabled", "enabled-runtime", "linked", "linked-runtime", "static",
                             "generated", "alias", "indirect"})
_CONTAINER_CGROUP_MARKERS = ("docker", "containerd", "libpod", "kubepods", "/lxc/")
_NOT_APPLIED = "Report only: changes no service."
#: The report's last line when this home has a backend the migration can plan for (never Desktop's own).
NEXT_STEP = ("To see what moving it to the gateway would do (changes nothing): "
             "{hermes} gateway migrate --backends --apply --dry-run")

# Present ownership facts, not migration instructions.
_OWNERSHIP = {
    "systemd": "The unit was written by hand (Hermes never installs one).",
    "nix-systemd": "The unit file is generated by Nix and read-only.",
    "launchd": "The plist was written by hand (Hermes never installs one).",
    "nix-launchd": "The plist is generated by Nix and read-only.",
    "s6": "The slot is declared by the container image.",
    "container": "The process belongs to a container defined by a Compose file or run command.",
    "desktop-ssh": "It is owned by a Desktop SSH session.",
    "desktop-local": "It is owned by the Desktop app.",
    "detached": "No supervisor owns it.",
    "manual": "It was started from a shell or another program.",
    "scheduled-task": "It is started by a Task Scheduler task (Hermes never creates one).",
    "startup-folder": "An entry in the Startup folder starts exactly this command (Hermes never creates one).",
    "unknown": "Its supervisor could not be identified.",
}


@dataclass
class BackendItem:
    supervisor: str
    running: bool
    pid: Optional[int] = None
    argv: list[str] = field(default_factory=list)
    unit: Optional[str] = None  # systemd unit / launchd label / s6 slot
    scope: Optional[str] = None  # systemd "user"/"system", launchd domain
    unit_path: Optional[str] = None  # unit file / plist / s6 service dir
    state: Optional[str] = None  # systemd UnitFileState
    hermes_home: Optional[str] = None
    this_home: Optional[bool] = None
    not_applied: str = ""
    notes: list[str] = field(default_factory=list)


# --------------------------------------------------------------------------- read-only probes


def _systemctl_query(scope: Optional[str], *args: str) -> Optional[str]:
    """stdout of a read-only ``systemctl [--user] <args>``; None when unavailable or non-zero."""
    from hermes_cli.main_dashboard import _SYSTEMCTL_ERRORS, _run_probe
    cmd = ["systemctl", *(["--user"] if scope == "user" else []), *args]
    try:
        result = _run_probe(cmd, timeout=10)
    except _SYSTEMCTL_ERRORS:
        return None
    return result.stdout or "" if result.returncode == 0 else None


def _unit_properties(unit: str, scope: Optional[str]) -> dict[str, str]:
    """``FragmentPath`` / ``UnitFileState`` / ``ActiveState`` / ``Environment`` of *unit*."""
    for candidate in ([scope] if scope else ["user", "system"]):
        out = _systemctl_query(candidate, "show", unit, "--no-pager", "--property=FragmentPath",
                               "--property=UnitFileState", "--property=ActiveState", "--property=Environment")
        if out is None:
            continue
        props = dict(line.split("=", 1) for line in out.splitlines() if "=" in line)
        if props.get("FragmentPath"):
            props["Scope"] = candidate
            return props
    return {}


def _env_home(environment: str) -> Optional[str]:
    """``HERMES_HOME`` from a ``systemctl show -p Environment`` value, or None."""
    try:
        tokens = shlex.split(environment)
    except ValueError:
        tokens = environment.split()
    return next((t.split("=", 1)[1] for t in tokens if t.startswith("HERMES_HOME=")), None)


def _nix_managed(path: Optional[str]) -> bool:
    """True when *path* is (or links into) the read-only Nix store."""
    if not path:
        return False
    if path.startswith("/nix/store/"):
        return True
    with contextlib.suppress(OSError, RuntimeError):
        return str(Path(path).resolve()).startswith("/nix/store/")
    return False


def _installed_units() -> list[tuple[str, str, str]]:
    """``(unit, scope, unit_file_state)`` for every hermes-serve*/-dashboard*/-backend* unit file."""
    found: list[tuple[str, str, str]] = []
    for scope in ("user", "system"):
        out = _systemctl_query(scope, "list-unit-files", "--no-legend", "--no-pager", "--plain", *_UNIT_PATTERNS)
        for line in (out or "").splitlines():
            parts = line.split()
            if len(parts) >= 2 and parts[0].endswith(".service"):
                found.append((parts[0], scope, parts[1]))
    return found


def _on_macos() -> bool:
    return os_family() == "darwin"


def _launchd_plists() -> dict[str, tuple[str, Optional[str], list[str]]]:
    """``label -> (plist path, EnvironmentVariables.HERMES_HOME, ProgramArguments)`` across the
    launchd plist dirs (read-only)."""
    import plistlib
    from xml.parsers.expat import ExpatError

    from hermes_cli.main_dashboard import _launchd_plist_dirs
    found: dict[str, tuple[str, Optional[str], list[str]]] = {}
    for _kind, plist_dir in _launchd_plist_dirs():
        try:
            plists = sorted(plist_dir.glob("*.plist"))
        except OSError:
            continue
        for plist_path in plists:
            try:
                with open(plist_path, "rb") as f:
                    data = plistlib.load(f)
            except (OSError, ValueError, plistlib.InvalidFileException, ExpatError):
                continue
            if isinstance(data, dict) and (label := str(data.get("Label") or "").strip()):
                env, args = data.get("EnvironmentVariables"), data.get("ProgramArguments")
                home = env.get("HERMES_HOME") if isinstance(env, dict) else None
                found.setdefault(label, (str(plist_path), str(home) if home else None,
                                         [str(a) for a in args] if isinstance(args, list) else []))
    return found


def _nix_launcher_jobs(plists) -> list[tuple[str, str, list[str], Optional[int]]]:
    """Loaded jobs running the Nix ``backend.waitFor`` launcher (``nix/moduleCommon.nix``
    ``backendLauncher``), which ``exec``s hermes but names no hermes command, so
    ``_loaded_launchd_backend_jobs`` skips it."""
    from hermes_cli.gateway import _launchd_print_service_pid
    from hermes_cli.main_dashboard import _SYSTEMCTL_ERRORS
    jobs: list[tuple[str, str, list[str], Optional[int]]] = []
    for label, (_path, _home, argv) in plists.items():
        if len(argv) != 1 or not os.path.basename(argv[0]).endswith("-hermes-backend-launch"):
            continue
        uid = os.getuid()  # windows-footgun: ok — only a launchd plist reaches here
        for domain in (f"gui/{uid}", f"user/{uid}"):
            with contextlib.suppress(*_SYSTEMCTL_ERRORS):
                loaded, live_pid = _launchd_print_service_pid(domain, label)
                if loaded:
                    jobs.append((domain, label, argv, live_pid))
                    break
    return jobs


def _s6_slot(pid: int) -> Optional[tuple[str, str]]:
    """``(slot, service_dir)`` when an ancestor of *pid* is ``s6-supervise <dir>``."""
    from hermes_cli.dashboard_procs import _process_ancestors
    from hermes_cli.main_dashboard import _dashboard_cmdline_for_pid
    for ancestor in _process_ancestors(pid):
        argv = _dashboard_cmdline_for_pid(ancestor) or []
        if argv and os.path.basename(argv[0]) == "s6-supervise":
            service_dir = argv[1] if len(argv) > 1 else ""
            return os.path.basename(service_dir.rstrip("/")) or "?", service_dir
    return None


def _container_cgroup(pid: int) -> bool:
    from hermes_cli.main_dashboard import _pid_unified_cgroup_entries
    return any(m in entry for entry in _pid_unified_cgroup_entries(pid) for m in _CONTAINER_CGROUP_MARKERS)


def _in_container() -> bool:
    from hermes_cli._startup_fast import is_container_startup_environment
    return is_container_startup_environment()


# --------------------------------------------------------------------------- classification


def _running_backends() -> list[tuple[int, str]]:
    """``(pid, command)`` of every live serve/dashboard (argv scan only, never the spawn ledger)."""
    from hermes_cli.dashboard_procs import _iter_process_table
    from hermes_cli.update_cmd_windows import _hermes_holder_subcommand
    try:
        rows = _iter_process_table()
        if not rows and _windows_without_wmic():  # Windows 11 24H2+: psutil reads the same table
            from hermes_cli.gateway_migrate_backends_windows import process_rows
            rows = process_rows()
    except (FileNotFoundError, subprocess.TimeoutExpired, OSError):  # same failures the update sweep tolerates
        return []
    recover = os_family() == "darwin"  # only macOS ``ps`` loses the launcher's argv boundaries
    found = []
    # This process is listed too when it is a backend itself: a `hermes dashboard` that runs the scan for
    # its own pages is the backend being asked about. The CLI's own row (`hermes gateway migrate ...`)
    # never matches, so the report lists exactly what it listed before.
    for pid, cmd in rows:
        if _hermes_holder_subcommand(cmd) in ("serve", "dashboard"):
            found.append((pid, cmd))
        elif recover and " -c " in cmd and "hermes" in cmd and (exact := _exact_argv(pid)) and \
                _hermes_holder_subcommand(shlex.join(exact)) in ("serve", "dashboard"):
            found.append((pid, shlex.join(exact)))
    if _windows_without_wmic():
        from hermes_cli.gateway_migrate_backends_windows import drop_launchers
        found = drop_launchers(found)  # hermes.exe runs the backend as a child with the same argv
    return found


def _windows_without_wmic() -> bool:
    """Windows without ``wmic`` (11 24H2 and later): only there the scan and the ownership come from
    psutil and the Windows module. Where wmic works, the report reads and prints what main does."""
    if os_family() != "win32":
        return False
    from hermes_cli.gateway_migrate_backends_windows import wmic_missing
    return wmic_missing()


def _exact_argv(pid: int) -> Optional[list[str]]:
    """*pid*'s argv exactly as exec'd, or None when unreadable.

    macOS ``ps`` prints a process's arguments joined by spaces and spells newlines ``\\012``, so the
    install launcher's ``python -I -c <multi-line bootstrap> dashboard ...`` loses the boundaries of
    its inline source and the token matcher cannot see the subcommand behind it. The kernel's argv
    (psutil: ``KERN_PROCARGS2``) keeps them. Linux ``ps`` text still matches, so it is never read there."""
    with contextlib.suppress(Exception):
        import psutil
        argv = psutil.Process(pid).cmdline()
        return [str(a) for a in argv] if argv else None
    return None


def _classify_running(pid: int, command: str, *, launchd_jobs, plists, ssh_pids, desktop_pids,
                      seen_units: set[str]) -> BackendItem:
    from hermes_cli._startup_fast import is_desktop_ssh_backend_argv
    from hermes_cli.dashboard_procs import _is_desktop_local_serve_cmdline, _process_ancestors, _process_ppid
    from hermes_cli.main_dashboard import (
        _dashboard_cmdline_for_pid,
        _launchd_job_owning_backend,
        _systemd_owner_for_pid,
    )
    from hermes_cli.update_cmd_windows import _hermes_holder_subcommand
    argv = _dashboard_cmdline_for_pid(pid)
    if argv and os_family() == "darwin" and _hermes_holder_subcommand(shlex.join(argv)) is None:
        argv = None  # macOS ``ps`` text lost the launcher's argv boundaries; *command* is the exact argv then
    if not argv and _windows_without_wmic():
        from hermes_cli.gateway_migrate_backends_windows import argv_of
        argv = argv_of(pid)
    exact_argv = argv
    if not argv:
        try:
            argv = shlex.split(command)
        except ValueError:
            argv = command.split()
    item = BackendItem(supervisor="unknown", running=True, pid=pid, argv=list(argv))
    if owner := _systemd_owner_for_pid(pid):
        unit, scope = owner
        props = _unit_properties(unit, scope)
        seen_units.add(f"{props.get('Scope', scope)}:{unit}")
        item.unit, item.scope = unit, props.get("Scope", scope)
        item.unit_path, item.state = props.get("FragmentPath") or None, props.get("UnitFileState") or None
        item.supervisor = "nix-systemd" if _nix_managed(item.unit_path) else "systemd"
    elif slot := _s6_slot(pid):
        item.supervisor, item.unit = "s6", slot[0]
        item.unit_path = slot[1] if os.path.isabs(slot[1]) else None  # s6-supervise runs from the scandir
        if _container_cgroup(pid):
            item.notes.append("Runs inside a container (seen from the host).")
    elif launchd_jobs and (job := _launchd_job_owning_backend(pid, argv, launchd_jobs,
                                                                ancestors=_process_ancestors(pid))):
        domain, label, _live = job
        item.unit, item.scope = label, domain
        item.unit_path, item.hermes_home, _args = plists.get(label, (None, None, []))
        item.supervisor = "nix-launchd" if _nix_managed(item.unit_path) else "launchd"
    elif pid in ssh_pids or is_desktop_ssh_backend_argv(argv):
        item.supervisor = "desktop-ssh"
    elif pid in desktop_pids or _is_desktop_local_serve_cmdline(command):
        item.supervisor = "desktop-local"
    elif _container_cgroup(pid) or _in_container():
        item.supervisor = "container"
    elif os_family() == "win32":
        if _windows_without_wmic():
            from hermes_cli.gateway_migrate_backends_windows import supervisor
            item.supervisor, item.unit, item.unit_path = supervisor(pid, item.argv)
    else:
        ppid = _process_ppid(pid)
        # On macOS launchd is the parent of every job and every orphan: ppid 1 proves no supervisor.
        orphan = ppid is not None and ppid <= 1 and os_family() != "darwin"
        item.supervisor = "detached" if orphan else ("manual" if ppid and ppid > 1 else "unknown")
    with contextlib.suppress(Exception):
        from hermes_cli.dashboard_procs import _hermes_home_for_pid
        home = (_hermes_home_for_pid(pid, argv_reader=lambda _: exact_argv) if _windows_without_wmic() and exact_argv
                else _hermes_home_for_pid(pid))
        item.hermes_home = home or item.hermes_home
    return item


def _finish(item: BackendItem, own_home: str) -> BackendItem:
    from hermes_cli.dashboard_procs import _normalized_home_for_compare
    from hermes_cli.profiles_run_elsewhere import run_elsewhere_for_home
    from hermes_cli.update_cmd_fleet import _is_serve_or_dashboard_unit
    item.not_applied = _NOT_APPLIED
    item.notes.append(_OWNERSHIP[item.supervisor])
    if item.hermes_home:
        item.this_home = _normalized_home_for_compare(item.hermes_home) == _normalized_home_for_compare(own_home)
        if (elsewhere := run_elsewhere_for_home(item.hermes_home)) is not None:
            # The backend a plugin runs for a profile can be a process of this machine, found like any other.
            item.notes.append(elsewhere.backend_note())
    if item.supervisor in ("systemd", "nix-systemd") and item.unit and not _is_serve_or_dashboard_unit(item.unit):
        item.notes.append("`hermes update`'s systemd unit pass matches only hermes-gateway*/hermes-serve*/"
                          f"hermes-dashboard* names, so it does not list {item.unit}.")
    if item.state == "disabled":
        item.notes.append("The unit is disabled: it does not start at boot.")
    return item


def collect_backends() -> list[BackendItem]:
    """Every serve/dashboard backend on this machine (running, or installed and enabled). Read-only."""
    from hermes_cli.dashboard_procs import _exclude_pids_from_env, _lock_owned_serve_pids
    from hermes_cli.main_dashboard import _loaded_launchd_backend_jobs
    from hermes_constants import get_hermes_home
    if os_family().startswith("linux"):
        # Without the user bus env (a headless shell) `systemctl --user` cannot prove a user unit owns
        # its dashboard, which is then reported a second time as a manual backend.
        from hermes_cli.gateway import _ensure_user_systemd_env
        _ensure_user_systemd_env()
    own_home = str(get_hermes_home())
    launchd_jobs = _loaded_launchd_backend_jobs()  # empty off macOS
    # ``_launchd_plist_dirs`` returns its dirs on every OS, so only scan them, and only look
    # for Nix launcher jobs (``launchctl print``), when launchd can exist.
    plists = _launchd_plists() if launchd_jobs or _on_macos() else {}
    if _on_macos():
        launchd_jobs = launchd_jobs + _nix_launcher_jobs(plists)
    seen_units: set[str] = set()
    items = [_classify_running(pid, cmd, launchd_jobs=launchd_jobs, plists=plists,
                               ssh_pids=_lock_owned_serve_pids(), desktop_pids=_exclude_pids_from_env(),
                               seen_units=seen_units)
             for pid, cmd in _running_backends()]
    running_labels = {i.unit for i in items if i.supervisor in ("launchd", "nix-launchd")}
    for unit, scope, state in _installed_units():
        if f"{scope}:{unit}" in seen_units or state not in _ENABLED_STATES:
            continue
        props = _unit_properties(unit, scope)
        path = props.get("FragmentPath") or None
        items.append(BackendItem(supervisor="nix-systemd" if _nix_managed(path) else "systemd", running=False,
                                 unit=unit, scope=scope, unit_path=path, state=state,
                                 hermes_home=_env_home(props.get("Environment", ""))))
    for domain, label, argv, _live_pid in launchd_jobs:
        if label in running_labels:
            continue
        path, home, _args = plists.get(label, (None, None, []))
        items.append(BackendItem(supervisor="nix-launchd" if _nix_managed(path) else "launchd", running=False,
                                 argv=list(argv), unit=label, scope=domain, unit_path=path, hermes_home=home))
    return [_finish(item, own_home) for item in items]


# --------------------------------------------------------------------------- output


def _display_argv(argv: list[str]) -> str:
    """*argv* for the macOS report: the install launcher's multi-line inline source is a placeholder.
    Elsewhere the ``runs:`` line is the whole argv, as before (Windows spells it as a Windows command)."""
    return shlex.join("<inline launcher source>" if i and argv[i - 1] == "-c" and "\n" in a else a
                      for i, a in enumerate(argv))


def format_report(items: list[BackendItem]) -> list[str]:
    lines = ["Serve/dashboard background services (report only; nothing was changed)", ""]
    if not items:
        return lines + ["  No running or enabled hermes serve / hermes dashboard backend found."]
    for item in items:
        head = f"PID {item.pid}" if item.pid else "not running"
        where = f" {item.unit}" if item.unit else ""
        scope = f" ({item.scope})" if item.scope else ""
        lines.append(f"• {item.supervisor}{where}{scope}: {head}")
        if item.argv:
            runs = subprocess.list2cmdline(item.argv) if _windows_without_wmic() else \
                _display_argv(item.argv) if os_family() == "darwin" else shlex.join(item.argv)
            lines.append(f"    runs:    {runs}")
        if item.unit_path:
            lines.append(f"    file:    {item.unit_path}")
        if item.state:
            lines.append(f"    state:   {item.state}")
        if item.hermes_home:
            mine = " (this HERMES_HOME)" if item.this_home else ""
            lines.append(f"    home:    {item.hermes_home}{mine}")
        lines.append(f"    report:  {item.not_applied}")
        lines.extend(f"    note:    {n}" for n in item.notes)
    if any(i.this_home and i.supervisor not in ("desktop-ssh", "desktop-local") for i in items):
        from hermes_cli.gateway_migrate_backends_plan import hermes_command
        from hermes_cli.profiles_run_elsewhere import run_elsewhere_for_home
        from hermes_constants import get_hermes_home
        home = str(get_hermes_home())
        if run_elsewhere_for_home(home) is None:  # a plugin runs this profile elsewhere: no move to offer
            lines += ["", NEXT_STEP.format(hermes=hermes_command(home, powershell=os.name == "nt"))]
    return lines


def cmd_backends_report(args) -> None:
    """``hermes gateway migrate --backends [--dry-run] [--json]``. Exits 0 on valid arguments, even when a scan fails."""
    if getattr(args, "yes", False) or getattr(args, "multiplex", False):
        print("✗ --backends is a read-only report; it cannot be combined with --yes or --multiplex.",
              file=sys.stderr)
        sys.exit(2)
    items = collect_backends()
    if getattr(args, "json", False):
        print(json.dumps({"applied": False, "backends": [asdict(i) for i in items]}, indent=2))
        return
    print("\n".join(format_report(items)))
