"""镜像消费端 PodmanClient 封装。

后端优先级：
  Tier 1: podman-py SDK（声明式 API，pyproject 已强制依赖）
  Tier 2: CLI subprocess（保底路径，当 SDK 连接失败 / 版本不兼容时）

rootless 三必需参数（/dev/fuse、label=disable、cgroupns=host）
由 utils.ContainerConfig 默认值内置，调用方无需显式传入。
"""
import json
import os
from pathlib import Path
import shutil
import subprocess
from typing import Optional

from invoke import Context
from invoke.exceptions import Exit

# SDK 连接统一层（get_client 全候选探测 / APIError / B-scheme socket / W-I*诊断）
# 的唯一实现位于组内共享包 jpman_common.connection，client 不再私有副本。
from jpman_common.connection import (
    APIError,
    PodmanNotFound,
    bsock_missing_guidance,
    ensure_host_podman_socket,
    get_client,
    podman_sock_path,
    sdk_available,
    windows_diagnose_hint,
)

from .utils import (
    ContainerConfig,
    LoadImageResult,
    build_passthrough_spec,
    check_runtime_ready,
    container_exists as cli_container_exists,
    container_running as cli_container_running,
    detect_runtime,
    generate_random_string,
    image_load_cli_command,
    passthrough_diagnose_hint,
    run_cmd,
    to_posix_path,
)


# ===========================================================================
# 镜像管理：加载 + 查询
# ===========================================================================


def _load_via_sdk(client, tar_path: Path) -> LoadImageResult:
    """通过 podman-py SDK 加载镜像 tar。

    podman-py 5.x 的 ``ImagesManager.load`` 支持两种互斥参数：
      * ``file_path`` (:class:`os.PathLike`) — SDK 内部自行 open 读取，零内存拷贝，推荐。
      * ``data`` (:class:`bytes`) — SDK 内部 ``io.BytesIO(data)`` 包装，**不能传 file-like**
        （否则 ``io.BytesIO`` 抛 ``a bytes-like object is required, not BufferedReader``）。
    """
    try:
        loaded = client.images.load(file_path=tar_path)
        tags: list[str] = []
        img_id = ""
        if isinstance(loaded, list) and loaded:
            # podman-py 5.x: 返回 Image 对象列表（签名是 Generator 但实际调用端可能是 list）
            first = loaded[0]
            img_id = getattr(first, "short_id", "") or getattr(first, "id", "")
            tags = list(getattr(first, "tags", []) or [])
        elif hasattr(loaded, "__iter__") and not isinstance(loaded, (str, bytes, list)):
            # Generator 情况（严格按 podman-py 签名）
            items = list(loaded)
            if items:
                first = items[0]
                img_id = getattr(first, "short_id", "") or getattr(first, "id", "")
                tags = list(getattr(first, "tags", []) or [])
        return LoadImageResult(
            loaded=True,
            tags=tags,
            id=img_id,
            message=f"[SDK] 已加载镜像（file_path={tar_path}）",
        )
    except Exception as e:
        return LoadImageResult(loaded=False, message=f"[SDK] 加载失败: {e}")



def _load_via_cli(c: Context, tar_path: Path) -> LoadImageResult:
    """通过 podman load 命令加载镜像 tar。

    命令构造按平台分流（唯一事实源 ``utils.image_load_cli_command``）：
      - Windows 原生：``type "<file>" | <runtime> load``（stdin 管道，规避
        Windows→WSL2 远距 daemon 大文件传输 EOF 的历史实测问题）；
      - POSIX（Linux/WSL2 内/macOS/容器内）：``<runtime> load -i "<file>"``。
        禁止 POSIX 走管道：``type`` 在 POSIX shell 是"命令类型"内建而非读文件；
        且 podman 3.4.x 的 stdin 路径对未压缩 docker-archive 会误报
        "payload does not match ..."（同文件 ``-i`` 正常，2026-09-12 实测）。

    注意：
    - Windows PowerShell/cmd 管道退出码不可靠，因此以 stdout 是否包含
      "Loaded image" 作为成功判断依据，而非 exit code（podman 3.x 输出
      "Loaded image(s):"、4/5.x 输出 "Loaded image:"，均含该子串）。
    - 以 ``warn=True`` 调用 run_cmd：命令失败时返回 Result 而不抛异常，使下方
      「Podman machine 未运行」与「归档格式不识别」检测分支可达（此前失败即
      raise Exit，友好提示被原生英文报错与 ``exit=125`` 掩盖）。
    """
    runtime = detect_runtime()
    result = run_cmd(
        c,
        image_load_cli_command(runtime, tar_path),
        pty=False,
        echo=True,
        warn=True,
    )

    # TTY Console 路径：subprocess.call() 成功返回 None，输出已直接写入控制台
    # 此时无法捕获 stdout，但命令已成功执行（否则会 raise Exit）
    if result is None:
        return LoadImageResult(
            loaded=True,
            tags=[],
            message="[CLI] 镜像加载完成",
        )

    _out = getattr(result, "stdout", "") or ""
    _err = getattr(result, "stderr", "") or ""
    combined = (_out + " " + _err).lower()

    # 优先检查 Podman machine 未运行的特定错误（在检查成功标志之前）
    if "cannot connect to podman" in combined or \
       "actively refused it" in combined or \
       "nonexistent pipe" in combined or \
       "exporting" in combined:
        return LoadImageResult(
            loaded=False,
            message=(
                "[CLI] Podman machine 未运行。\n"
                "解决方法：在终端执行以下命令启动 Podman machine：\n"
                "  podman machine start\n"
                "如需初始化：podman machine init"
            )
        )

    # 归档格式不识别（C-I4）：POSIX 已走 `load -i`，仍命中本错误说明不是
    # shell 管道问题，而是「运行时版本 × 归档特性」不兼容或文件损坏。
    # 必须把原生报错翻译为可执行指引，否则用户只看到 exit=125 无法分流
    # （2026-09-12 事故：tar 完好但管道喂入方式错误，现象与本错误相同）。
    if "payload does not match" in combined or "supported image formats" in combined:
        return LoadImageResult(
            loaded=False,
            message=(
                "[CLI] podman 无法识别该镜像归档（payload does not match）。排查顺序：\n"
                f"  1) 手动复核归档结构: tar tf {tar_path} | head（应能列出 manifest.json）\n"
                f"  2) 手动加载复核: {runtime} load -i \"{tar_path}\"\n"
                "  3) 若手动加载同样报错：多为 podman 版本过旧（如 3.4.x）无法解析"
                "新归档特性，或归档传输损坏——请升级 podman（≥4）或在构建端重新 save"
            )
        )

    # Windows PowerShell 管道退出码不可靠，以 stdout 是否含 "Loaded image" 为准
    stdout = _out
    tags: list[str] = []
    for line in stdout.splitlines():
        if "Loaded image" in line:
            name = line.split(":", 1)[1].strip()
            tags.append(name)

    if tags:
        return LoadImageResult(
            loaded=True,
            tags=tags,
            message="[CLI] 镜像加载完成",
        )

    # 没有 Loaded image 且没有已知错误 → 真正的失败。
    # 携带 podman 原生 stderr 末行（此前只报 exit 码，排查者拿不到任何线索）。
    err_lines = [ln.strip() for ln in (_err or "").splitlines() if ln.strip()]
    detail = f": {err_lines[-1]}" if err_lines else ""
    return LoadImageResult(
        loaded=False,
        message=f"[CLI] load 命令执行失败（exit={result.exited}）{detail}",
    )


def load_image(c: Context, tar_path: Path) -> LoadImageResult:
    """从本地 tar.gz 加载镜像，SDK 优先失败则走 CLI。"""
    if not tar_path.exists():
        return LoadImageResult(loaded=False, message=f"镜像文件不存在: {tar_path}")

    # 就绪预检：Podman machine 未运行时直接给出中文指引，避免执行注定失败的
    # 大文件加载（Windows `type <大文件> | podman load` / POSIX `load -i`，
    # 既浪费 IO 又只会得到英文原生报错）。
    ready, hint = check_runtime_ready()
    if not ready:
        return LoadImageResult(loaded=False, message=f"[Load] {hint}")

    print(f"[Load] 从 {tar_path} 加载镜像...")

    sdk_result: Optional[LoadImageResult] = None
    with get_client() as client:
        if client is not None:
            sdk_result = _load_via_sdk(client, tar_path)
            if sdk_result.loaded:
                print(sdk_result.message)
                if sdk_result.tags:
                    print(f"[Load] Tags: {', '.join(sdk_result.tags)}")
                return sdk_result
            # SDK 成功连接到 daemon，但加载本身失败（非连接失败）→ 仍降级 CLI，统一 [INFO][降级] 前缀
            print(f"[INFO][降级] SDK加载失败 → 走CLI fallback: {sdk_result.message}")

    cli_result = _load_via_cli(c, tar_path)
    if cli_result.loaded:
        print(cli_result.message)
        if cli_result.tags:
            print(f"[Load] Tags: {', '.join(cli_result.tags)}")
    else:
        print(cli_result.message)
    return cli_result


def _list_images_sdk(client) -> list[dict]:
    """SDK 列出本地镜像。"""
    out: list[dict] = []
    try:
        for img in client.images.list():
            tags = list(getattr(img, "tags", []) or [])
            out.append(
                {
                    "id": getattr(img, "short_id", "") or getattr(img, "id", "")[:12],
                    "tags": tags,
                    "size": getattr(img, "attrs", {}).get("Size", 0),
                    "created": getattr(img, "attrs", {}).get("Created", ""),
                }
            )
    except Exception:
        return []
    return out


def _list_images_cli(c: Context) -> list[dict]:
    """CLI 列出本地镜像。"""
    runtime = detect_runtime()
    out: list[dict] = []
    go_fmt = "{{.ID}}|{{.Repository}}:{{.Tag}}|{{.Size}}"
    result = run_cmd(
        c,
        runtime + ' images --format "' + go_fmt + '"',
        hide=True,
        warn=True,
        echo=False,
    )
    if result is None:
        return out
    for line in (getattr(result, "stdout", "") or "").splitlines():
        line = line.strip()
        if not line or "|" not in line:
            continue
        parts = line.split("|", 2)
        if len(parts) < 3:
            continue
        img_id, tag, size = parts
        tag = tag if "<none>" not in tag else ""
        out.append(
            {
                "id": img_id[:12],
                "tags": [tag] if tag else [],
                "size": size,
                "created": "",
            }
        )
    return out


def list_images(c: Context) -> list[dict]:
    """列出本地所有镜像（SDK 优先）。"""
    with get_client() as client:
        if client is not None:
            return _list_images_sdk(client)
    return _list_images_cli(c)


def image_exists(c: Context, tag: str) -> bool:
    """判断本地是否存在指定标签的镜像。"""
    images = list_images(c)
    for img in images:
        if tag in img["tags"]:
            return True
    return False


def image_inspect_info(c: Context, tag: str) -> dict:
    """读取单镜像 inspect 摘要（CLI 路径，供 run 前基底指纹检测等轻量场景）。

    走 ``podman image inspect`` 原始 JSON（而非 --format 模板），规避
    Windows cmd / Linux bash 双 shell 下模板引号与 ``$`` 变量展开差异。
    返回 ``{"digest": str, "labels": dict}``；镜像不存在或解析失败返回空 dict，
    调用方按「无指纹」降级，不得抛异常阻断主流程。
    """
    runtime = detect_runtime()
    r = run_cmd(
        c,
        f"{runtime} image inspect {tag}",
        hide=True,
        warn=True,
        echo=False,
    )
    if r is None or not getattr(r, "ok", False) or not (r.stdout or "").strip():
        return {}
    try:
        data = json.loads(r.stdout)
        info = data[0] if isinstance(data, list) and data else {}
    except (json.JSONDecodeError, IndexError, TypeError):
        info = {}
    if not isinstance(info, dict):
        return {}
    labels = info.get("Labels") or {}
    return {
        "digest": str(info.get("Digest") or "").strip(),
        "labels": labels if isinstance(labels, dict) else {},
    }


# torch 形态标签：构建期 build-arg TORCH_FLAVOR 烘入（Containerfile.native-dev），
# 是与 `/opt/native-torch-flavor` 标记文件并列的镜像内单一事实源。
TORCH_FLAVOR_LABEL = "org.specweave.torch-flavor"


def _image_torch_flavor(info: dict) -> str:
    """从 ``image_inspect_info`` 的 labels 取 torch 形态（无该 LABEL 返回空串）。

    非 torch 栈（quant/monetize）镜像不带此 LABEL，恒返回空串，调用方据此
    保持历史行为（C20）。
    """
    labels = info.get("labels") or {}
    if not isinstance(labels, dict):
        return ""
    return str(labels.get(TORCH_FLAVOR_LABEL) or "").strip()


def _save_via_cli(c: Context, image: str, outfile: Path) -> bool:
    """通过 CLI 流式导出镜像为 gzip tar（podman save | gzip/pigz）。

    与构建端 ``bin/jpman cmd_save`` 的产物格式逐项对齐（docker-archive → gzip），
    保证产物可被 ``invoke load`` / ``jpman load`` 交叉消费。pigz 存在时多线程压缩。

    兼容降级：Windows 原生 PowerShell/cmd 下 ``gzip``/``pigz`` 命令通常不存在，
    shell 管道 ``| gzip`` 会 exit 255；此时回退为 ``podman save -o`` 直接落盘
    未压缩 tar（扩展名由调用方确定为 ``.tar``，本函数直接使用 ``outfile``）。
    优先级：pigz > gzip > 未压缩。落盘路径与 ``outfile`` 完全一致。
    """
    runtime = detect_runtime()
    if shutil.which("pigz"):
        cmd = (
            f'{runtime} save "{image}" --format docker-archive'
            " | pigz -p 4 > "
            f'"{outfile}"'
        )
    elif shutil.which("gzip"):
        cmd = f'{runtime} save "{image}" --format docker-archive | gzip > "{outfile}"'
    else:
        # Windows 原生无 gzip：直接导出 tar（不压缩），outfile 应为 .tar 路径
        cmd = f'{runtime} save "{image}" --format docker-archive -o "{outfile}"'
    try:
        run_cmd(c, cmd, hide=True, pty=False, echo=False)
    except Exception as e:
        print(f"[Save] ✗ 镜像导出失败: {image}: {e}")
        return False
    if not outfile.exists() or outfile.stat().st_size == 0:
        print("[Save] ✗ 产物为空（0 字节），导出失败")
        return False
    return True


def save_image(
    c: Context,
    image: str,
    cache_dir: Path,
    *,
    not_found_hint: str = "",
    restore_hint: str = "",
) -> bool:
    """导出镜像到缓存目录（供备份 / VM 崩溃恢复），返回是否成功。

    产物与 manifest 规范对齐构建端 ``jpman save``：
      - 文件名：``<repo>-<short_id>-<YYYYMMDD-HHMMSS>.tar.gz``
      - 同步 ``*-latest.tar.gz`` 软链接（供 load 直接取最新）
      - 写 ``manifest.txt`` 段（IMAGE_FILE/SIZE/SHA256/SAVED），与
        ``validate_manifest_integrity`` 的解析格式互操作
      - ``gzip -t`` 完整性校验

    ``not_found_hint`` / ``restore_hint`` 供调用方（如各叠加栈的离线归档任务）
    覆盖默认文案，缺省空串即保持 client 叠加层原有提示（零回归）。
    """
    import datetime as _dt
    import hashlib as _hl
    import shutil as _sh
    import time as _tm

    if not image:
        print("[Save] ✗ 未指定镜像 tag")
        return False

    # 镜像存在性预检（S5：失败原因需明确是「镜像不存在」而非 daemon 问题）
    if not _image_exists_fast(c, image):
        print(f"[Save] ✗ 本地未找到镜像: {image}")
        if not_found_hint:
            print(f"[Save]   {not_found_hint}")
        else:
            print("[Save]   先构建: cd ../jupyter-podman-rootless && bash bin/jpman rebuild-all")
            print("[Save]   或加载: invoke load")
        return False

    cache_dir.mkdir(parents=True, exist_ok=True)
    # short_id 取 digest 去前缀后的前 12 位（避免 `sha256:` 冒号进入文件名/命令，
    # 否则在 Windows shell 管道中破坏命令合法性）
    info = image_inspect_info(c, image)
    short_id = (info.get("digest") or "").strip()
    if ":" in short_id:
        short_id = short_id.split(":", 1)[1]
    short_id = short_id[:12] or "unknown"
    # torch 形态取镜像 LABEL（构建期烘入，唯一事实源）。形态必须进归档名：
    # cpu 与 cu130 两份镜像 tag 相同（localhost/native-dev:latest），若归档名也不带
    # 形态，则两者同族同名、共用同一个 -latest 软链，离线机 load 按 mtime 取
    # 「最新」会静默导入错形态，直到容器内 torch.cuda 为空才暴露（C20）。
    flavor = _image_torch_flavor(info)
    ts = _dt.datetime.now().strftime("%Y%m%d-%H%M%S")
    safe_name = image.replace("/", "-").replace(":", "-")
    # 形态段必须带 `torch` 标记中缀：无标记的 `-<flavor>-` 会与镜像 tag 自带的
    # 反向解析成 flavor=latest。无形态时不加段，命名与历史产物逐字一致（零回归）。
    stem = f"{safe_name}-torch-{flavor}" if flavor else safe_name
    # 扩展名由「可用压缩工具」决定：pigz/gzip → .tar.gz；否则 → .tar（未压缩）
    use_gzip = bool(shutil.which("pigz") or shutil.which("gzip"))
    ext = ".tar.gz" if use_gzip else ".tar"
    outfile = cache_dir / f"{stem}-{short_id}-{ts}{ext}"
    latest_link = cache_dir / f"{stem}-latest{ext}"

    if not _save_via_cli(c, image, outfile):
        return False
    saved = outfile

    # 完整性校验（压缩产物 gzip -t；未压缩仅核大小）
    file_size = saved.stat().st_size
    if ext == ".tar.gz" and not _check_gzip_integrity(saved):
        print("[Save] ✗ gzip -t 校验失败，产物不可信")
        return False

    # SHA256 摘要（供 manifest / load 前完整性比对）
    sha = _hl.sha256()
    with open(saved, "rb") as f:
        for chunk in iter(lambda: f.read(1024 * 1024), b""):
            sha.update(chunk)
    digest = sha.hexdigest()

    # latest 软链接（Windows 上 os.symlink 可能需要权限：失败静默，不影响主流程）
    try:
        if latest_link.exists() or latest_link.is_symlink():
            latest_link.unlink()
        latest_link.symlink_to(saved.name)
    except OSError:
        pass

    _append_manifest(cache_dir, image, saved.name, file_size, digest, flavor)
    print(f"[Save] ✅ 已保存: {saved.name} ({file_size / 1024 / 1024:.1f} MB)")
    print(f"[Save]   SHA256: {digest}")
    if flavor:
        print(f"[Save]   torch 形态: {flavor}（来源：镜像 LABEL {TORCH_FLAVOR_LABEL}）")
    hint = restore_hint or f"invoke load --path {saved}   或   bash bin/jpman load"
    print(f"[Save]   恢复:  {hint}")
    return True


def _image_exists_fast(c: Context, image: str) -> bool:
    """轻量镜像存在性检查（避免走 list_images 全量解析）。"""
    runtime = detect_runtime()
    r = run_cmd(
        c,
        f'{runtime} image exists {image}',
        hide=True,
        warn=True,
        echo=False,
    )
    return r is not None and getattr(r, "ok", False)


def _check_gzip_integrity(path: Path) -> bool:
    """gzip -t 校验（Windows 无 gzip 时回退简单非零检查）。"""
    if shutil.which("gzip"):
        try:
            subprocess.run(
                ["gzip", "-t", str(path)],
                capture_output=True,
                text=True,
                timeout=60,
            )
            return Path(path).exists()
        except (OSError, subprocess.TimeoutExpired):
            pass
    return Path(path).exists() and path.stat().st_size > 0


def _append_manifest(
    cache_dir: Path,
    image: str,
    filename: str,
    size_bytes: int,
    sha256_hex: str,
    flavor: str = "",
) -> None:
    """向 manifest.txt 追加一段（对齐构建端 jpman save 的 manifest 格式）。

    保证 ``validate_manifest_integrity``（按 IMAGE_FILE 精确匹配段）能读到本段。
    ``TORCH_FLAVOR`` 为冗余记账字段（归档名才是解析的单一事实源），供人工核对
    归档与镜像形态是否一致；无 torch 的镜像写空值。
    """
    from datetime import datetime as _dt

    manifest = cache_dir / "manifest.txt"
    header = "# Jupyter Podman Image Cache"
    lines = [
        header,
        f"IMAGE_NAME={image}",
        f"IMAGE_FILE={filename}",
        f"TORCH_FLAVOR={flavor}",
        f"SIZE={size_bytes / 1024 / 1024:.0f}MB",
        f"SHA256={sha256_hex.upper()}",
        f"SAVED={_dt.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ')}",
        "",
    ]
    body = "\n".join(lines)
    if manifest.exists():
        file_body = manifest.read_text(encoding="utf-8")
        # 若表头已存在则只追加段；否则整体替换（表头保留最新一段语义）
        if header in file_body:
            manifest.write_text(file_body.rstrip("\n") + "\n" + body, encoding="utf-8")
            return
    manifest.write_text(body, encoding="utf-8")


# ===========================================================================
# 容器生命周期：run / stop / status / clean
# ===========================================================================


def _ensure_secrets(cfg: ContainerConfig) -> None:
    """自动填充缺失的密码/token（与构建端生成规则一致）。"""
    if not cfg.user_password:
        cfg.user_password = generate_random_string(16)
        print(f"[Config] 自动生成密码: {cfg.user_password}")
    if not cfg.jupyter_token:
        cfg.jupyter_token = generate_random_string(32)
        print(f"[Config] 自动生成 token: {cfg.jupyter_token}")


def _sdk_run_kwargs(cfg: ContainerConfig, workspace_posix: str) -> dict:
    """构造 podman-py containers.run 的 kwargs。

    透传部分由 ``utils.build_passthrough_spec`` 统一解析，与 CLI fallback 共用同一份
    结果，确保两条路径的运行参数完全一致（见 invoke-tasks 规则 §3.2）。
    """
    spec = build_passthrough_spec(cfg)
    ports = {
        "22/tcp": cfg.ssh_port,
        "8888/tcp": cfg.jupyter_port,
    }
    volumes = {
        workspace_posix: {"bind": "/workspace", "mode": "rw"},
        # B-scheme: 直连宿主 rootless daemon（绕过嵌套 userns）。
        # 宿主 socket bind-mount 到容器同一路径，容器内 entrypoint 的 B-scheme
        # 分支据此建立符号链接并设置 CONTAINER_HOST，SDK from_env() 即可连通。
        podman_sock_path(): {"bind": podman_sock_path(), "mode": "rw"},
    }
    # Wayland / D-Bus 透传挂载
    for src, dst, mode in spec.volumes:
        volumes[src] = {"bind": dst, "mode": mode}

    environment: dict[str, str] = {
        "USER_PASSWORD": cfg.user_password,
        "JUPYTER_TOKEN": cfg.jupyter_token,
        # B-scheme: 告知容器内 entrypoint 宿主 daemon socket 已 bind-mount 到
        # 容器内的哪个路径（与构建端语义一致）。
        "HOST_PODMAN_SOCK": podman_sock_path(),
    }
    if cfg.ssh_public_key:
        environment["SSH_PUBLIC_KEY"] = cfg.ssh_public_key
    if cfg.grant_sudo:
        environment["GRANT_SUDO"] = "yes"
    # 透传注入的环境变量（XDG_RUNTIME_DIR / WAYLAND_DISPLAY / DBUS_SESSION_BUS_ADDRESS
    # / SSHD_PORT）
    environment.update(spec.environment)

    kwargs = {
        "image": cfg.image,
        "name": cfg.name,
        "volumes": volumes,
        "environment": environment,
        "detach": cfg.detach,
        # C3：rootless 三必需的 /dev/fuse 硬编码保留，开启 GPU/USB 时在其后追加
        "devices": list(cfg.devices) + spec.devices,
        "security_opt": cfg.security_opt,
        "cgroupns": cfg.cgroupns,
        "user": cfg.user,
    }
    # Host 网络与端口发布互斥：host 网络下不传 ports
    if spec.publish_ports:
        kwargs["ports"] = ports
    if spec.network_mode:
        kwargs["network_mode"] = spec.network_mode
    return kwargs


def _run_via_sdk(client, cfg: ContainerConfig, workspace_posix: str) -> bool:
    """SDK 启动容器。"""
    try:
        try:
            old = client.containers.get(cfg.name)
            print(f"[SDK] 清理旧容器: {cfg.name}")
            old.remove(force=True)
        except PodmanNotFound:
            pass

        kwargs = _sdk_run_kwargs(cfg, workspace_posix)
        print(f"[SDK] 启动容器: {cfg.name} ({cfg.image})")
        container = client.containers.run(**kwargs)
        if cfg.detach:
            container.reload()
            print(f"[SDK] 容器已启动 (detached): {container.short_id}")
        else:
            print("[SDK] 容器前台运行")
        return True
    except Exception as e:
        # B-scheme 核心 socket 缺失（C-I5）优先于 opt-in 透传诊断（C-I3）；
        # Windows 原生 TTY 控制台下 CLI 路径走 subprocess.call 不捕获 stderr，
        # 故 SDK 层是 C-I5/C-I3 指引的主要提示来源。
        if "podman.sock" in str(e):
            print(bsock_missing_guidance())
        else:
            hint = passthrough_diagnose_hint(str(e))
            if hint:
                print(hint)
        print(f"[SDK] 启动失败 fallback to CLI: {e}")
        return False


def _run_via_cli(c: Context, cfg: ContainerConfig, workspace_posix: str) -> None:
    """CLI 启动容器（与 jpman create 参数一致）。

    透传参数与 SDK 路径同为 ``utils.build_passthrough_spec`` 的产物，逐项等价：
      ``--network host``（且不带 ``-p``）/ ``-v``（Wayland、D-Bus）/ ``--device``（GPU、USB）
      / ``-e``（XDG_RUNTIME_DIR、WAYLAND_DISPLAY、DBUS_SESSION_BUS_ADDRESS、SSHD_PORT）。
    """
    runtime = detect_runtime()
    spec = build_passthrough_spec(cfg)

    if cli_container_exists(c, runtime, cfg.name):
        print(f"[CLI] 容器 {cfg.name} 已存在，先清理...")
        _stop_via_cli(c, cfg.name)

    cmd_parts = [
        runtime,
        "run",
        "--name",
        cfg.name,
    ]
    # ① Host 网络模式：与端口发布互斥，改传 --network host
    if spec.publish_ports:
        cmd_parts.extend(["-p", f"{cfg.ssh_port}:22", "-p", f"{cfg.jupyter_port}:8888"])
    else:
        cmd_parts.extend(["--network", spec.network_mode or "host"])
    cmd_parts.extend(
        [
            "-v",
            f"{workspace_posix}:/workspace",
            # B-scheme: 直连宿主 rootless daemon（绕过嵌套 userns）。
            # 宿主 socket bind-mount 到容器同一路径，容器内 entrypoint 的 B-scheme
            # 分支据此建立符号链接并设置 CONTAINER_HOST，容器内 podman SDK/CLI 可连通。
            "-v",
            f"{podman_sock_path()}:{podman_sock_path()}",
        ]
    )
    # ② Wayland / ④ D-Bus 透传挂载
    for src, dst, mode in spec.volumes:
        cmd_parts.extend(["-v", f"{src}:{dst}:{mode}"])
    cmd_parts.extend(
        [
            # C3：rootless 三必需硬编码，先于可选的 GPU/USB 设备
            "--device /dev/fuse",
            "--security-opt label=disable",
            "--cgroupns=host",
            "--user",
            cfg.user,
        ]
    )
    # ③ GPU / ⑤ USB 透传设备
    for dev in spec.devices:
        cmd_parts.extend(["--device", dev])
    if cfg.detach:
        cmd_parts.append("-d")
    cmd_parts.extend(["-e", f"USER_PASSWORD={cfg.user_password}"])
    cmd_parts.extend(["-e", f"JUPYTER_TOKEN={cfg.jupyter_token}"])
    cmd_parts.extend(["-e", f"HOST_PODMAN_SOCK={podman_sock_path()}"])
    if cfg.ssh_public_key:
        cmd_parts.extend(["-e", f'SSH_PUBLIC_KEY="{cfg.ssh_public_key}"'])
    if cfg.grant_sudo:
        cmd_parts.extend(["-e", "GRANT_SUDO=yes"])
    for key, val in spec.environment.items():
        cmd_parts.extend(["-e", f"{key}={val}"])
    cmd_parts.append(cfg.image)
    run_cmd(c, " ".join(cmd_parts), pty=not cfg.detach)
    if cfg.detach:
        print("[CLI] 容器已启动 (detached)")


def _exception_text(exc: BaseException) -> str:
    """拼接异常消息与 invoke 结果对象的 stderr/stdout。

    透传诊断（C-I3）需要 podman 的原始报错（``Error: statfs ...``），而该内容在
    ``UnexpectedExit.result.stderr`` 里，不在异常消息本身。
    """
    parts = [str(exc)]
    result = getattr(exc, "result", None)
    for attr in ("stderr", "stdout"):
        val = getattr(result, attr, "") or ""
        if val:
            parts.append(val)
    return "\n".join(parts)


def _print_passthrough_summary(cfg: ContainerConfig) -> None:
    """打印已启用的运行时透传项（全部关闭时零输出，保持默认隔离的输出不变）。"""
    enabled = [
        label
        for label, on in (
            ("host-network", cfg.host_network),
            ("wayland", cfg.wayland),
            ("gpu", cfg.gpu),
            ("usb", cfg.usb),
            ("dbus", cfg.dbus),
            ("video", cfg.video),
        )
        if on
    ]
    if enabled:
        print(f"[Run] 透传: {', '.join(enabled)}")


def run_container(c: Context, cfg: ContainerConfig) -> ContainerConfig:
    """启动容器，SDK 优先失败走 CLI。返回最终使用的配置（含自动填充的密码/token）。"""
    ready, hint = check_runtime_ready()
    if not ready:
        # 用 Exit 而非 RuntimeError：invoke 下前者打印简洁中文提示，后者会抛出完整 traceback
        raise Exit(1, f"运行时未就绪: {hint}")

    # B-scheme 预检（仅原生 Linux 本机生效）：socket 挂载源不存在则 podman run 必然
    # statfs 硬失败 exit=125；先尝试自动拉起宿主 rootless socket 服务（systemctl
    # 单元 → podman system service 兜底两级自愈），失败即 fail-fast
    # 给出 C-I5 指引，避免注定失败的 run 与 C-I3 误报（2026-09-12，UID 1006 事故）。
    sock_ready, sock_detail, sock_started = ensure_host_podman_socket()
    if not sock_ready:
        raise Exit(1, bsock_missing_guidance(sock_detail))
    if sock_started:
        print(f"[Run][B-scheme] 已自动启动宿主 rootless podman socket 服务: {podman_sock_path()}")

    _ensure_secrets(cfg)
    workspace_path = cfg.resolved_workspace()
    if not workspace_path.exists():
        print(f"[Workspace] 创建工作目录: {workspace_path}")
        workspace_path.mkdir(parents=True, exist_ok=True)
    workspace_posix = to_posix_path(workspace_path)

    print(f"[Run] 容器: {cfg.name}  镜像: {cfg.image}")
    print(f"[Run] 挂载 {workspace_posix} -> /workspace")
    if cfg.host_network:
        # host 网络下容器直接占用宿主端口：SSH 走 SSHD_PORT（= --ssh-port，非特权端口），
        # Jupyter 固定为容器内 8888（不由 --jupyter-port 控制）。
        print(
            f"[Run] 网络: host（不发布端口；SSH=localhost:{cfg.ssh_port}，"
            "Jupyter=localhost:8888）"
        )
    else:
        print(f"[Run] 端口映射: SSH={cfg.ssh_port}  Jupyter={cfg.jupyter_port}")
    _print_passthrough_summary(cfg)

    sdk_ok = False
    with get_client() as client:
        if client is not None:
            sdk_ok = _run_via_sdk(client, cfg, workspace_posix)
    if not sdk_ok:
        try:
            _run_via_cli(c, cfg, workspace_posix)
        except Exception as exc:  # noqa: BLE001 - 需把 podman 原生报错翻译成 C-I5/C-I3 指引
            exc_text = _exception_text(exc)
            # B-scheme 核心 socket（C-I5）优先于 opt-in 透传（C-I3）
            if "podman.sock" in exc_text:
                print(bsock_missing_guidance())
            else:
                pt_hint = passthrough_diagnose_hint(exc_text)
                if pt_hint:
                    print(pt_hint)
            raise

    if cfg.host_network and cfg.jupyter_port != 8888:
        print(
            f"[Run] ⚠ host 网络模式下 Jupyter 固定监听容器内 8888，"
            f"--jupyter-port={cfg.jupyter_port} 不生效"
        )
    jupyter_port = 8888 if cfg.host_network else cfg.jupyter_port

    print("\n" + "=" * 60)
    print("访问信息:")
    print(f"  SSH:         ssh -p {cfg.ssh_port} devuser@localhost")
    print(f"  SSH 密码:    {cfg.user_password}")
    print(f"  Jupyter Lab: http://localhost:{jupyter_port}/lab?token={cfg.jupyter_token}")
    print(f"  工作区:      {workspace_path}")
    print("=" * 60)
    return cfg


def _stop_via_sdk(client, name: str) -> bool:
    try:
        container = client.containers.get(name)
        if container.status == "running":
            print(f"[SDK] 停止容器: {name}")
            container.stop(timeout=10)
        print(f"[SDK] 删除容器: {name}")
        container.remove(force=True)
        return True
    except PodmanNotFound:
        print(f"[SDK] 容器 {name} 不存在")
        return True
    except Exception as e:
        print(f"[SDK] 停止失败 fallback: {e}")
        return False


def _stop_via_cli(c: Context, name: str) -> None:
    runtime = detect_runtime()
    if not cli_container_exists(c, runtime, name):
        print(f"[CLI] 容器 {name} 不存在")
        return
    print(f"[CLI] 停止容器: {name}")
    run_cmd(c, f"{runtime} stop {name}", warn=True, hide=True, echo=False)
    run_cmd(c, f"{runtime} rm {name}", warn=True, hide=True, echo=False)
    print("[CLI] 容器已停止并删除")


def stop_container(c: Context, name: str) -> None:
    """停止并删除容器（SDK 优先）。"""
    print(f"[Stop] 目标容器: {name}")
    sdk_ok = False
    with get_client() as client:
        if client is not None:
            sdk_ok = _stop_via_sdk(client, name)
    if not sdk_ok:
        _stop_via_cli(c, name)


def _status_via_sdk(client, name: str) -> bool:
    try:
        target = None
        for ct in client.containers.list(all=True):
            if ct.name == name:
                target = ct
                break
        print(f"容器状态: {name}")
        print("-" * 60)
        if target is None:
            print(f"容器 {name} 不存在")
            return True
        target.reload()
        ports_str = ", ".join(
            f"{p.get('HostPort', '?')}->{container_port}"
            for container_port, port_bindings in target.ports.items()
            if port_bindings
            for p in port_bindings or []
        )
        status = target.status
        print(f"  Name:      {target.name}")
        print(f"  Status:    {status}")
        print(f"  Image:     {target.image.tags[0] if target.image.tags else target.short_id}")
        print(f"  Ports:     {ports_str or 'none'}")
        started = target.attrs.get("State", {}).get("StartedAt")
        exited = target.attrs.get("State", {}).get("ExitCode")
        if status == "running" and started:
            print(f"  Started:   {started}")
        if status == "exited" and exited is not None:
            print(f"  ExitCode:  {exited}")
        return True
    except Exception as e:
        print(f"[SDK] status 失败 fallback: {e}")
        return False


def _status_via_cli(c: Context, name: str) -> None:
    runtime = detect_runtime()
    print(f"容器状态: {name}")
    print("-" * 60)
    if not cli_container_exists(c, runtime, name):
        print(f"容器 {name} 不存在")
        return
    go_fmt = "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
    result = run_cmd(
        c,
        runtime + ' ps -a --filter name=^' + name + '$ --format "' + go_fmt + '"',
        pty=False,
        echo=False,
    )
    if result:
        print(result.stdout)


def status_container(c: Context, name: str) -> None:
    """查询容器状态（SDK 优先）。"""
    sdk_ok = False
    with get_client() as client:
        if client is not None:
            sdk_ok = _status_via_sdk(client, name)
    if not sdk_ok:
        _status_via_cli(c, name)


def clean_container(c: Context, name: str, tag: str, volume: bool = False, image: bool = False) -> None:
    """清理容器/卷/镜像（SDK 优先）。"""
    print(f"[Clean] 容器={name}  卷={volume}  镜像={image}")
    sdk_ok = False
    with get_client() as client:
        if client is not None:
            try:
                _stop_via_sdk(client, name)
                if volume:
                    print("[SDK] 清理未使用卷...")
                    try:
                        client.volumes.prune()
                    except Exception:
                        pass
                if image:
                    print(f"[SDK] 删除镜像: {tag}")
                    try:
                        img = client.images.get(tag)
                        img.remove(force=True)
                    except Exception:
                        pass
                sdk_ok = True
            except Exception as e:
                print(f"[SDK] clean 失败 fallback: {e}")
    if not sdk_ok:
        runtime = detect_runtime()
        _stop_via_cli(c, name)
        if volume:
            print("[CLI] 清理未使用卷...")
            run_cmd(c, f"{runtime} volume prune -f", warn=True)
        if image:
            print(f"[CLI] 删除镜像: {tag}")
            run_cmd(c, f"{runtime} rmi {tag}", warn=True)
    print("[Clean] 完成")
