#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.14"
# dependencies = [
#   "typer>=0.12,<1",
#   "questionary>=2.0,<3",
#   "rich>=13,<15",
# ]
# ///
#
# agent-container — interactive wizard + CLI for agent-container containers.
#
# ============================================================================
# This script is the SINGLE SOURCE OF TRUTH for the agent-container on-disk contract.
# Everything below — container naming (agent-container-<name>), the port hash
# (2200 + sum-of-char-codes mod 100), the per-name state files
# ($XDG_STATE_HOME/agent-container/<name>.port), the env-file resolution order
# (./.env -> ~/.config/agent-container/<name>.env -> ~/.config/agent-container/.env), and
# the hosts.conf KEY=VALUE format (FOO_HOST / FOO_PORT) — is defined here and
# only here. The shell completions read the same state files directly; keep
# them in step with the constants in this file.
# ============================================================================
#
# hosts.conf handling: this tool parses hosts.conf line-by-line and NEVER
# executes/sources it. Quoting and unquoted trailing `# comment`s are handled
# like bash `source`, but values containing `$` or backticks are taken
# literally (no expansion), with a one-time warning.

import json
import os
import re
import shutil
import signal
import socket
import subprocess
import sys
import termios
import time
from collections.abc import Callable
from pathlib import Path
from typing import NoReturn

import questionary
import typer
from rich.console import Console
from rich.table import Table

# --- constants ---------------------------------------------------------------

IMAGE_NAME = "localhost/agent-container:latest"
CONTAINER_PREFIX = "agent-container-"
PORT_BASE = 2200
PORT_RANGE = 100  # 2200..2299

STATE_DIR = (
    Path(os.environ.get("XDG_STATE_HOME") or Path.home() / ".local/state") / "agent-container"
)
CONFIG_DIR = Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config") / "agent-container"
HOSTS_CONF = CONFIG_DIR / "hosts.conf"
# Feature 001: the host registry (hosts.json) supersedes the flat hosts.conf
# address book. DEFAULT_HOST is the implicit local host name; per-host runtime
# state lives under STATE_DIR/<host>/. See specs/001-multi-host-deployment/.
HOSTS_JSON = CONFIG_DIR / "hosts.json"
REGISTRY_VERSION = 1
DEFAULT_HOST = "local"


def _is_repo_checkout(base: Path) -> bool:
    """Best-effort test that `base` is an agent-container checkout.

    Keyed on `completions/agent-container.bash` (plus a Dockerfile for the build
    context): a repo-specific sentinel rather than the generic `Dockerfile` +
    `completions/` dir pair, which is common to unrelated trees. Requiring the
    exact file _completion_script reads (bin/agent-container: REPO_ROOT/completions/
    agent-container.<shell>) also makes the marker and that consumed path the same
    invariant — a recognized checkout can never then serve stale package data.
    This is a heuristic, not a guaranteed false-positive-free identifier.
    """
    return (base / "Dockerfile").is_file() and (
        base / "completions" / "agent-container.bash"
    ).is_file()


def _find_repo_root() -> Path | None:
    """Locate the repo checkout in a way that survives a non-editable install.

    A wheel copies this module into site-packages, so Path(__file__) no longer
    points inside the repo. Resolution order:
      1. AGENT_CONTAINER_REPO (explicit operator override): trusted only when it
         satisfies the checkout marker (see _is_repo_checkout); a wrong/typo'd
         path yields None rather than a bogus root (build then dies actionably).
      2. Walk up from this file, then from cwd, looking for a dir that matches
         the marker.
    Returns None when no checkout is reachable — client subcommands still work
    (completions falls back to bundled package data; build fails actionably).
    Note: this cannot die here — it runs at import, before Fatal/die exist.
    """
    env = os.environ.get("AGENT_CONTAINER_REPO")
    if env:
        base = Path(env).expanduser().resolve()
        return base if _is_repo_checkout(base) else None
    here = Path(__file__).resolve()
    for base in here.parents:
        if _is_repo_checkout(base):
            return base
    for base in (Path.cwd(), *Path.cwd().parents):
        if _is_repo_checkout(base):
            return base
    return None


REPO_ROOT = _find_repo_root()

NAME_RE = re.compile(r"[a-z0-9][a-z0-9_-]*")
# ssh argv injection guard: a user/host that begins with '-' would be parsed
# by ssh as an option (e.g. -oProxyCommand=...). Conservative charsets that
# can never start with '-'.
SSH_USER_RE = re.compile(r"[A-Za-z0-9_][A-Za-z0-9._-]*")
SSH_HOST_RE = re.compile(r"[A-Za-z0-9_\[][A-Za-z0-9.:_\]-]*")
# tmux window name: embedded in the ssh remote command (attach --window), so it
# is charset-validated. Matches the entrypoint / agent-container window charset.
WINDOW_RE = re.compile(r"[A-Za-z0-9._-]+")

console = Console()


def eprint(msg: str) -> None:
    # Plain stderr writer; rich would mangle "[agent-container]" as markup and wrap lines.
    print(msg, file=sys.stderr)


class Fatal(Exception):
    """Fatal error; CLI exits 1, wizard prints and returns to the menu."""


def die(msg: str) -> NoReturn:  # cli() turns Fatal into exit 1
    raise Fatal(msg)


# --- pure helpers ------------------------------------------------------------


def validate_name(name: str) -> str:
    """Validate the container short-name charset: ^[a-z0-9][a-z0-9_-]*$.

    >>> validate_name("acme")
    'acme'
    >>> validate_name("my-box")
    'my-box'
    >>> validate_name("Bad")
    Traceback (most recent call last):
    ...
    Fatal: invalid <name> 'Bad'; must match [a-z0-9][a-z0-9_-]*
    """
    if not name:
        die("missing required <name> argument")
    if not NAME_RE.fullmatch(name):
        die(f"invalid <name> '{name}'; must match [a-z0-9][a-z0-9_-]*")
    return name


def container_name(name: str) -> str:
    """
    >>> container_name("acme")
    'agent-container-acme'
    """
    return f"{CONTAINER_PREFIX}{name}"


def volume_name(name: str) -> str:
    """
    >>> volume_name("acme")
    'agent-container-acme-workspace'
    """
    return f"{CONTAINER_PREFIX}{name}-workspace"


def claude_volume_name(name: str) -> str:
    """
    >>> claude_volume_name("acme")
    'agent-container-acme-claude'
    """
    return f"{CONTAINER_PREFIX}{name}-claude"


def codex_volume_name(name: str) -> str:
    """
    >>> codex_volume_name("acme")
    'agent-container-acme-codex'
    """
    return f"{CONTAINER_PREFIX}{name}-codex"


def pi_volume_name(name: str) -> str:
    """
    >>> pi_volume_name("acme")
    'agent-container-acme-pi'
    """
    return f"{CONTAINER_PREFIX}{name}-pi"


def shellenv_volume_name(name: str) -> str:
    """
    >>> shellenv_volume_name("acme")
    'agent-container-acme-shellenv'
    """
    return f"{CONTAINER_PREFIX}{name}-shellenv"


def tmux_volume_name(name: str) -> str:
    """Persists ~/.config/tmux (tmux.conf + tpm plugins) across down/up.

    >>> tmux_volume_name("acme")
    'agent-container-acme-tmux'
    """
    return f"{CONTAINER_PREFIX}{name}-tmux"


def ssh_volume_name(name: str) -> str:
    """Persists ~/.ssh across down/up: authorized_keys, known_hosts, and the
    dev-owned SSH host key under hostkeys/. Because the container is rootless
    (sshd runs as dev), the host key lives here rather than in root-owned
    /etc/ssh, so a container keeps a STABLE SSH identity across recreation.

    >>> ssh_volume_name("acme")
    'agent-container-acme-ssh'
    """
    return f"{CONTAINER_PREFIX}{name}-ssh"


def all_volume_mounts(name: str) -> list[str]:
    """The seven per-container '-v' volume args, in the canonical fixed order
    (workspace, claude, codex, pi, shellenv, tmux, ssh). pi-coding-agent's
    config/auth dir is ~/.pi (verified from
    the package: piConfig.configDir='.pi', getAgentDir()->~/.pi/agent).

    >>> all_volume_mounts("acme")
    ['agent-container-acme-workspace:/workspace', 'agent-container-acme-claude:/home/dev/.claude', 'agent-container-acme-codex:/home/dev/.codex', 'agent-container-acme-pi:/home/dev/.pi', 'agent-container-acme-shellenv:/home/dev/.agent-container', 'agent-container-acme-tmux:/home/dev/.config/tmux', 'agent-container-acme-ssh:/home/dev/.ssh']
    """
    return [
        f"{volume_name(name)}:/workspace",
        f"{claude_volume_name(name)}:/home/dev/.claude",
        f"{codex_volume_name(name)}:/home/dev/.codex",
        f"{pi_volume_name(name)}:/home/dev/.pi",
        f"{shellenv_volume_name(name)}:/home/dev/.agent-container",
        f"{tmux_volume_name(name)}:/home/dev/.config/tmux",
        f"{ssh_volume_name(name)}:/home/dev/.ssh",
    ]


def per_container_volumes(name: str) -> list[str]:
    """All per-container volume NAMES, canonical order; used by --purge.

    >>> per_container_volumes("acme")
    ['agent-container-acme-workspace', 'agent-container-acme-claude', 'agent-container-acme-codex', 'agent-container-acme-pi', 'agent-container-acme-shellenv', 'agent-container-acme-tmux', 'agent-container-acme-ssh']
    """
    return [
        volume_name(name),
        claude_volume_name(name),
        codex_volume_name(name),
        pi_volume_name(name),
        shellenv_volume_name(name),
        tmux_volume_name(name),
        ssh_volume_name(name),
    ]


def resolve_bind_mount(spec: str) -> str:
    """Resolve a '--mount HOSTDIR[:CONTAINERPATH]' spec into an absolute,
    read-write '-v' value.

    HOSTDIR is resolved to an absolute real path (Path.resolve()) and must be
    an existing directory. CONTAINERPATH defaults to /workspace/<basename>; if
    given explicitly it must be absolute. No secret/env value ever reaches argv.

    Lima prerequisite: the host dir must sit under a path the Lima VM exposes
    WRITABLE (set `writable: true` on the relevant mount and restart Lima),
    otherwise the bind is read-only inside the VM.
    """
    host, sep, container = spec.partition(":")
    if not host:
        die(f"--mount: empty host directory in '{spec}'")
    p = Path(host)
    if not p.is_dir():
        die(f"--mount: host path '{host}' does not exist or is not a directory")
    abs_host = str(p.resolve())
    if sep:  # an explicit ':' was present
        if not container:
            die(f"--mount: empty container path in '{spec}'")
        if not container.startswith("/"):
            die(f"--mount: container path '{container}' must be absolute")
    else:
        container = f"/workspace/{Path(abs_host).name}"
    return f"{abs_host}:{container}"


# Container-side paths the entrypoint reads injected SSH material from (bind
# mounts). Kept in sync with INJECT_DIR in entrypoint.sh.
INJECT_HOST_KEY_PATH = "/run/agent-container/ssh_host_ed25519_key"
INJECT_AUTHORIZED_KEYS_PATH = "/run/agent-container/authorized_keys"


def validate_private_key(path: Path) -> None:
    """Fail fast if `path` is not a readable, unencrypted OpenSSH private key.
    stdin is closed so an encrypted key fails cleanly instead of prompting."""
    r = subprocess.run(
        ["ssh-keygen", "-y", "-f", str(path)],
        capture_output=True,
        text=True,
        stdin=subprocess.DEVNULL,
    )
    if r.returncode != 0:
        die(
            f"--host-key: {path} is not a valid, unencrypted OpenSSH private key "
            f"({r.stderr.strip() or 'ssh-keygen validation failed'})"
        )


def resolve_ssh_injection(
    name: str, host_key: Path | None, authorized_keys: list[Path]
) -> list[str]:
    """Resolve `up --host-key/--authorized-key` into read-only '-v' bind specs.

    The entrypoint installs whatever appears at the container-side inject paths
    onto the persisted ~/.ssh volume at boot. Both the host key and the
    concatenated authorized_keys are staged as per-container files under
    STATE_DIR and bind-mounted from there, so the bind survives a container
    restart (a temp file would vanish and leave an empty mount).

    The staged files are mode 0644 on purpose: the entrypoint reads them as the
    unprivileged `dev` user, whose uid need NOT equal the host uid that ran `up`
    (it does not on CI runners / any host with a different login uid). Docker has
    no bind-mount chown (unlike podman's `:U`), so an 0600 file owned by the host
    user is unreadable inside the container — the read fails and, under the
    entrypoint's `set -e`, crash-loops sshd. 0644 is safe: STATE_DIR is locked to
    0700 so no other HOST user can traverse to these files, while the container
    reads each file inode directly through the mount (host dir perms don't gate
    it). authorized_keys are public regardless; the host key stays dir-protected.
    """
    specs: list[str] = []
    STATE_DIR.mkdir(parents=True, exist_ok=True)
    STATE_DIR.chmod(0o700)
    if host_key is not None:
        hk = host_key.expanduser()
        if not hk.is_file():
            die(f"--host-key: {host_key} does not exist or is not a file")
        validate_private_key(hk)
        hk_file = STATE_DIR / f"{name}.host_key"
        hk_file.write_bytes(hk.read_bytes())
        hk_file.chmod(0o644)
        specs.append(f"{hk_file}:{INJECT_HOST_KEY_PATH}:ro")
    if authorized_keys:
        blob = ""
        for p in authorized_keys:
            pk = p.expanduser()
            if not pk.is_file():
                die(f"--authorized-key: {p} does not exist or is not a file")
            text = pk.read_text()
            blob += text if text.endswith("\n") else text + "\n"
        ak_file = STATE_DIR / f"{name}.authorized_keys"
        ak_file.write_text(blob)
        ak_file.chmod(0o644)
        specs.append(f"{ak_file}:{INJECT_AUTHORIZED_KEYS_PATH}:ro")
    return specs


def port_for_name(name: str) -> int:
    """Deterministic port: PORT_BASE + (sum of char codes mod PORT_RANGE).

    Name charset is ASCII-only (enforced by NAME_RE), so ord() matches
    bash's printf '%d' "'c" exactly.

    >>> port_for_name("acme")
    2206
    >>> port_for_name("my-box")
    2204
    """
    return PORT_BASE + (sum(ord(c) for c in name) % PORT_RANGE)


def name_to_key(name: str) -> str:
    """hosts.conf key prefix: hyphens -> underscores, uppercased.

    >>> name_to_key("my-box")
    'MY_BOX'
    >>> name_to_key("acme")
    'ACME'
    """
    return name.replace("-", "_").upper()


def resolve_ssh_user(override: str | None = None) -> str:
    """SSH user from --user / AGENT_CONTAINER_USER / 'dev', charset-checked so it can
    never be parsed by ssh as an option.

    >>> resolve_ssh_user("dev")
    'dev'
    >>> resolve_ssh_user("-oProxyCommand=x")
    Traceback (most recent call last):
    ...
    Fatal: invalid ssh user '-oProxyCommand=x'
    """
    user = override or os.environ.get("AGENT_CONTAINER_USER") or "dev"
    if not SSH_USER_RE.fullmatch(user):
        die(f"invalid ssh user '{user}'")
    return user


def validate_window(window: str) -> str:
    """tmux window name guard: it is embedded in the ssh remote shell command,
    so reject anything outside the safe charset before building it.

    >>> validate_window("agents")
    'agents'
    >>> validate_window("a; rm -rf ~")
    Traceback (most recent call last):
    ...
    Fatal: invalid tmux window 'a; rm -rf ~'; must match [A-Za-z0-9._-]+
    """
    if not WINDOW_RE.fullmatch(window):
        die(f"invalid tmux window '{window}'; must match [A-Za-z0-9._-]+")
    return window


def parse_kv_config(text: str) -> dict[str, str]:
    """Literal KEY=VALUE parser for hosts.conf. Never executes the file.

    Skips blank lines and # comments, strips an optional leading 'export ',
    splits on the first '=', honours one pair of matching quotes, and — like
    bash `source` — drops unquoted trailing ' # comment's (a '#' only starts
    a comment when preceded by whitespace; 'A=#lit' keeps the '#').

    >>> parse_kv_config("# c\\n\\nA=1\\nexport B='two'\\nC=\\"three\\"\\nD=a=b\\n")
    {'A': '1', 'B': 'two', 'C': 'three', 'D': 'a=b'}
    >>> parse_kv_config('H=vps.example.com # primary box\\nQ="a # b" # c\\nR=#lit\\n')
    {'H': 'vps.example.com', 'Q': 'a # b', 'R': '#lit'}
    """
    out: dict[str, str] = {}
    for line in text.splitlines():
        line = line.strip()
        if not line or line.startswith("#") or "=" not in line:
            continue
        if line.startswith("export "):
            line = line[len("export ") :].lstrip()
        key, _, value = line.partition("=")
        key = key.strip()
        value = value.strip()
        if value[:1] in ("'", '"'):
            # Quoted: take up to the matching close quote; anything after it
            # (e.g. a trailing comment) is ignored, as bash would.
            closing = value.find(value[0], 1)
            if closing != -1:
                value = value[1:closing]
        else:
            m = re.search(r"\s#", value)
            if m:
                value = value[: m.start()].rstrip()
        if key:
            out[key] = value
    return out


def env_file_candidates(name: str, cwd: Path) -> list[Path]:
    """Env-file resolution order (./.env, then per-name, then shared default).

    >>> [str(p) for p in env_file_candidates("acme", Path("/w"))][0]
    '/w/.env'
    """
    return [cwd / ".env", CONFIG_DIR / f"{name}.env", CONFIG_DIR / ".env"]


def resolve_env_file(name: str) -> Path | None:
    # Secret hygiene: only existence checks; contents are never read.
    for candidate in env_file_candidates(name, Path.cwd()):
        if candidate.is_file():
            return candidate
    return None


def state_file(name: str) -> Path:
    return STATE_DIR / f"{name}.port"


# --- per-host state (Feature 001) --------------------------------------------
# Runtime state is namespaced per host: STATE_DIR/<host>/<name>.{port,compose.yaml,
# host_key,authorized_keys}. Identity VALUES (container_name/port_for_name/volume
# names) are unchanged — only the state file LOCATION gains a host segment, so the
# same name may run on different hosts without collision (per-host daemons make
# project/volume collisions structurally impossible). The pre-per-host flat
# STATE_DIR/<name>.* files belong to the implicit 'local' host; migrate_flat_state()
# relocates them once, keeping the identity contract stable (Constitution IV).


def host_state_dir(host: str) -> Path:
    return STATE_DIR / host


def state_file_for(host: str, name: str) -> Path:
    return host_state_dir(host) / f"{name}.port"


def compose_file_path(host: str, name: str) -> Path:
    return host_state_dir(host) / f"{name}.compose.yaml"


# Flat state artifacts written before per-host namespacing existed. Migrated into
# STATE_DIR/local/ on first host-aware access.
_FLAT_STATE_SUFFIXES = (".port", ".host_key", ".authorized_keys")


def migrate_flat_state() -> None:
    """One-time: relocate flat STATE_DIR/<name>.{port,host_key,authorized_keys}
    into STATE_DIR/local/ (the implicit host). Idempotent: skips when the target
    already exists and never overwrites. Safe to call repeatedly."""
    if not STATE_DIR.is_dir():
        return
    local_dir = host_state_dir(DEFAULT_HOST)
    for f in sorted(STATE_DIR.iterdir()):
        if not f.is_file() or f.suffix not in _FLAT_STATE_SUFFIXES:
            continue
        # Skip .compose.yaml (never existed flat) and anything already migrated.
        target = local_dir / f.name
        if target.exists():
            continue
        local_dir.mkdir(parents=True, exist_ok=True)
        os.replace(f, target)


# --- runtime -----------------------------------------------------------------

_hosts_warned = False

# Captured at startup so an abnormal ssh exit can't leave the terminal raw.
try:
    _ORIG_TERMIOS = termios.tcgetattr(sys.stdin.fileno()) if sys.stdin.isatty() else None
except Exception:
    _ORIG_TERMIOS = None


def detect_runtime() -> str:
    """Resolve the container runtime.

    AGENT_CONTAINER_RUNTIME (validated docker|podman, must be on PATH) always wins.
    Otherwise the default is platform-aware: on macOS the operator runs Lima +
    docker-cli, so prefer docker then podman; on Linux (the VPS) prefer podman
    then docker. Dies if neither is installed.
    """
    forced = os.environ.get("AGENT_CONTAINER_RUNTIME")
    if forced:
        if forced not in ("podman", "docker"):
            die(f"AGENT_CONTAINER_RUNTIME must be 'docker' or 'podman', got: {forced}")
        if not shutil.which(forced):
            die(f"AGENT_CONTAINER_RUNTIME={forced} but '{forced}' is not on PATH")
        return forced
    order = ("docker", "podman") if sys.platform.startswith("darwin") else ("podman", "docker")
    for rt in order:
        if shutil.which(rt):
            return rt
    die("neither 'podman' nor 'docker' on PATH (install one, or set AGENT_CONTAINER_RUNTIME)")


def query(argv: list[str]) -> subprocess.CompletedProcess:
    return subprocess.run(argv, capture_output=True, text=True)


def container_running(rt: str, cname: str) -> bool:
    r = query([rt, "ps", "--filter", f"name=^{cname}$", "--format", "{{.Names}}"])
    return cname in r.stdout.splitlines()  # exact match, mirrors grep -qx


def container_exists(rt: str, cname: str) -> bool:
    r = query([rt, "ps", "-a", "--filter", f"name=^{cname}$", "--format", "{{.Names}}"])
    return cname in r.stdout.splitlines()


def ps_agent_container(rt: str, include_stopped: bool = False) -> list[tuple[str, str, str, str]]:
    """(cname, image, status, uptime) rows for agent-container-* containers.

    Go-template + tab split, not --format json: podman and docker JSON
    shapes are incompatible, the template output is not.
    """
    argv = [rt, "ps"] + (["-a"] if include_stopped else [])
    argv += ["--format", "{{.Names}}\t{{.Image}}\t{{.Status}}\t{{.RunningFor}}"]
    rows = []
    for line in query(argv).stdout.splitlines():
        parts = line.split("\t")
        if len(parts) == 4 and parts[0].startswith(CONTAINER_PREFIX):
            rows.append((parts[0], parts[1], parts[2], parts[3]))
    return rows


def image_exists(rt: str, tag: str) -> bool:
    # `image inspect` works on both podman and docker (podman's `image exists` does not).
    return query([rt, "image", "inspect", tag]).returncode == 0


def port_free(port: int) -> bool:
    # Wildcard bind: `-p {port}:2222` publishes on ALL interfaces (parity with
    # agent-container), so probe what will actually be bound, not just loopback.
    try:
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            s.bind(("", port))
        return True
    except OSError:
        return False


def wait_port_released(port: int, timeout: float = 15.0) -> None:
    """Block until `port` is bindable again (or timeout elapses). `<rt> rm`
    returns before the daemon has finished tearing down the published-port
    forwarding, so an immediate `up` on the same name hits a false 'port in
    use'. Making `down` wait keeps a down+up (recreate) cycle on one name
    reliable. Best-effort: on timeout we simply return and let `up` report the
    real state."""
    deadline = time.monotonic() + timeout
    while time.monotonic() < deadline:
        if port_free(port):
            return
        time.sleep(0.25)


def write_state(host: str, name: str, port: int) -> None:
    host_state_dir(host).mkdir(parents=True, exist_ok=True)
    state_file_for(host, name).write_text(f"{port}\n")


def read_state_port(host: str, name: str) -> str | None:
    f = state_file_for(host, name)
    if not f.is_file():
        return None
    return f.read_text().strip() or None


def clear_state(host: str, name: str) -> None:
    state_file_for(host, name).unlink(missing_ok=True)


def load_hosts_conf() -> dict[str, str]:
    global _hosts_warned
    if not HOSTS_CONF.is_file():
        return {}
    conf = parse_kv_config(HOSTS_CONF.read_text())
    if not _hosts_warned and any("$" in v or "`" in v for v in conf.values()):
        eprint(
            "[agent-container] WARNING: hosts.conf contains '$' or '`' values; "
            "agent-container does not perform shell expansion (agent-container does)."
        )
        _hosts_warned = True
    return conf


def hosts_entry(name: str) -> tuple[str, str] | None:
    """(host, port) from hosts.conf, or None unless BOTH keys are present."""
    conf = load_hosts_conf()
    key = name_to_key(name)
    host, port = conf.get(f"{key}_HOST"), conf.get(f"{key}_PORT")
    if host and port:
        return host, port
    return None


# --- host registry (Feature 001) ---------------------------------------------
# The registry (hosts.json) is the single source of truth for WHERE containers
# run, superseding the flat hosts.conf address book. Shape:
#   {"version": 1, "default": "<name>|null", "hosts": {"<name>": {Host}, ...}}
# A Host record: {driver, context, address, port?, provisioning, created_by_tool}.
# When hosts.json is absent, a legacy hosts.conf is read into read-only
# 'existing-ssh' (attach-only) hosts for a deprecation window. The registry is
# written atomically and its content is NEVER executed (parity with hosts.conf).


def _synthesize_legacy_registry() -> dict:
    """Read a legacy hosts.conf into attach-only 'existing-ssh' Host records.
    Not written back; removed after the deprecation window."""
    conf = load_hosts_conf()
    hosts: dict = {}
    for key in conf:
        if not key.endswith("_HOST"):
            continue
        base = key[: -len("_HOST")]
        host, port = conf[key], conf.get(f"{base}_PORT")
        if not (host and port):
            continue
        hosts[base.lower()] = {
            "driver": "existing-ssh",
            "context": "",
            "address": host,
            "port": port,
            "provisioning": None,
            "created_by_tool": False,
        }
    return {"version": REGISTRY_VERSION, "default": None, "hosts": hosts}


def load_registry() -> dict:
    """The host registry. Reads hosts.json when present, else synthesizes a
    read-only legacy registry from hosts.conf. Dies on a malformed file rather
    than silently losing host records."""
    if HOSTS_JSON.is_file():
        try:
            data = json.loads(HOSTS_JSON.read_text())
        except (json.JSONDecodeError, OSError) as e:
            die(f"invalid host registry at {HOSTS_JSON}: {e}")
        if not isinstance(data, dict) or not isinstance(data.get("hosts"), dict):
            die(f"invalid host registry at {HOSTS_JSON}: missing 'hosts' object")
        data.setdefault("version", REGISTRY_VERSION)
        data.setdefault("default", None)
        return data
    return _synthesize_legacy_registry()


def save_registry(reg: dict) -> None:
    """Persist the registry atomically (temp + os.replace) so a crash mid-write
    never truncates hosts.json."""
    CONFIG_DIR.mkdir(parents=True, exist_ok=True)
    tmp = HOSTS_JSON.with_name(HOSTS_JSON.name + ".tmp")
    tmp.write_text(json.dumps(reg, indent=2) + "\n")
    os.replace(tmp, HOSTS_JSON)


def registry_hosts(reg: dict) -> dict:
    hosts = reg.get("hosts")
    return hosts if isinstance(hosts, dict) else {}


def get_host(reg: dict, name: str) -> dict | None:
    return registry_hosts(reg).get(name)


def default_host_name(reg: dict) -> str | None:
    """The registry's default deploy target, or None."""
    d = reg.get("default")
    return d if isinstance(d, str) else None


def address_from_context(context: str) -> str:
    """Attach address implied by a runtime context: the host of an ssh:// context,
    else localhost (a local context publishes to the local machine).

    >>> address_from_context("ssh://root@203.0.113.7")
    '203.0.113.7'
    >>> address_from_context("ssh://ops@vps.example.com:22")
    'vps.example.com'
    >>> address_from_context("lima-docker")
    'localhost'
    """
    m = re.match(r"ssh://(?:[^@/]+@)?([^:/]+)", context)
    return m.group(1) if m else "localhost"


def probe_host_runtime(host: dict) -> str | None:
    """Best-effort capability probe: returns an error string if the host's
    runtime is not usable (binary missing / context unreachable), else None.
    Non-blocking by design — a host may be registered before its context is
    reachable (e.g. just-provisioned); the deploy path fails hard later if still
    unusable. Bounded so a dead ssh:// context can't hang registration."""
    try:
        argv = driver_runtime_argv(host) + ["version"]
    except Fatal:
        return "driver is attach-only"
    if not shutil.which(argv[0]):
        return f"'{argv[0]}' is not on PATH"
    try:
        r = subprocess.run(argv, capture_output=True, text=True, timeout=8)
    except (subprocess.TimeoutExpired, OSError) as e:
        return f"runtime probe failed: {e}"
    if r.returncode != 0:
        return (r.stderr.strip() or "runtime probe failed").splitlines()[0][:160]
    return None


def cli_host_add(
    name: str,
    driver: str,
    context: str | None,
    address: str | None,
    make_default: bool,
) -> None:
    """Register a local/remote container-runtime host in the registry. Cloud
    provisioning (--provider) arrives in a later feature; this handles the
    docker/podman context drivers."""
    validate_name(name)
    if driver not in ("docker", "podman"):
        die(f"--driver must be 'docker' or 'podman' (got '{driver}')")
    if not context:
        opt = "--docker-context" if driver == "docker" else "--connection"
        die(f"host add: a {driver} host needs {opt} <context>")
    record = {
        "driver": driver,
        "context": context,
        "address": address or address_from_context(context),
        "provisioning": None,
        "created_by_tool": False,
    }
    reg = load_registry()
    hosts = registry_hosts(reg)
    existed = name in hosts
    hosts[name] = record
    reg["hosts"] = hosts
    if make_default or default_host_name(reg) is None:
        reg["default"] = name
    save_registry(reg)
    verb = "updated" if existed else "registered"
    is_default = " [default]" if default_host_name(reg) == name else ""
    log(f"{verb} host '{name}' (driver={driver}, context={context}){is_default}")
    err = probe_host_runtime(record)
    if err is not None:
        warn(f"host '{name}' registered but its runtime is not usable yet: {err}")


def do_host_ls(as_json: bool) -> None:
    reg = load_registry()
    hosts = registry_hosts(reg)
    default = default_host_name(reg)
    if as_json:
        print(json.dumps({"default": default, "hosts": hosts}, indent=2))
        return
    if not hosts:
        log("no hosts registered (add one: agent-container host add <name> --docker-context <ctx>)")
        return
    table = Table(show_header=True, header_style="bold", box=None, pad_edge=False)
    for col in ("NAME", "DRIVER", "CONTEXT", "ADDRESS", "DEFAULT"):
        table.add_column(col)
    for hname in sorted(hosts):
        h = hosts[hname]
        table.add_row(
            hname,
            str(h.get("driver", "?")),
            str(h.get("context") or "-"),
            str(h.get("address") or "-"),
            "*" if hname == default else "",
        )
    console.print(table)


# --- driver seam (Feature 001) -----------------------------------------------
# A driver abstracts build/run/connect on a host so local and remote share one
# path. Pure argv builders (no runtime needed) — the docker/podman asymmetry is
# absorbed here: docker targets `--context`, podman targets `--connection`. An
# 'existing-ssh' host is attach-only and rejects container operations.


def driver_runtime_argv(host: dict) -> list[str]:
    """Base argv targeting a host's runtime.

    >>> driver_runtime_argv({"driver": "docker", "context": "lima"})
    ['docker', '--context', 'lima']
    >>> driver_runtime_argv({"driver": "podman", "context": "vps"})
    ['podman', '--connection', 'vps']
    >>> driver_runtime_argv({"driver": "docker", "context": ""})
    ['docker']
    """
    driver = host.get("driver")
    ctx = host.get("context") or ""
    if driver == "docker":
        return ["docker", "--context", ctx] if ctx else ["docker"]
    if driver == "podman":
        return ["podman", "--connection", ctx] if ctx else ["podman"]
    die(f"host driver '{driver}' is attach-only; it cannot build or run containers")


def driver_compose_argv(host: dict, project: str, file: Path, *args: str) -> list[str]:
    """`<runtime> --context/-connection X compose -p <project> -f <file> …`.

    >>> from pathlib import Path
    >>> driver_compose_argv({"driver": "docker", "context": "lima"}, "agent-container-acme", Path("/s/acme.compose.yaml"), "up", "-d")
    ['docker', '--context', 'lima', 'compose', '-p', 'agent-container-acme', '-f', '/s/acme.compose.yaml', 'up', '-d']
    """
    return driver_runtime_argv(host) + ["compose", "-p", project, "-f", str(file), *args]


def driver_up_argv(host: dict, project: str, file: Path) -> list[str]:
    return driver_compose_argv(host, project, file, "up", "-d", "--build")


def driver_down_argv(host: dict, project: str, file: Path, purge: bool = False) -> list[str]:
    return driver_compose_argv(host, project, file, "down", *(["--volumes"] if purge else []))


def driver_reachable_address(host: dict) -> str:
    """Address used for attach: the host's own address (localhost for local)."""
    return host.get("address") or "localhost"


# --- compose generation (Feature 001) ----------------------------------------
# The per-container deployment is a generated, inspectable compose project,
# emitted as JSON (a valid YAML subset) so no YAML dependency is needed. It
# declares the seven named volumes and expresses injected SSH identity as compose
# `secrets` (private host key) / `configs` (public authorized_keys) referencing
# LOCAL files, so the material transfers over a remote context (a bind would
# resolve empty on the remote). No secret value is ever written inline — only
# `file:` references. Regenerated from parameters on every up (derived artifact).


def compose_project(name: str) -> str:
    """
    >>> compose_project("acme")
    'agent-container-acme'
    """
    return container_name(name)


def build_compose_model(
    name: str,
    build_context: Path | str,
    host_key_file: Path | None = None,
    authorized_keys_file: Path | None = None,
    env_file: Path | None = None,
    extra_mounts: list[str] | None = None,
) -> dict:
    """Build the compose model for container <name>. Pure: embeds paths as
    strings, reads nothing. host_key_file/authorized_keys_file are LOCAL staged
    files referenced via compose secrets/configs (never inlined). env_file is
    read client-side by compose and merged into the service environment;
    extra_mounts are already-resolved '<abs-host>:<container>' bind specs.

    NOTE: the exact in-container mount path for compose secrets vs configs (an
    absolute `target`) is validated in the acceptance tier (research R5); the
    entrypoint reads the INJECT_* paths.
    """
    port = port_for_name(name)
    service: dict = {
        "container_name": container_name(name),
        "build": {"context": str(build_context)},
        "restart": "unless-stopped",
        "ports": [f"{port}:2222"],
        "volumes": list(all_volume_mounts(name)) + list(extra_mounts or []),
    }
    if env_file is not None:
        service["env_file"] = [str(env_file)]
    model: dict = {
        "name": compose_project(name),
        "services": {"agent": service},
        # Pin each volume's `name` so compose does NOT prefix it with the project
        # ("<project>_<vol>"); the seven volume names are the deterministic identity
        # contract (Constitution IV) that `--purge` and the completions rely on.
        "volumes": {vn: {"name": vn} for vn in per_container_volumes(name)},
    }
    # Injected SSH identity rides as compose `configs` (NOT `secrets`). Both the
    # host key and authorized_keys are delivered this way because a compose
    # `secret` with an ABSOLUTE target crash-loops the container on some docker
    # engines (observed on GitHub ubuntu runners; compose `configs` with an
    # absolute target are portable). The material is still handled as sensitive:
    # staged locally 0600, ephemeral (never persisted to a volume), never baked
    # into the image, never on argv (Constitution III — least exposure holds; the
    # secret-vs-config choice is a portability-forced compose mechanism detail).
    svc_configs: list[dict] = []
    model_configs: dict = {}
    if host_key_file is not None:
        svc_configs.append({"source": "ssh_host_key", "target": INJECT_HOST_KEY_PATH})
        model_configs["ssh_host_key"] = {"file": str(host_key_file)}
    if authorized_keys_file is not None:
        svc_configs.append({"source": "ssh_authorized_keys", "target": INJECT_AUTHORIZED_KEYS_PATH})
        model_configs["ssh_authorized_keys"] = {"file": str(authorized_keys_file)}
    if svc_configs:
        service["configs"] = svc_configs
        model["configs"] = model_configs
    return model


def write_compose_file(host: str, name: str, model: dict) -> Path:
    """Write the (regenerable) compose model as JSON to the per-host state dir."""
    host_state_dir(host).mkdir(parents=True, exist_ok=True)
    p = compose_file_path(host, name)
    p.write_text(json.dumps(model, indent=2) + "\n")
    return p


def quadlet_active(name: str) -> bool:
    # Best-effort probe; systemctl is absent on macOS — ignore all failures.
    if not shutil.which("systemctl"):
        return False
    try:
        r = query(["systemctl", "--user", "is-active", f"{container_name(name)}.service"])
        return r.returncode == 0 and r.stdout.strip() == "active"
    except Exception:
        return False


def is_tty() -> bool:
    return sys.stdin.isatty() and sys.stdout.isatty()


# --- commands ----------------------------------------------------------------


def log(msg: str) -> None:
    eprint(f"[agent-container] {msg}")


def warn(msg: str) -> None:
    eprint(f"[agent-container] WARNING: {msg}")


def hint(cmd: str) -> None:
    console.print(f"hint: {cmd}", style="dim")


def do_build(tag: str, context: Path | None = None) -> None:
    # `build` is the one subcommand that needs a repo checkout: a docker build
    # context IS a checkout. Resolve it explicitly (a PyPI install has REPO_ROOT
    # is None) and fail actionably rather than with a traceback.
    ctx = context
    if ctx is None:
        env = os.environ.get("AGENT_CONTAINER_REPO")
        if env:
            base = Path(env).expanduser().resolve()
            if not _is_repo_checkout(base):
                die(
                    f"AGENT_CONTAINER_REPO={env} is not an agent-container checkout "
                    "(missing Dockerfile/completions/agent-container.bash)"
                )
            ctx = base
        else:
            ctx = REPO_ROOT
    if ctx is None:
        die(
            "no repo checkout for the docker build context; run from a checkout, "
            "set AGENT_CONTAINER_REPO=<checkout>, or pass --context <dir>"
        )
    rt = detect_runtime()
    log(f"building image '{tag}' with {rt} from {ctx}")
    # Inherited stdio: layer progress must stream, never capture.
    rc = subprocess.run([rt, "build", "-t", tag, str(ctx)]).returncode
    if rc != 0:
        die(f"build failed (exit {rc})")


def resolve_build_context() -> Path:
    """The repo checkout used as the compose build context (image builds on the
    host). Same resolution as do_build (AGENT_CONTAINER_REPO -> REPO_ROOT); dies
    actionably when no checkout is reachable (e.g. a bare PyPI install)."""
    env = os.environ.get("AGENT_CONTAINER_REPO")
    if env:
        base = Path(env).expanduser().resolve()
        if not _is_repo_checkout(base):
            die(f"AGENT_CONTAINER_REPO={env} is not an agent-container checkout")
        return base
    if REPO_ROOT is not None:
        return REPO_ROOT
    die(
        "no repo checkout for the compose build context; run from a checkout "
        "or set AGENT_CONTAINER_REPO=<checkout>"
    )


def host_is_local(host: dict) -> bool:
    return driver_reachable_address(host) == "localhost"


def implicit_local_host(rt: str | None = None) -> dict:
    """A synthetic 'local' host using the default runtime context — the smooth
    upgrade path from the pre-registry single-host tool."""
    return {
        "driver": rt or detect_runtime(),
        "context": "",
        "address": "localhost",
        "provisioning": None,
        "created_by_tool": False,
    }


def resolve_deploy_host(host_name: str | None) -> tuple[str, dict]:
    """Resolve (host_name, host_record) for a deploy/lifecycle op. An explicit
    --host must exist; otherwise the registry default; and if the registry is
    empty, an implicit local host (behaves like the pre-multi-host tool)."""
    reg = load_registry()
    if host_name is not None:
        h = get_host(reg, host_name)
        if h is None:
            die(f"no host named '{host_name}' (see: agent-container host ls)")
        return host_name, h
    default = default_host_name(reg)
    if default is not None:
        h = get_host(reg, default)
        if h is not None:
            return default, h
    log(
        f"no hosts registered; using an implicit local host "
        f"(register one with: agent-container host add {DEFAULT_HOST} --docker-context <ctx>)"
    )
    return DEFAULT_HOST, implicit_local_host()


def host_ps_rows(host: dict, include_stopped: bool = False) -> list[tuple[str, str, str, str]]:
    """(cname, image, status, uptime) rows for agent-container-* on a host's daemon."""
    argv = driver_runtime_argv(host) + ["ps"] + (["-a"] if include_stopped else [])
    argv += ["--format", "{{.Names}}\t{{.Image}}\t{{.Status}}\t{{.RunningFor}}"]
    rows = []
    for line in query(argv).stdout.splitlines():
        parts = line.split("\t")
        if len(parts) == 4 and parts[0].startswith(CONTAINER_PREFIX):
            rows.append((parts[0], parts[1], parts[2], parts[3]))
    return rows


def host_container_names(host: dict, include_stopped: bool = False) -> set[str]:
    return {row[0] for row in host_ps_rows(host, include_stopped)}


def stage_ssh_injection(
    host: str, name: str, host_key: Path | None, authorized_keys: list[Path]
) -> tuple[Path | None, Path | None]:
    """Stage injected SSH material as LOCAL files under the per-host state dir,
    returning (host_key_file, authorized_keys_file) for the compose model to
    reference as configs (transfers over a remote context; a bind resolves empty
    on a remote host).

    Both files are staged **0644**: compose exposes the source file's mode into
    the container, where the unprivileged `dev` user reads it — and dev's uid
    (1000) need NOT equal the host uid that ran `up` (it does not on CI runners),
    so a 0600 file is unreadable inside the container and crash-loops the
    entrypoint. 0644 is safe because the per-host state dir is locked to 0700, so
    no other HOST user can traverse to the files, while the container reads each
    inode through the mount. (This mirrors the original bind-mount rationale;
    staging 0600 here was a regression that broke on ubuntu docker.)"""
    d = host_state_dir(host)
    d.mkdir(parents=True, exist_ok=True)
    d.chmod(0o700)  # host-side protection for the 0644 key files
    hk_file: Path | None = None
    ak_file: Path | None = None
    if host_key is not None:
        hk = host_key.expanduser()
        if not hk.is_file():
            die(f"--host-key: {host_key} does not exist or is not a file")
        validate_private_key(hk)
        hk_file = d / f"{name}.host_key"
        hk_file.write_bytes(hk.read_bytes())
        hk_file.chmod(0o644)
    if authorized_keys:
        blob = ""
        for p in authorized_keys:
            pk = p.expanduser()
            if not pk.is_file():
                die(f"--authorized-key: {p} does not exist or is not a file")
            text = pk.read_text()
            blob += text if text.endswith("\n") else text + "\n"
        ak_file = d / f"{name}.authorized_keys"
        ak_file.write_text(blob)
        ak_file.chmod(0o644)
    return hk_file, ak_file


def compose_up_exec(
    host_name: str,
    host_rec: dict,
    name: str,
    env_file: Path,
    mounts: list[str],
    host_key: Path | None,
    authorized_keys: list[Path],
) -> None:
    """Generate the compose project and bring it up on the host (image builds on
    the host). Replaces the imperative `<rt> run` path."""
    port = port_for_name(name)
    if host_is_local(host_rec) and not port_free(port):
        die(
            f"port {port} is already in use (port = 2200 + name hash; "
            f"collisions are possible). Stop whatever holds it (agent-container list) "
            f"or pick a different name."
        )
    hk_file, ak_file = stage_ssh_injection(host_name, name, host_key, authorized_keys)
    build_ctx = resolve_build_context()
    model = build_compose_model(name, build_ctx, hk_file, ak_file, env_file, mounts)
    compose_file = write_compose_file(host_name, name, model)
    log(f"host={host_name} name={name} port={port} env-file={env_file}")
    log(f"compose={compose_file}")
    argv = driver_up_argv(host_rec, compose_project(name), compose_file)
    rc = subprocess.run(argv).returncode  # inherited stdio: build output streams
    if rc != 0:
        die(f"compose up failed (exit {rc})")
    write_state(host_name, name, port)
    addr = driver_reachable_address(host_rec)
    hflag = "" if host_name == DEFAULT_HOST else f" --host {host_name}"
    log(f"started {container_name(name)}; attach with: agent-container attach {name}{hflag}")
    log(f"or directly: ssh dev@{addr} -p {port} -t tmux attach -t main")


def do_up(
    name: str,
    host: str | None = None,
    env_file_override: Path | None = None,
    mounts: list[str] | None = None,
    host_key: Path | None = None,
    authorized_keys: list[Path] | None = None,
) -> None:
    validate_name(name)
    migrate_flat_state()
    # Resolve binds up front so a bad --mount aborts before any runtime call.
    resolved_mounts = [resolve_bind_mount(m) for m in (mounts or [])]
    host_name, host_rec = resolve_deploy_host(host)
    cname = container_name(name)
    hflag = "" if host_name == DEFAULT_HOST else f" --host {host_name}"

    existing = host_container_names(host_rec, include_stopped=True)
    if cname in host_container_names(host_rec):
        port = read_state_port(host_name, name)
        log(
            f"container {cname} already running on {host_name}"
            + (f" (port {port})" if port else "")
        )
        log(f"attach with: agent-container attach {name}{hflag}")
        return
    if cname in existing:
        die(
            f"container {cname} exists but is not running on {host_name}. Run: agent-container down {name}{hflag}"
        )

    env_file = env_file_override or resolve_env_file(name)
    if env_file is None:
        cands = ", ".join(str(c) for c in env_file_candidates(name, Path.cwd()))
        die(f"no .env found. Looked in: {cands}")

    # The image builds on the host via compose (`up --build`) — no pre-built
    # image or registry needed.
    compose_up_exec(
        host_name, host_rec, name, env_file, resolved_mounts, host_key, authorized_keys or []
    )


def down_container(host_name: str, host_rec: dict, name: str, purge: bool) -> None:
    cname = container_name(name)
    compose_file = compose_file_path(host_name, name)
    exists = cname in host_container_names(host_rec, include_stopped=True)
    vols = per_container_volumes(name)

    if exists or compose_file.is_file():
        log(f"stopping and removing {cname} on {host_name}")
        if compose_file.is_file():
            # compose down removes the container (+ networks); --volumes also drops
            # the seven named volumes. Without --volumes they are preserved.
            query(driver_down_argv(host_rec, compose_project(name), compose_file, purge))
        else:
            # No compose file (e.g. a pre-compose container): fall back to rm and,
            # on purge, explicit volume removal.
            query(driver_runtime_argv(host_rec) + ["rm", "-f", cname])
            if purge:
                for vname in vols:
                    query(driver_runtime_argv(host_rec) + ["volume", "rm", vname])
        # `rm`/compose-down returns before the daemon frees the published port;
        # wait so an immediate re-`up` on the same name doesn't hit 'port in use'.
        if host_is_local(host_rec):
            wait_port_released(port_for_name(name))
    else:
        log(f"no container named {cname} on {host_name}")

    if purge:
        compose_file.unlink(missing_ok=True)  # the derived artifact goes too
        log(f"purged volumes: {', '.join(vols)}")
    else:
        log(f"volumes preserved (use --purge to remove): {', '.join(vols)}")

    clear_state(host_name, name)


# Host-side paths of the persisted SSH material inside the container (rootless,
# dev-owned). Kept in sync with entrypoint.sh / the Dockerfile HostKey directive.
CONTAINER_HOSTKEY = "/home/dev/.ssh/hostkeys/ssh_host_ed25519_key"
CONTAINER_AUTHKEYS = "/home/dev/.ssh/authorized_keys"


def inject_keys(rt: str, name: str, host_key: Path | None, authorized_keys: list[Path]) -> None:
    """Inject an SSH host key and/or authorized_keys into a RUNNING container,
    onto the persisted ~/.ssh volume, without recreating it. The host key is
    copied in and installed (then sshd is HUP-reloaded); public keys are
    streamed over stdin (never on argv) and merged with dedup. Rootless: every
    in-container step runs as the dev user, no sudo."""
    cname = container_name(name)
    if host_key is not None:
        hk = host_key.expanduser()
        if not hk.is_file():
            die(f"--host-key: {host_key} does not exist or is not a file")
        validate_private_key(hk)
        # Stream the key over stdin (not `cp`): `cp` lands it owned by the host
        # uid, unreadable by the rootless `dev` user. Writing via `cat` inside
        # the container gives dev ownership, and the key never touches argv.
        install_sh = (
            f"umask 077; mkdir -p /home/dev/.ssh/hostkeys; "
            f"cat > {CONTAINER_HOSTKEY}; chmod 600 {CONTAINER_HOSTKEY}; "
            f"ssh-keygen -y -f {CONTAINER_HOSTKEY} > {CONTAINER_HOSTKEY}.pub && "
            f"pkill -HUP -x sshd"
        )
        r = subprocess.run(
            [rt, "exec", "-i", cname, "bash", "-lc", install_sh], input=hk.read_bytes()
        )
        if r.returncode != 0:
            die(f"failed to install host key in {cname}")
        log(f"installed host key into {cname} and reloaded sshd")
    for p in authorized_keys:
        pk = p.expanduser()
        if not pk.is_file():
            die(f"--authorized-key: {p} does not exist or is not a file")
        append_sh = (
            f"umask 077; mkdir -p /home/dev/.ssh; cat >> {CONTAINER_AUTHKEYS}; "
            f"awk 'NF && !seen[$0]++' {CONTAINER_AUTHKEYS} > {CONTAINER_AUTHKEYS}.tmp && "
            f"mv {CONTAINER_AUTHKEYS}.tmp {CONTAINER_AUTHKEYS}; chmod 600 {CONTAINER_AUTHKEYS}"
        )
        r = subprocess.run(
            [rt, "exec", "-i", cname, "bash", "-lc", append_sh], input=pk.read_bytes()
        )
        if r.returncode != 0:
            die(f"failed to inject authorized key {p}")
        log(f"injected authorized key {pk.name} into {cname}")


def cli_keys(name: str, host_key: Path | None, authorized_keys: list[Path]) -> None:
    validate_name(name)
    if host_key is None and not authorized_keys:
        die("keys: nothing to inject — pass --host-key and/or --authorized-key")
    rt = detect_runtime()
    cname = container_name(name)
    if not container_running(rt, cname):
        die(f"container {cname} is not running. Start it first: agent-container up {name}")
    inject_keys(rt, name, host_key, authorized_keys)


def cli_down(name: str, purge: bool, yes: bool, host: str | None = None) -> None:
    validate_name(name)
    host_name, host_rec = resolve_deploy_host(host)

    if host_is_local(host_rec) and quadlet_active(name):
        warn(
            f"systemd user unit {container_name(name)}.service is active; "
            f"systemd will restart the container after removal. Manage it via Quadlet instead."
        )
        if not yes:
            eprint("[agent-container] re-run with -y/--yes to proceed despite the active unit")
            raise typer.Exit(2)

    if not yes:
        if not is_tty():
            eprint("[agent-container] refusing destructive 'down' without -y/--yes on a non-TTY")
            raise typer.Exit(2)
        what = f"stop and remove {container_name(name)} on {host_name}"
        if purge:
            what += (
                f" and DELETE all per-container volumes ({', '.join(per_container_volumes(name))})"
            )
        if not questionary.confirm(f"{what}?", default=False).ask():
            log("aborted")
            return

    down_container(host_name, host_rec, name, purge)


def gather_rows(rt: str) -> list[dict[str, object]]:
    """Rows for `list`. Live status comes from the LOCAL runtime; containers on
    other hosts are surfaced from their per-host state files (querying every
    remote daemon on each `list` is deferred to the lifecycle feature)."""
    rows: list[dict[str, object]] = []
    local_running: set[str] = set()
    for cname, image, status, uptime in ps_agent_container(rt):
        short = cname[len(CONTAINER_PREFIX) :]
        local_running.add(short)
        rows.append(
            {
                "name": cname,
                "host": DEFAULT_HOST,
                "port": read_state_port(DEFAULT_HOST, short) or "?",
                "image": image,
                "status": status,
                "uptime": uptime,
                "stale": False,
            }
        )
    # Per-host state files (local orphans + containers on other hosts).
    if STATE_DIR.is_dir():
        for host_dir in sorted(p for p in STATE_DIR.iterdir() if p.is_dir()):
            hname = host_dir.name
            for f in sorted(host_dir.glob("*.port")):
                short = f.stem
                if hname == DEFAULT_HOST and short in local_running:
                    continue
                is_local = hname == DEFAULT_HOST
                rows.append(
                    {
                        "name": container_name(short),
                        "host": hname,
                        "port": read_state_port(hname, short) or "?",
                        "image": "-",
                        "status": "stale" if is_local else "on remote host",
                        "uptime": "-",
                        "stale": is_local,
                    }
                )
    return rows


def do_list(as_json: bool) -> None:
    migrate_flat_state()
    rt = detect_runtime()
    rows = gather_rows(rt)
    if as_json:
        print(json.dumps(rows, indent=2))
        return
    table = Table(show_header=True, header_style="bold", box=None, pad_edge=False)
    for col in ("NAME", "HOST", "PORT", "IMAGE", "STATUS", "UPTIME"):
        table.add_column(col)
    for row in rows:
        style = "dim" if row["stale"] else None
        table.add_row(
            str(row["name"]),
            str(row["host"]),
            str(row["port"]),
            str(row["image"]),
            str(row["status"]),
            str(row["uptime"]),
            style=style,
        )
    console.print(table)


def ssh_argv(user: str, host: str, port: str | int, window: str | None = None) -> list[str]:
    # The one true attach command; argv list, never a shell string. Without a
    # window the argv is unchanged (agent-container parity). With one, the remote
    # command is a SINGLE compound string that selects the window (tolerating
    # its absence) THEN attaches — select-window works on a detached session.
    base = ["ssh", f"{user}@{host}", "-p", str(port), "-t"]
    if window:
        return base + [f"tmux select-window -t main:{window} 2>/dev/null; exec tmux attach -t main"]
    return base + ["tmux", "attach", "-t", "main"]


def tmux_nest_warning() -> str | None:
    if os.environ.get("TMUX"):
        return "already inside tmux; detach the INNER session with Ctrl-B Ctrl-B d"
    return None


def resolve_attach_target(
    name: str,
    mode: str,  # "auto" | "local" | "remote"
    user_override: str | None = None,
    host_override: str | None = None,
) -> tuple[str, str, str, str]:
    """Returns (user, host, port, kind). kind is 'local' or 'remote'."""
    # Case-insensitive like agent-container: 'My-Box' resolves the same
    # MY_BOX_* keys (and the same lowercase state file agent-container writes).
    name = validate_name(name.lower())
    user = resolve_ssh_user(user_override)
    if host_override is not None and not SSH_HOST_RE.fullmatch(host_override):
        die(f"invalid ssh host '{host_override}'")
    key = name_to_key(name)

    if mode == "remote" and not HOSTS_CONF.is_file():
        die(f"no hosts config at {HOSTS_CONF} — create it (see docs/agent-container-hosts.example)")

    entry = hosts_entry(name)
    if mode == "remote" or (mode == "auto" and entry is not None):
        if entry is None:
            die(f"no host configured for {name} — add {key}_HOST and {key}_PORT to {HOSTS_CONF}")
        host, port = entry
        return user, host_override or host, port, "remote"

    # Local target: per-host state under the implicit 'local' host. (Attaching to
    # a specific registered host by name is a follow-up; today `up`/`down` carry
    # --host and local attach covers the default-host loop.)
    port = read_state_port(DEFAULT_HOST, name)
    if port is None:
        sf = state_file_for(DEFAULT_HOST, name)
        if mode == "local":
            die(
                f"no local state for {name} at {sf} — is the container "
                f"running? (try: agent-container up {name})"
            )
        die(
            f"no attach target for {name}; checked {HOSTS_CONF} (no {key}_HOST/{key}_PORT) and {sf}"
        )
    host = host_override or os.environ.get("AGENT_CONTAINER_HOST") or "localhost"
    return user, host, port, "local"


def cli_attach(
    name: str,
    mode: str,
    user_override: str | None,
    host_override: str | None,
    window: str | None = None,
) -> None:
    # Validate the window BEFORE resolving/building the command (it is embedded
    # in the remote shell string).
    if window:
        validate_window(window)
    migrate_flat_state()
    user, host, port, _ = resolve_attach_target(name, mode, user_override, host_override)
    if w := tmux_nest_warning():
        warn(w)  # CLI mode: warn and proceed
    session = '"main"' + (f', window "{window}"' if window else "")
    eprint(f"agent-container: {user}@{host}:{port} (tmux session {session})")
    sys.stdout.flush()
    sys.stderr.flush()
    # Full handover: the process is replaced; signals, SIGWINCH, TTY ownership
    # and the exit code belong to ssh — identical to bash `exec ssh`.
    os.execvp("ssh", ssh_argv(user, host, port, window))


def _child_default_sigint() -> None:
    # SIG_IGN survives exec; without this reset a child spawned while the
    # parent shields itself from Ctrl-C would ignore SIGINT too.
    signal.signal(signal.SIGINT, signal.SIG_DFL)


def wizard_handover(
    user: str,
    host: str,
    port: str,
    logs_hint: str = "agent-container logs <name>",
    window: str | None = None,
) -> None:
    """Attach without killing the wizard: inherited-stdio subprocess + cleanup."""
    target = f"{user}@{host}:{port}"
    session = '"main"' + (f', window "{window}"' if window else "")
    eprint(f"agent-container: {target} (tmux session {session})")
    sys.stdout.flush()
    sys.stderr.flush()
    old_int = signal.signal(signal.SIGINT, signal.SIG_IGN)  # Ctrl-C goes to ssh only
    try:
        rc = subprocess.run(
            ssh_argv(user, host, port, window), preexec_fn=_child_default_sigint
        ).returncode
    finally:
        signal.signal(signal.SIGINT, old_int)
        if _ORIG_TERMIOS is not None:
            try:
                termios.tcsetattr(sys.stdin.fileno(), termios.TCSADRAIN, _ORIG_TERMIOS)
            except Exception:
                pass
    if rc == 0:
        console.print(
            f"Detached — tmux session 'main' is still running on {target}; agents keep working."
        )
    elif rc == 255:
        warn(f"ssh could not connect to {target}; check hosts.conf or the container state.")
    else:
        warn(
            f"remote command failed (exit {rc}); likely 'tmux attach' found no session "
            f"'main'. Check the entrypoint via: {logs_hint}"
        )


def do_logs(name: str, follow: bool) -> int:
    validate_name(name)
    rt = detect_runtime()
    argv = [rt, "logs"] + (["-f"] if follow else []) + [container_name(name)]
    try:
        return subprocess.run(argv).returncode  # inherited stdio
    except KeyboardInterrupt:
        return 130


# --- wizard ------------------------------------------------------------------
# Lifecycle pickers (start/stop/purge/logs) list LOCAL containers only;
# remote (hosts.conf) targets appear exclusively in the Attach picker.


def _validate_wiz_name(text: str):  # questionary validator: True or error string
    return True if NAME_RE.fullmatch(text) else "must match [a-z0-9][a-z0-9_-]*"


def _short(cname: str) -> str:
    return cname[len(CONTAINER_PREFIX) :]


def wiz_build(rt: str) -> None:
    tag = questionary.text("image tag", default=IMAGE_NAME).ask()
    if not tag:
        return
    do_build(tag)
    hint("agent-container build" + (f" {tag}" if tag != IMAGE_NAME else ""))


def wiz_up(rt: str) -> None:
    name = questionary.text("container name", validate=_validate_wiz_name).ask()
    if not name:
        return
    migrate_flat_state()
    cname = container_name(name)
    host_rec = implicit_local_host(rt)  # the wizard deploys to the local host

    if cname in host_container_names(host_rec):
        port = read_state_port(DEFAULT_HOST, name)
        log(f"container {cname} already running" + (f" on port {port}" if port else ""))
        return
    if cname in host_container_names(host_rec, include_stopped=True):
        log(f"container {cname} exists but is stopped — remove it first (Stop / remove)")
        return

    env_file = resolve_env_file(name)
    if env_file is None:
        eprint("[agent-container] no env file found; looked in:")
        for c in env_file_candidates(name, Path.cwd()):
            eprint(f"  {c}")
        target = CONFIG_DIR / f"{name}.env"
        if questionary.confirm(f"create/edit {target} in $EDITOR now?", default=True).ask():
            CONFIG_DIR.mkdir(parents=True, exist_ok=True)
            # $EDITOR gets the path only; agent-container never reads env contents.
            subprocess.run([os.environ.get("EDITOR") or "vi", str(target)])
            env_file = resolve_env_file(name)
        if env_file is None:
            log("still no env file; not starting")
            return

    # Optional single host-dir bind (empty = none). Resolved now so a bad path
    # surfaces before the confirmation card; Fatal returns to the menu.
    mounts: list[str] = []
    mount_dir = questionary.text(
        "host directory to mount read-write (empty = none)", default=""
    ).ask()
    if mount_dir:
        mounts = [resolve_bind_mount(mount_dir)]

    card = Table(show_header=False, box=None, pad_edge=False)
    card.add_column(style="bold")
    card.add_column()
    card.add_row("env-file", str(env_file))  # path only, never contents
    card.add_row("port", str(port_for_name(name)))
    card.add_row("volumes", ", ".join(per_container_volumes(name)))
    if mounts:
        card.add_row("bind", mounts[0])
    card.add_row("image", "built on host via compose")
    console.print(card)

    if not questionary.confirm(f"start {cname}?", default=True).ask():
        return
    # Compose build + up (port pre-check + actionable abort inside).
    compose_up_exec(DEFAULT_HOST, host_rec, name, env_file, mounts, None, [])
    hint(f"agent-container up {name}" + (f" --mount {mount_dir}" if mounts else ""))


def wiz_attach(rt: str) -> None:
    choices: list[questionary.Choice] = []
    for cname, _image, _status, _uptime in ps_agent_container(rt):
        short = _short(cname)
        port = read_state_port(DEFAULT_HOST, short) or "?"
        choices.append(
            questionary.Choice(f"{short}  [local :{port}]", value=("local", short, "", ""))
        )
    conf = load_hosts_conf()
    for key in sorted(conf):
        if not key.endswith("_HOST"):
            continue
        base = key[: -len("_HOST")]
        host, port = conf[key], conf.get(f"{base}_PORT")
        if not (host and port):
            continue
        rname = base.lower()  # round-trips through name_to_key for the hint
        choices.append(
            questionary.Choice(
                f"{rname}  [remote {host}:{port}]", value=("remote", rname, host, port)
            )
        )
    if not choices:
        log("nothing to attach to: no running local containers and no hosts.conf entries")
        return

    sel = questionary.select("attach to", choices=choices).ask()
    if sel is None:
        return
    if w := tmux_nest_warning():
        warn(w)
        if not questionary.confirm("continue attaching?", default=True).ask():
            return

    # Optional window to select before attaching (empty = session default).
    # Validated now so a bad name aborts back to the menu (Fatal is caught there).
    window = questionary.text("window to select (empty = default)", default="").ask() or None
    if window:
        validate_window(window)

    kind, name, host, port = sel
    user = resolve_ssh_user()
    if kind == "local":
        port = read_state_port(DEFAULT_HOST, name)
        if port is None:  # TOCTOU: state file vanished since the picker rendered
            warn(f"state file for {name} disappeared; is the container still up?")
            return
        host = os.environ.get("AGENT_CONTAINER_HOST") or "localhost"
    wizard_handover(user, host, port, logs_hint=f"agent-container logs {name}", window=window)
    hint(f"agent-container attach {name} --{kind}" + (f" --window {window}" if window else ""))


def wiz_logs(rt: str) -> None:
    rows = ps_agent_container(rt)
    if not rows:
        log("no running agent-container containers")
        return
    sel = questionary.select("logs for", choices=[_short(r[0]) for r in rows]).ask()
    if sel is None:
        return
    log("streaming logs — Ctrl-C returns to the menu")
    old_int = signal.signal(signal.SIGINT, signal.SIG_IGN)  # Ctrl-C stops the tail only
    try:
        subprocess.run([rt, "logs", "-f", container_name(sel)], preexec_fn=_child_default_sigint)
    finally:
        signal.signal(signal.SIGINT, old_int)
    hint(f"agent-container logs {sel}")


def wiz_down(rt: str) -> None:
    rows = ps_agent_container(rt, include_stopped=True)
    if not rows:
        log("no agent-container containers (running or stopped)")
        return
    choices = []
    for cname, _image, status, _uptime in rows:
        short = _short(cname)
        label = f"{short}  [exited]" if status.lower().startswith("exited") else short
        choices.append(questionary.Choice(label, value=short))
    sel = questionary.select("stop / remove", choices=choices).ask()
    if sel is None:
        return
    cname = container_name(sel)

    if not container_exists(rt, cname):  # TOCTOU re-verify
        warn(f"container {cname} no longer exists")
        return
    if quadlet_active(sel):
        warn(
            f"systemd user unit {cname}.service is active; systemd will restart "
            f"the container after removal. Manage it via Quadlet instead."
        )
        if not questionary.confirm("proceed anyway?", default=False).ask():
            return
    if not questionary.confirm(f"stop and remove {cname}?", default=False).ask():
        log("aborted")
        return

    purge = False
    vols = per_container_volumes(sel)
    if questionary.confirm(
        f"also delete ALL per-container volumes ({', '.join(vols)})?", default=False
    ).ask():
        typed = questionary.text(
            f"type the container name ({cname}) to confirm volume deletion"
        ).ask()
        if typed == cname:
            purge = True
        else:
            log("name mismatch — volumes will be preserved")
    down_container(DEFAULT_HOST, implicit_local_host(rt), sel, purge)  # reports + clears state
    hint(f"agent-container down {sel}" + (" --purge" if purge else ""))


def _volume_names(rt: str) -> list[str]:
    out = query([rt, "volume", "ls", "--format", "{{.Name}}"]).stdout.splitlines()
    return [v for v in out if re.fullmatch(re.escape(CONTAINER_PREFIX) + r".+-workspace", v)]


def wiz_purge_volume(rt: str) -> None:
    containers = {row[0] for row in ps_agent_container(rt, include_stopped=True)}
    orphans = []
    for vol in _volume_names(rt):
        short = vol[len(CONTAINER_PREFIX) : -len("-workspace")]
        if container_name(short) not in containers:
            orphans.append(vol)
    if not orphans:
        log("no orphaned agent-container volumes")
        return
    sel = questionary.select("purge orphaned volume", choices=orphans).ask()
    if sel is None:
        return
    typed = questionary.text(f"type the volume name ({sel}) to confirm deletion").ask()
    if typed != sel:
        log("name mismatch — nothing removed")
        return
    if sel not in _volume_names(rt):  # TOCTOU re-verify
        warn(f"volume {sel} no longer exists")
        return
    if query([rt, "volume", "rm", sel]).returncode != 0:
        warn(f"volume {sel} not removed (in use)")
    else:
        log(f"volume {sel} purged")
    hint(f"{rt} volume rm {sel}")


def wiz_keys(rt: str) -> None:
    rows = ps_agent_container(rt, include_stopped=False)  # running only
    if not rows:
        log("no running agent-container containers")
        return
    sel = questionary.select("inject SSH keys into", choices=[_short(r[0]) for r in rows]).ask()
    if sel is None:
        return
    hk = questionary.text("host key path (unencrypted ed25519 private key; blank to skip)").ask()
    ak = questionary.text("authorized public key path (blank to skip)").ask()
    host_key = Path(hk).expanduser() if hk else None
    authorized = [Path(ak).expanduser()] if ak else []
    if host_key is None and not authorized:
        log("nothing to inject")
        return
    inject_keys(rt, sel, host_key, authorized)
    hint(
        f"agent-container keys {sel}"
        + (f" --host-key {hk}" if hk else "")
        + (f" --authorized-key {ak}" if ak else "")
    )


_MENU: list[tuple[str, Callable[[str], None] | None]] = [
    ("Provision (build image)", wiz_build),
    ("Start a container", wiz_up),
    ("Attach", wiz_attach),
    ("Inject SSH keys", wiz_keys),
    ("Logs", wiz_logs),
    ("Stop / remove", wiz_down),
    ("Purge orphaned volume", wiz_purge_volume),
    ("Quit", None),
]


def wizard_loop() -> int:
    if not is_tty():
        eprint(
            "[agent-container] no TTY; interactive wizard unavailable. Use subcommands (agent-container --help)."
        )
        return 2
    try:
        rt = detect_runtime()
    except Fatal as e:
        eprint(f"[agent-container] FATAL: {e}")
        return 1
    actions = dict(_MENU)
    while True:
        try:
            running = len(ps_agent_container(rt))
            hosts = "present" if HOSTS_CONF.is_file() else "absent"
            console.print(
                f"runtime: {rt} | running local containers: {running} | hosts.conf: {hosts}",
                style="dim",
            )
            choice = questionary.select(
                "agent-container — what now?", choices=[t for t, _ in _MENU]
            ).ask()
            if choice is None or choice == "Quit":
                return 0
            try:
                action = actions[choice]
                if action is not None:
                    action(rt)
            except Fatal as e:
                eprint(f"[agent-container] ERROR: {e}")  # back to the menu, not exit
        except KeyboardInterrupt, EOFError:
            return 0


# --- entry -------------------------------------------------------------------

app = typer.Typer(
    add_completion=False,
    no_args_is_help=False,
    pretty_exceptions_enable=False,
    help="Interactive wizard + CLI for agent-container containers.",
)


def fatal_exit(e: Fatal) -> NoReturn:
    eprint(f"[agent-container] FATAL: {e}")
    raise typer.Exit(1)


def run_self_test() -> int:
    import doctest

    failures, tests = doctest.testmod(
        sys.modules[__name__], optionflags=doctest.IGNORE_EXCEPTION_DETAIL
    )
    # Hard-coded port corpus: pins the deterministic port hash against regressions.
    corpus = {
        "acme": 2206,
        "blog": 2220,
        "scratch": 2244,
        "my-box": 2204,
        "a": 2297,
        "devbox123": 2298,
    }
    bad = {n: (port_for_name(n), want) for n, want in corpus.items() if port_for_name(n) != want}
    keys_ok = name_to_key("my-box") == "MY_BOX" and name_to_key("acme") == "ACME"
    ok = failures == 0 and not bad and keys_ok
    print(f"doctests: {tests - failures}/{tests} passed")
    print(f"port corpus: {'ok' if not bad else f'MISMATCH {bad}'}")
    print(f"key derivation: {'ok' if keys_ok else 'MISMATCH'}")
    print("self-test:", "PASS" if ok else "FAIL")
    return 0 if ok else 1


@app.command()
def build(
    tag: str = typer.Argument(IMAGE_NAME, help="Image tag to build."),
    context: Path | None = typer.Option(
        None,
        "--context",
        help="Docker build context (repo checkout). Defaults to AGENT_CONTAINER_REPO "
        "or the auto-detected checkout; required when installed from PyPI.",
    ),
) -> None:
    """Build the image from a repo checkout (streams build output)."""
    do_build(tag, context)


@app.command()
def up(
    name: str = typer.Argument(..., help="Container short name (agent-container-<name>)."),
    host: str | None = typer.Option(
        None, "--host", help="Deploy to this registered host (default: the registry default)."
    ),
    env_file: Path | None = typer.Option(
        None, "--env-file", help="Bypass env-file resolution; path must exist."
    ),
    mount: list[str] = typer.Option(
        None,
        "--mount",
        help="Bind-mount a host dir read-write (repeatable): HOSTDIR[:CONTAINERPATH]. "
        "Default CONTAINERPATH is /workspace/<basename>. Lima: host dir must be "
        "under a writable Lima mount.",
    ),
    host_key: Path | None = typer.Option(
        None,
        "--host-key",
        help="Inject an OpenSSH ed25519 PRIVATE host key so the container adopts "
        "a known SSH identity (persisted on the ~/.ssh volume). Must be "
        "unencrypted.",
    ),
    authorized_key: list[Path] = typer.Option(
        None,
        "--authorized-key",
        help="Inject an SSH public key into authorized_keys (repeatable), so you "
        "can attach without a manual exec. Persisted on the ~/.ssh volume.",
    ),
) -> None:
    """Start container agent-container-NAME (detached)."""
    if env_file is not None and not env_file.is_file():
        raise typer.BadParameter(f"--env-file {env_file} does not exist")
    do_up(name, host, env_file, mount or [], host_key, authorized_key or [])


@app.command()
def keys(
    name: str = typer.Argument(..., help="Container short name."),
    host_key: Path | None = typer.Option(
        None,
        "--host-key",
        help="Install an unencrypted ed25519 PRIVATE host key into the running "
        "container and reload sshd (persists on the ~/.ssh volume).",
    ),
    authorized_key: list[Path] = typer.Option(
        None,
        "--authorized-key",
        help="Append an SSH public key to authorized_keys in the running "
        "container (repeatable; deduped; persists on the ~/.ssh volume).",
    ),
) -> None:
    """Inject SSH host key / authorized keys into a RUNNING container (no recreate)."""
    cli_keys(name, host_key, authorized_key or [])


@app.command()
def down(
    name: str = typer.Argument(..., help="Container short name."),
    host: str | None = typer.Option(
        None, "--host", help="Host the container runs on (default: the registry default)."
    ),
    purge: bool = typer.Option(
        False,
        "--purge",
        help="Also delete all seven per-container volumes (workspace + agent logins, shell env, tmux config, ssh).",
    ),
    yes: bool = typer.Option(False, "-y", "--yes", help="Skip confirmation."),
) -> None:
    """Stop and remove container agent-container-NAME."""
    cli_down(name, purge, yes, host)


@app.command()
def purge(
    name: str = typer.Argument(..., help="Container short name."),
    yes: bool = typer.Option(False, "-y", "--yes", help="Skip confirmation."),
) -> None:
    """Sugar for: down NAME --purge."""
    cli_down(name, purge=True, yes=yes)


@app.command(name="list")
def list_cmd(
    as_json: bool = typer.Option(False, "--json", help="Emit machine-readable JSON."),
) -> None:
    """List running agent-container containers (plus stale state files)."""
    do_list(as_json)


# The `host` group manages WHERE containers run (registered targets). Container
# lifecycle (up/down/attach/logs) stays as bare top-level verbs; a container is
# addressed by name and lives on a host chosen with --host (default: the registry
# default). There is deliberately no `host up`/`host down` — those are container
# operations, not host operations. Deprovisioning a host is `host rm` (later).
host_app = typer.Typer(
    no_args_is_help=True,
    help="Manage deployment hosts (the machines/contexts where containers run).",
)
app.add_typer(host_app, name="host")


@host_app.command("add")
def host_add(
    name: str = typer.Argument(..., help="Host short name (registry key)."),
    driver: str = typer.Option("docker", "--driver", help="Runtime driver: docker or podman."),
    docker_context: str | None = typer.Option(
        None,
        "--docker-context",
        help="Existing docker context (local endpoint or ssh://user@host).",
    ),
    connection: str | None = typer.Option(
        None, "--connection", help="Podman system connection name (for --driver podman)."
    ),
    address: str | None = typer.Option(
        None, "--address", help="Attach address override (default: derived from the context)."
    ),
    make_default: bool = typer.Option(
        False, "--default", help="Make this the default deploy target."
    ),
) -> None:
    """Register a container-runtime host (where `up --host NAME` deploys)."""
    cli_host_add(name, driver, docker_context or connection, address, make_default)


@host_app.command("ls")
def host_ls(
    as_json: bool = typer.Option(False, "--json", help="Emit machine-readable JSON."),
) -> None:
    """List registered hosts (name, driver, context, address, default)."""
    do_host_ls(as_json)


@app.command()
def attach(
    name: str = typer.Argument(..., help="Container short name."),
    local: bool = typer.Option(False, "--local", help="Force local target (state file)."),
    remote: bool = typer.Option(False, "--remote", help="Force remote target (hosts.conf)."),
    user: str | None = typer.Option(
        None, "--user", help="SSH user (default: AGENT_CONTAINER_USER or dev)."
    ),
    host: str | None = typer.Option(None, "--host", help="Override the resolved host."),
    window: str | None = typer.Option(
        None, "--window", "-w", help="Select tmux window NAME (session 'main') before attaching."
    ),
) -> None:
    """ssh + tmux attach to container NAME (local state file or hosts.conf)."""
    if local and remote:
        raise typer.BadParameter("--local and --remote are mutually exclusive")
    mode = "local" if local else ("remote" if remote else "auto")
    cli_attach(name, mode, user, host, window)


@app.command()
def logs(
    name: str = typer.Argument(..., help="Container short name."),
    no_follow: bool = typer.Option(False, "--no-follow", help="Print logs without following."),
) -> None:
    """Tail container logs."""
    raise typer.Exit(do_logs(name, follow=not no_follow))


@app.command()
def menu() -> None:
    """Interactive wizard (same as bare agent-container)."""
    raise typer.Exit(wizard_loop())


def _completion_script(shell: str) -> str:
    """Return the bash/zsh completion script text.

    Prefers the on-disk checkout (dev / `uv run --script`, where REPO_ROOT
    resolves via the __file__ marker); falls back to the completions bundled as
    package data in a non-editable PyPI install (where REPO_ROOT is None).
    """
    if REPO_ROOT is not None:
        p = REPO_ROOT / "completions" / f"agent-container.{shell}"
        if p.is_file():
            return p.read_text()
    try:
        import importlib.resources as ir

        res = ir.files("agent_container").joinpath(f"completions/agent-container.{shell}")
        if res.is_file():
            return res.read_text()
    except ModuleNotFoundError, ImportError, FileNotFoundError, TypeError, AttributeError:
        pass
    die(f"completion script for '{shell}' not found (need a checkout or an installed package)")


@app.command()
def completions(
    # Optional + manual validation so a bad/missing shell routes through die()
    # (exit 1, '[agent-container] FATAL:' style), not Typer's exit-2 required-arg error.
    shell: str = typer.Argument("", help="Shell to emit completion for: bash or zsh."),
) -> None:
    """Print the completion script for bash or zsh (from a checkout or package data)."""
    if shell not in ("bash", "zsh"):
        die("usage: agent-container completions <bash|zsh>")
    sys.stdout.write(_completion_script(shell))


def _resolve_version() -> str:
    """The tool's version, single-sourced from pyproject.toml. When installed
    (wheel), it is read from package metadata; when run via `uv run --script`
    from a checkout, it is read from pyproject directly — no hardcoded constant
    to drift from the release version release-please bumps."""
    try:
        from importlib.metadata import PackageNotFoundError, version

        return version("agent-container")
    except PackageNotFoundError:
        pass
    if REPO_ROOT is not None:
        try:
            import tomllib

            with (REPO_ROOT / "pyproject.toml").open("rb") as f:
                return tomllib.load(f)["project"]["version"]
        except Exception:
            pass
    return "0.0.0+unknown"


def _version_callback(value: bool) -> None:
    if value:
        typer.echo(_resolve_version())
        raise typer.Exit()


@app.callback(invoke_without_command=True)
def main(
    ctx: typer.Context,
    self_test: bool = typer.Option(
        False, "--self-test", help="Run doctests + port-hash corpus checks."
    ),
    version: bool = typer.Option(
        False,
        "--version",
        callback=_version_callback,
        is_eager=True,
        help="Show the agent-container version and exit.",
    ),
) -> None:
    if self_test:
        raise typer.Exit(run_self_test())
    if ctx.invoked_subcommand is None:
        raise typer.Exit(wizard_loop())


def cli() -> None:
    """Console-script entry point for `uv tool install` (see pyproject.toml).

    uv's generated launcher does `from agent_container import cli; sys.exit(cli())`,
    so the Fatal -> exit-1 handling that used to live only in the __main__ guard
    is hoisted here. NOT named `main` — that is already the Typer @app.callback.
    """
    try:
        app()
    except Fatal as e:
        eprint(f"[agent-container] FATAL: {e}")
        sys.exit(1)


if __name__ == "__main__":
    cli()
