"""Read-only binding checks; unknown supervisor syntax is not profile absence.

These checks recognize the installed Hermes launch formats, not arbitrary shell
programs. Manager-loaded values take precedence over filenames and disk copies.
"""
from __future__ import annotations

import json
import os
from pathlib import Path
import re
import shlex
import stat
from typing import NoReturn


SYSTEMD_IDENTITY_PROPERTIES = (
    "User", "DynamicUser", "ExecStart", "Environment", "EnvironmentFiles",
    "PassEnvironment", "UnsetEnvironment", "PAMName", "RootDirectory", "RootImage",
    "ExecStartPre", "ExecCondition", "DropInPaths",
)
# `systemctl show --all` (systemd 259) prints no line at all for these when the
# list is empty, so their absence carries no identity uncertainty.
SYSTEMD_OMITTED_WHEN_EMPTY = ("EnvironmentFiles", "ExecStartPre", "ExecCondition")


class Unverified(ValueError):
    """``str()`` stays the reason code callers map; ``check`` names the rule the definition broke."""

    def __init__(self, check: str):
        super().__init__("service_identity_unverified")
        self.check = check


def _unverified(check: str) -> NoReturn:
    raise Unverified(check)


def _absolute(value: str) -> Path:
    if not value or not Path(value).is_absolute():
        _unverified(f"not an absolute path: {value!r}")
    return Path(value).resolve()


class ForeignRoot(ValueError):
    """The service serves another install root (a different HOME), not another profile of ours."""

    def __init__(self, theirs: Path):
        super().__init__("foreign_root")
        self.check = f"the service runs another Hermes home: {theirs}"


def _install_root(home: Path) -> Path:
    # <root>/.hermes or <root>/.hermes/profiles/<name>: the root is the HOME that anchors it.
    parts = home.parts
    if len(parts) >= 3 and parts[-3] == ".hermes" and parts[-2] == "profiles":
        return home.parents[2]
    return home.parent


def verify_home(home: Path, configured: str) -> None:
    ours, theirs = home.resolve(), _absolute(configured)
    if os.path.normcase(str(theirs)) == os.path.normcase(str(ours)):
        return
    if os.path.normcase(str(_install_root(theirs))) != os.path.normcase(str(_install_root(ours))):
        raise ForeignRoot(theirs)
    raise ValueError("profile_mismatch")


# ``python``, ``pythonw``, ``python3``, ``python3.12`` (``.exe`` on Windows): an interpreter launch.
_PYTHON_EXECUTABLE = re.compile(r"python(?:w|\d+(?:\.\d+)*)?(?:\.exe)?")


def _own_store_launcher(executable: str) -> bool:
    """Whether ``executable`` is a launcher ``installation_command`` writes for THIS install root
    (root = gateway.PROJECT_ROOT), never another checkout's: the store's ``<root>/.hermes/bin/hermes``,
    or a macOS bundle's own ``bin/hermes`` (``_launchers.sealed_service_launcher``)."""
    from hermes_cli import gateway
    from hermes_cli._launchers import sealed_service_launcher
    root = Path(gateway.PROJECT_ROOT).resolve()
    ours = (root / ".hermes" / "bin" / "hermes", sealed_service_launcher(root))
    actual = os.path.normcase(str(Path(executable).resolve()))
    return any(actual == os.path.normcase(str(launcher)) for launcher in ours if launcher is not None)


def _launch_module(argv: list[str], *, legacy: bool = True) -> tuple[str, list[str]] | None:
    """``(module, its argv)`` for the module launches the installer persists: ``python -m``, or
    ``_launchers.installation_command``'s two forms for THIS install root (gateway.PROJECT_ROOT): its
    launcher's ``--run-module`` (``_own_store_launcher``), or ``runtime_command``'s inline bootstrap
    regenerated byte for byte. A launcher or bootstrap of another checkout is not ours. None otherwise."""
    from hermes_cli import gateway
    from hermes_cli._launchers import runtime_command
    root = Path(gateway.PROJECT_ROOT).resolve()
    executable = Path(argv[0]).name.lower() if argv else ""
    if _PYTHON_EXECUTABLE.fullmatch(executable):
        # ``python -m`` is the legacy unwrapped plist form; no installer put it inside the osascript wrapper.
        if legacy and argv[1:2] == ["-m"] and len(argv) > 2:
            return argv[2], argv[3:]
        if argv[1:3] == ["-I", "-c"] and len(argv) > 3:
            module = next((name for name in ("hermes_cli.stderr_timestamp", "hermes_cli.main")
                           if runtime_command(root, module=name, python=argv[0])[3] == argv[3]), None)
            return (module, argv[4:]) if module else None
    elif argv[1:2] == ["--run-module"] and len(argv) > 2 and _own_store_launcher(argv[0]):
        return argv[2], argv[3:]
    return None


def verify_gateway_argv(argv: list[str], home: Path, *, wrapped: bool = False) -> None:
    """``wrapped``: a launcher wrapper (the osascript Local Network wrapper) was already stripped, so
    only this root's installer forms count: no legacy ``python -m``, and a ``hermes`` launcher must be
    one this root's installer writes (``_own_store_launcher``). The stderr-timestamp wrapper holds its inner
    ``hermes`` to the same rule. A bare unwrapped ``hermes`` keeps verifying by name, as older
    systemd/schtasks/launchd definitions persisted it (binding those is a separate change)."""
    from gateway.status import looks_like_gateway_command_line

    # The installer wraps launchd stderr with this fixed, non-shell module.
    wrapper = _launch_module(argv, legacy=not wrapped)
    own_launcher_only = wrapped
    if wrapper is not None and wrapper[0] == "hermes_cli.stderr_timestamp":
        args = wrapper[1]
        if len(args) < 4 or args[0] != "--error-log" or args[2] != "--":
            _unverified("the stderr-timestamp wrapper's arguments are not the installer's")
        argv, own_launcher_only = args[3:], True
    if not argv or not looks_like_gateway_command_line(subprocess_command(argv)):
        _unverified("the command is not a Hermes gateway command")
    executable = Path(argv[0]).name.lower()
    if _PYTHON_EXECUTABLE.fullmatch(executable):
        entry = _launch_module(argv, legacy=not wrapped)
        if entry is None or entry[0] != "hermes_cli.main":
            _unverified("the Python command is not this install's -m hermes_cli.main")
        args = entry[1]
    elif executable in {"hermes", "hermes.exe"} and (not own_launcher_only or _own_store_launcher(argv[0])):
        args = argv[1:]
    else:
        _unverified(f"{Path(argv[0]).name} is not this install's Python or hermes launcher")
    profiles = []
    filtered = []
    index = 0
    while index < len(args):
        token = args[index]
        if token in {"--profile", "-p"}:
            index += 1
            if index == len(args):
                _unverified("--profile has no value")
            profiles.append(args[index])
        elif token.startswith("--profile="):
            profiles.append(token.split("=", 1)[1])
        else:
            filtered.append(token)
        index += 1
    if len(profiles) > 1:
        _unverified("the command names more than one --profile")
    if profiles:
        # An explicit selector must agree with the pinned environment. This
        # preserves custom-root profiles without borrowing the caller's root.
        from hermes_constants import profile_name_for_home
        expected = profile_name_for_home(home) or (home.name if home.parent.name == "profiles" else "default")
        if profiles[0] != expected:
            raise ValueError("profile_mismatch")
    if filtered[:2] != ["gateway", "run"] or any(
        arg not in {"--quiet", "--external-supervisor"} for arg in filtered[2:]
    ):
        _unverified(f"the command runs {' '.join(filtered) or 'nothing'!r}, not gateway run")


def subprocess_command(argv: list[str]) -> str:
    # The canonical matcher is quote-aware on both hosts.
    import subprocess
    return subprocess.list2cmdline(argv)


def environment_pairs(value: str) -> dict[str, str]:
    # systemctl uses C escapes for unusual bytes. Do not silently reinterpret
    # those with shell escaping (not the same grammar).
    if "\\" in value:
        _unverified("the manager environment uses C escapes")
    result = {}
    for item in shlex.split(value):
        key, separator, val = item.partition("=")
        if not separator:
            _unverified("a manager environment entry has no =")
        result[key] = val
    return result


def apply_unset_environment(env: dict[str, str], value: str) -> dict[str, str]:
    """systemd's ``UnsetEnvironment=`` *value* (as ``systemctl show`` prints it), applied last to *env*: a
    ``NAME`` drops the variable, a ``NAME=VALUE`` only that exact assignment (systemd.exec(5))."""
    for item in shlex.split(value):
        key, sep, val = item.partition("=")
        if not sep or env.get(key) == val:
            env.pop(key, None)
    return env


def verify_systemd(props: dict[str, str], manager_env: str, home: Path, *, system: bool) -> None:
    import pwd

    # systemd 259 omits empty exec-command lists and EnvironmentFiles from
    # `show --all` output entirely; an omitted list is empty, not unknown.
    props = {**{key: "" for key in SYSTEMD_OMITTED_WHEN_EMPTY}, **props}
    if not all(key in props for key in SYSTEMD_IDENTITY_PROPERTIES):
        _unverified("systemctl show omitted an identity property")
    # These can change the execution account, environment, mount namespace, or
    # definitions at start time; show does not expose their resulting identity.
    if props["DynamicUser"] != "no" or any(props[key] for key in (
        "EnvironmentFiles", "PAMName", "RootDirectory", "RootImage", "ExecStartPre", "ExecCondition",
    )):
        _unverified("the unit can change its identity at start (DynamicUser, EnvironmentFiles, PAMName, "
                    "RootDirectory, RootImage, ExecStartPre or ExecCondition)")
    user = props["User"]
    uid = os.getuid()  # windows-footgun: ok — native systemd only
    if user:
        try:
            service_uid = int(user) if user.isdecimal() else pwd.getpwnam(user).pw_uid
        except KeyError:
            _unverified(f"the unit's User {user!r} does not exist")
    else:
        service_uid = 0 if system else uid
    if service_uid != uid:
        raise ValueError("service_account_mismatch")
    inherited = environment_pairs(manager_env)
    env = inherited if not system else {k: v for k, v in inherited.items() if k in props["PassEnvironment"].split()}
    env.update(environment_pairs(props["Environment"]))
    apply_unset_environment(env, props["UnsetEnvironment"])
    configured = env.get("HERMES_HOME", "").strip()
    if not configured:
        configured = str(_absolute(env.get("HOME") or pwd.getpwuid(uid).pw_dir) / ".hermes")
    verify_home(home, configured)
    match = re.fullmatch(r"\{ path=(.*?) ; argv\[\]=(.*?) ; ignore_errors=(?:yes|no) ;(?:.*?)\}", props["ExecStart"])
    if not match or any(char in match[2] for char in ("$", "\\", "{", "}")):
        _unverified("ExecStart is not a plain command line")
    argv = shlex.split(match[2])
    if not argv or match[1] != argv[0]:
        _unverified("ExecStart's path and argv[0] differ")
    verify_gateway_argv(argv, home)


def _verify_launchd_argv(argv: list[str], home: Path) -> None:
    command, wrapped = _launchd_command(argv)
    verify_gateway_argv(command, home, wrapped=wrapped)


def _launchd_command(argv: list[str]) -> tuple[list[str], bool]:
    """``(command, wrapped)``: the command the launchd job runs, and whether it came out of the Local
    Network wrapper (gateway_launchd.launchd_program_arguments, #71206). The wrapper is accepted only when
    the installer regenerates it byte for byte from the inner command and the two log paths it carries,
    so no shell operator, substitution, extra JXA or foreign osascript rides along."""
    if argv[:1] != ["/usr/bin/osascript"]:
        return argv, False
    from hermes_cli.gateway_launchd import launchd_program_arguments
    # Recover the inputs, then let the installer rebuild the whole argv: the comparison is the check.
    script, opener = argv[-1], "$.system("
    try:
        shell = json.JSONDecoder().raw_decode(script, script.index(opener) + len(opener))[0]
        tokens = shlex.split(shell) if isinstance(shell, str) else []
    except ValueError:
        tokens = []
    if len(tokens) < 6 or tokens[0] != "exec" or tokens[-4] != ">>" or tokens[-2] != "2>>":
        _unverified("the osascript wrapper is not the installer's")
    command = tokens[1:-4]
    if launchd_program_arguments(command, Path(tokens[-3]), Path(tokens[-1])) != argv:
        _unverified("the osascript wrapper is not the installer's")
    return command, True


def verify_launchd_loaded(output: str, home: Path, *, uid: int, username: str) -> None:
    # Only the job's own blocks, never inherited/default environments or a
    # different job embedded in launchctl diagnostic text.
    def block(name):
        found = re.findall(r"^\t" + name + r" = \{\n(.*?)^\t\}", output, re.MULTILINE | re.DOTALL)
        if len(found) != 1:
            _unverified(f"launchctl printed {len(found)} {name} blocks")
        return found[0].splitlines()

    for key, expected in (("uid", str(uid)), ("username", username)):
        values = re.findall(r"^\t" + key + r" = (.+)$", output, re.MULTILINE)
        if values and values != [expected]:
            raise ValueError("service_account_mismatch")
    env = {}
    for line in block("environment"):
        if not line.strip():
            continue
        key, sep, value = line.strip().partition(" => ")
        if not sep or key in env:
            _unverified("the job environment has a malformed or repeated entry")
        env[key] = value
    verify_home(home, env.get("HERMES_HOME", ""))
    if home.parent.name != "profiles" and not env.get("HERMES_SUPERVISED_CHILD"):
        _unverified("the job does not set HERMES_SUPERVISED_CHILD")
    argv = [line.strip() for line in block("arguments")]
    programs = re.findall(r"^\tprogram = (.+)$", output, re.MULTILINE)
    if len(programs) != 1 or not argv or programs[0] != argv[0]:
        _unverified("the job's program and arguments disagree")
    _verify_launchd_argv(argv, home)


def verify_launchd_plist(definition: dict, label: str, home: Path) -> None:
    if definition.get("Label") != label:
        _unverified("the plist Label differs")
    if definition.get("Disabled"):
        raise ValueError("service_disabled")
    if definition.get("UserName") or definition.get("GroupName") or definition.get("RootDirectory"):
        _unverified("the plist sets UserName, GroupName or RootDirectory")
    env = definition.get("EnvironmentVariables", {})
    if not isinstance(env, dict):
        _unverified("the plist EnvironmentVariables is not a dictionary")
    verify_home(home, env.get("HERMES_HOME", ""))
    argv = definition.get("ProgramArguments")
    if not isinstance(argv, list) or not all(isinstance(arg, str) for arg in argv):
        _unverified("the plist ProgramArguments is not a list of strings")
    if definition.get("Program", argv[0] if argv else None) != (argv[0] if argv else None):
        _unverified("the plist Program differs from ProgramArguments[0]")
    _verify_launchd_argv(argv, home)
    if home.parent.name != "profiles" and not env.get("HERMES_SUPERVISED_CHILD"):
        _unverified("the job does not set HERMES_SUPERVISED_CHILD")


def read_definition(path: Path) -> bytes:
    # Nonblocking open precedes fstat: a FIFO replacement must not consume the
    # entire startup deadline waiting for a writer. Symlinked installs work.
    fd = os.open(path, os.O_RDONLY | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_BINARY", 0))
    with os.fdopen(fd, "rb") as stream:
        info = os.fstat(stream.fileno())
        if not stat.S_ISREG(info.st_mode) or info.st_size > 1024 * 1024:
            _unverified(f"{path} is not a regular file under 1 MiB")
        value = stream.read(1024 * 1024 + 1)
        if len(value) > 1024 * 1024:
            _unverified(f"{path} is larger than 1 MiB")
        return value


def launcher_text(raw: bytes) -> str:
    """Current .vbs launchers are UTF-16 with a BOM (wscript.exe reads a BOM-less script in the ANSI
    code page); launchers written by older versions, and every other service definition, are UTF-8.
    Undecodable bytes raise ``ValueError``."""
    if raw[:2] in (b"\xff\xfe", b"\xfe\xff"):
        try:
            return raw.decode("utf-16")
        except UnicodeDecodeError:
            _unverified("the launcher is not valid UTF-16")
    try:
        return raw.decode("utf-8-sig")
    except UnicodeDecodeError:
        _unverified("the launcher is neither UTF-16 with a BOM nor UTF-8")


# A VBS string literal (doubled quotes escape, an unterminated one runs to the end), or a ' / REM comment.
# Literals match first, so an apostrophe inside a string never starts a comment.
_VBS_VALUE = re.compile(r'"(?:[^"]|"")*(?:"|$)|(?P<comment>(?:\'|(?<![\w.])(?i:REM)\b).*$)')


def _masked_literals(line: str) -> str:
    # A customised launcher line may assign an opaque credential the generic redactor can't recognise
    # (``env.Item("S3_SECRET") = "..."``), or carry one in a comment: keep the names, never the values.
    def mask(found: re.Match[str]) -> str:
        if found["comment"] is not None:
            return "' ***" if found["comment"].startswith("'") else found["comment"][:3] + " ***"
        return found[0] if line[:found.start()].endswith(("Item(", "Environment(")) else '"***"'
    return _VBS_VALUE.sub(mask, line)


# The launcher's lines after its env block; None slots hold values, which _vbs_identity checks one by one.
_LAUNCHER_TAIL = ('existing_pp = env.Item("PYTHONPATH")', 'If Len(existing_pp) > 0 Then', None, 'Else', None,
                  'End If', None, None)
# The waiting launcher (#146976) maps stop exits to 0 (the owned-exit line is shape-checked by
# _vbs_identity) and quits with the gateway's code.
_WAITING_LAUNCHER_TAIL = (*_LAUNCHER_TAIL, "If code = 78 Then code = 0", None, "WScript.Quit code")


def launcher_pid_file(hermes_home: str) -> str:
    """The ``gateway.pid`` the waiting launcher checks for an owned exit 1: ``gateway.status._get_pid_path``
    of the home it sets (a Windows path; joined as text so both hosts render the same line)."""
    return hermes_home.rstrip("\\/") + "\\gateway.pid"


def _tail_mismatch(tail: list[str], waits: bool = False) -> int | None:
    """Offset of the first tail line that breaks the template's shape, or None when it holds."""
    shape = _WAITING_LAUNCHER_TAIL if waits else _LAUNCHER_TAIL
    for offset, expected in enumerate(shape):
        if offset == len(tail) or expected not in (None, tail[offset]):
            return offset
    return len(shape) if len(tail) > len(shape) else None


def _vbs_identity(script: str) -> tuple[str, list[str]]:
    # Recognize the vendor's complete template, not a HERMES_HOME substring
    # inside an arbitrary executable script. Doubled quotes are VB literals.
    literal = r'"(?:[^"\r\n]|"")*"'
    lines = script.splitlines()
    if len(lines) < 16 or not lines[0].startswith("' "):
        _unverified("the launcher does not start with the installer's header")
    # Two installer generations: the waiting launcher (``Dim ... code``, #146976) and the one installs
    # made before it still run (returns at once) until the next install or update re-renders it.
    waits = lines[2:3] == ["Dim sh, env, existing_pp, code"]
    fixed = ["Option Explicit", "Dim sh, env, existing_pp, code" if waits else "Dim sh, env, existing_pp",
             'Set sh = CreateObject("WScript.Shell")', 'Set env = sh.Environment("PROCESS")']
    if lines[1:5] != fixed:
        _unverified("the launcher's setup lines are not the installer's")
    env = {}
    index = 5
    while index < len(lines):
        match = re.fullmatch(r'env.Item\("([A-Z_]+)"\) = (' + literal + ')', lines[index])
        if not match:
            break
        if match[1] not in {"HERMES_HOME", "HERMES_SUPERVISED_CHILD", "HERMES_GATEWAY_DETACHED", "PYTHONIOENCODING", "VIRTUAL_ENV"} or match[1] in env:
            _unverified(f"the launcher sets {match[1]} twice or sets an unexpected variable")
        env[match[1]] = match[2][1:-1].replace('""', '"')
        index += 1
    tail = lines[index:]
    mismatch = _tail_mismatch(tail, waits)
    if mismatch is not None:
        index += mismatch
        line = _masked_literals(lines[index]) if index < len(lines) else "<end of file>"
        _unverified(f"launcher line {index + 1} is not the installer's: {line[:120]!r}")
    if not re.fullmatch(r'  env.Item\("PYTHONPATH"\) = ' + literal + r' & existing_pp', tail[2]) or not re.fullmatch(r'  env.Item\("PYTHONPATH"\) = ' + literal, tail[4]):
        _unverified("the launcher's PYTHONPATH lines are not the installer's")
    if not re.fullmatch(r'sh.CurrentDirectory = ' + literal, tail[6]):
        _unverified("the launcher's working-directory line is not the installer's")
    run = re.fullmatch(r'code = sh\.Run\((' + literal + r'), 0, True\)' if waits else r'sh.Run (' + literal + r'), 0, False',
                       tail[7])
    if not run or not env.get("HERMES_SUPERVISED_CHILD"):
        _unverified("the launcher has no Run line or does not set HERMES_SUPERVISED_CHILD")
    if waits:
        owned = re.fullmatch(r'If code = 1 And CreateObject\("Scripting\.FileSystemObject"\)\.FileExists\(('
                             + literal + r')\) Then code = 0', tail[9])
        pid_file = owned[1][1:-1].replace('""', '"') if owned else None
        if pid_file is None or pid_file != launcher_pid_file(env.get("HERMES_HOME", "")):
            _unverified("the launcher's exit mapping is not the installer's")
    command = run[1][1:-1].replace('""', '"')
    if "%" in command or "%" in env.get("HERMES_HOME", ""):
        _unverified("the launcher command or HERMES_HOME contains %")
    # The template uses list2cmdline, with no embedded executable quote escapes.
    argv = [part.strip('"') for part in shlex.split(command, posix=False)]
    return env.get("HERMES_HOME", ""), argv


class LogonOnlyTask(Exception):
    """The task is the one installers before the wscript launcher registered for this home: a logon
    trigger whose single action is the installer's own ``.cmd`` wrapper. It starts the gateway at
    logon and nothing else, so it is neither run nor a reason to refuse this home."""


def _is_own_cmd_wrapper(command: str, arguments: str, home: Path, task_name: str) -> bool:
    """Whether a task action is exactly ``<home>/gateway-service/<task>.cmd`` with no arguments, the
    action ``schtasks /Create /TR <wrapper>`` registered before the task ran wscript.exe."""
    from hermes_cli.gateway_windows import _sanitize_filename
    value = command.strip()
    if len(value) >= 2 and value[0] == value[-1] == '"':  # /TR quoted a wrapper path with spaces
        value = value[1:-1]
    if arguments.strip() or not Path(value).is_absolute():
        return False
    wrapper = home.resolve() / "gateway-service" / f"{_sanitize_filename(task_name)}.cmd"
    # The file name as registered, in the folder this home resolves to: the wrapper need not exist.
    return (os.path.normcase(Path(value).name) == os.path.normcase(wrapper.name)
            and os.path.normcase(str(Path(value).parent.resolve())) == os.path.normcase(str(wrapper.parent)))


def _starts_at_logon_only(task, ns: dict[str, str]) -> bool:
    """One plain logon trigger and no restart policy: Task Scheduler starts the action at logon, once."""
    triggers = task.find("t:Triggers", ns)
    return (triggers is not None and len(triggers) == 1 and triggers[0].tag == '{' + ns['t'] + '}LogonTrigger'
            and triggers[0].find("t:Repetition", ns) is None
            and task.find("t:Settings/t:RestartOnFailure", ns) is None)


def verify_windows_task(xml: str | bytes, home: Path, account: str, sid: str, *,
                        task_name: str | None = None) -> None:
    """``task_name``: the task queried. With it, this home's pre-wscript registration raises
    ``LogonOnlyTask`` once its principal and enabled state have passed, instead of being refused."""
    import xml.etree.ElementTree as ET

    try:
        task = ET.fromstring(xml)
    except ET.ParseError:
        _unverified("the task XML does not parse")
    ns = {"t": "http://schemas.microsoft.com/windows/2004/02/mit/task"}
    principals = task.findall("t:Principals/t:Principal", ns)
    actions = task.find("t:Actions", ns)
    if len(principals) != 1 or actions is None or len(actions) != 1:
        _unverified(f"the task has {len(principals)} principal(s) and "
                    f"{0 if actions is None else len(actions)} action(s), not one each")
    principal = principals[0]
    user = principal.findtext("t:UserId", "", ns)
    if not user or not account or not sid or principal.find("t:GroupId", ns) is not None:
        _unverified("the task principal names no user, or names a group")
    if user.casefold() not in {account.casefold(), sid.casefold()}:
        raise ValueError("service_account_mismatch")
    # schtasks /Query /XML omits elements that hold the Windows default (#139013): an absent RunLevel
    # is least privilege and an absent Enabled is enabled. An explicit other value is still refused.
    if principal.findtext("t:RunLevel", "LeastPrivilege", ns) != "LeastPrivilege" or actions.get("Context") != principal.get("id"):
        _unverified(f"the task RunLevel is {principal.findtext('t:RunLevel', 'LeastPrivilege', ns)!r} and its "
                    f"action context is {actions.get('Context')!r}; expected LeastPrivilege and {principal.get('id')!r}")
    if task.findtext("t:Settings/t:Enabled", "true", ns) != "true":
        raise ValueError("service_disabled")
    action = actions[0]
    if task_name and action.tag == '{' + ns['t'] + '}Exec' and _starts_at_logon_only(task, ns) and _is_own_cmd_wrapper(
            action.findtext('t:Command', '', ns), action.findtext('t:Arguments', '', ns), home, task_name):
        raise LogonOnlyTask
    if action.tag != '{' + ns['t'] + '}Exec' or action.findtext('t:Command', '', ns).lower() not in {"wscript.exe", r"c:\windows\system32\wscript.exe"}:
        _unverified(f"the task runs {action.findtext('t:Command', '', ns) or action.tag!r}, not wscript.exe")
    args = action.findtext("t:Arguments", "", ns)
    match = re.fullmatch(r'//B //Nologo "([^"\r\n]+)"', args)
    if not match:
        _unverified(f"the task arguments are {args!r}, not //B //Nologo \"<launcher>\"")
    script = _absolute(match[1])
    if script.suffix.lower() != '.vbs':
        _unverified(f"the task runs {script.name}, not a .vbs launcher")
    configured, argv = _vbs_identity(launcher_text(read_definition(script)))
    verify_home(home, configured)
    verify_gateway_argv(argv, home)
