"""Plan or run the fixed M5 prompt ingress through private GCP IAP."""

from __future__ import annotations

import argparse
import hashlib
import json
import os
import re
import shlex
import shutil
import stat
import subprocess
import sys
import uuid
from collections.abc import Callable, Mapping
from pathlib import Path
from typing import Any

CONTRACT_ROOT = Path(__file__).resolve().parents[1]
if str(CONTRACT_ROOT) not in sys.path:
    sys.path.insert(0, str(CONTRACT_ROOT))

from ops import gcp_leoclean_nosend_package as package  # noqa: E402
from ops import gcp_leoclean_nosend_prompt_ingress as ingress  # noqa: E402
from ops import run_gcp_leoclean_nosend_iap as iap  # noqa: E402

PLAN_SCHEMA = "livingip.leocleanNoSendPromptIngressPlan.v1"
RESULT_SCHEMA = "livingip.leocleanNoSendPromptIngressResult.v1"
REMOTE_RESULT_SCHEMA = "livingip.leocleanNoSendPromptIngressRemoteResult.v1"
REMOTE_FAILURE_SCHEMA = "livingip.leocleanNoSendPromptIngressRemoteFailure.v1"
PROJECT = package.PROJECT
ZONE = package.ZONE
INSTANCE = package.INSTANCE
SERVICE = package.SERVICE
CONTAINER_NAME = package.CONTAINER_NAME
IMAGE_REPOSITORY = package.IMAGE_REPOSITORY
GCLOUD = iap.GCLOUD
KEY_LIFETIME = "5m"
MAX_OUTPUT_BYTES = 2 * 1024 * 1024
HEX_40 = re.compile(r"^[0-9a-f]{40}$")
HEX_64 = re.compile(r"^[0-9a-f]{64}$")
DIGEST = re.compile(r"^sha256:[0-9a-f]{64}$")
REQUEST_ID = re.compile(r"^m5-[a-z0-9]{12,24}$")
SECRET_NAME = re.compile(r"^[a-z][a-z0-9_-]{2,254}$")
TELEGRAM_TOKEN = re.compile(r"\b\d{6,}:[A-Za-z0-9_-]{20,}\b")
SECRET_OUTPUT_MARKERS = (
    "authorization:",
    "access_token",
    "refresh_token",
    "password",
    "private_key",
    "77.42.65.182",
    "teleo-prod-1",
)
NO_SEND_AUTHORITY = {
    "canonical_proposal_applied": False,
    "canonical_proposal_approved": False,
    "posted_to_telegram": False,
    "production_traffic_changed": False,
    "public_endpoint_created": False,
    "sending_enabled": False,
    "vps_touched": False,
}
CLAIM_CEILING = (
    "This external hash-bound harness proves a private, transient, no-send ingress contract "
    "for one exact installed immutable image. A dry-run plan does not prove live image "
    "compatibility, model behavior, benchmark parity, Telegram delivery, or production readiness."
)
PROMPT_IDS = tuple(item["id"] for item in ingress.PROMPTS)
PAYLOAD = Path(ingress.__file__).resolve()
REMOTE_ROOT = "/run/livingip-m5-prompt-ingress"

REMOTE_EXECUTOR_SOURCE = r"""
import hashlib, json, os, re, stat, subprocess, sys

uploaded, payload_hash, image_ref, config_digest, release_hash, runtime_revision, request_id, catalog_hash = sys.argv[1:]
prompt_ids = ("DC-01", "DC-02", "DC-03", "DC-04", "DC-05", "DC-06")
docker = ["/usr/bin/docker", "--host=unix:///var/run/docker.sock", "--config=/var/lib/livingip/leoclean-nosend/docker-config"]
managed_name = "livingip-leoclean-nosend"
stage_root = "/run/livingip-m5-prompt-ingress"
stage = f"{stage_root}/{request_id}"
payload = f"{stage}/payload.py"
transient_names = []

def sha(value):
    return hashlib.sha256(value).hexdigest()

def canonical(value):
    return (json.dumps(value, allow_nan=False, separators=(",", ":"), sort_keys=True) + "\n").encode()

def require(condition, reason):
    if not condition:
        raise RuntimeError(reason)

def command(argv, *, input_bytes=None, timeout=120, accepted=(0,)):
    completed = subprocess.run(
        argv,
        input=input_bytes,
        stdin=subprocess.DEVNULL if input_bytes is None else None,
        capture_output=True,
        check=False,
        timeout=timeout,
    )
    require(len(completed.stdout) <= 2 * 1024 * 1024 and len(completed.stderr) <= 256 * 1024, "command_output_limit")
    require(completed.returncode in accepted, "command_failed")
    return completed

def strict_json(raw, reason):
    try:
        value = json.loads(raw.decode("utf-8", "strict"))
    except Exception:
        raise RuntimeError(reason)
    require(isinstance(value, dict), reason)
    return value

def managed_posture():
    raw = command([*docker, "inspect", managed_name]).stdout
    try:
        value = json.loads(raw.decode("utf-8", "strict"))
    except Exception:
        raise RuntimeError("managed_inspect_invalid")
    require(isinstance(value, list) and len(value) == 1 and isinstance(value[0], dict), "managed_inspect_invalid")
    item = value[0]
    config = item.get("Config") or {}
    state = item.get("State") or {}
    host = item.get("HostConfig") or {}
    network = item.get("NetworkSettings") or {}
    labels = config.get("Labels") or {}
    env_names = sorted(str(row).partition("=")[0] for row in (config.get("Env") or []))
    health = state.get("Health") or {}
    ports = network.get("Ports") or {}
    tmpfs = host.get("Tmpfs") or {}
    require(config.get("Image") == image_ref, "managed_image_reference_mismatch")
    require(item.get("Image") == config_digest, "managed_image_config_mismatch")
    require(labels.get("livingip.release.sha256") == release_hash, "managed_release_mismatch")
    require(labels.get("livingip.container.role") == "leoclean-gcp-nosend", "managed_role_mismatch")
    require(
        config.get("Entrypoint") == [
            "/opt/livingip/leoclean-nosend/venv/bin/python",
            "/opt/livingip/leoclean-nosend/entrypoint.py",
        ]
        and config.get("Cmd") == ["service"],
        "managed_command_mismatch",
    )
    require(state.get("Running") is True and health.get("Status") == "healthy", "managed_service_not_healthy")
    require(item.get("RestartCount") == 0, "managed_service_restarted")
    require(
        host.get("AutoRemove") is True
        and host.get("ReadonlyRootfs") is True
        and host.get("CapDrop") == ["ALL"]
        and sorted(cap.removeprefix("CAP_") for cap in (host.get("CapAdd") or []))
        == ["CHOWN", "SETGID", "SETPCAP", "SETUID"]
        and host.get("PidsLimit") == 512
        and host.get("SecurityOpt") == ["no-new-privileges:true"]
        and set((network.get("Networks") or {})) == {"bridge"}
        and set(tmpfs) == {"/run/leoclean-profile", "/tmp", "/var/lib/postgresql/data"},
        "managed_isolation_mismatch",
    )
    require(
        not (host.get("PortBindings") or {})
        and all(value in (None, []) for value in ports.values()),
        "managed_service_has_ports",
    )
    require(
        not any(
            name == "OPENROUTER_API_KEY"
            or name.startswith(("TELEGRAM_", "DISCORD_", "SLACK_", "WEBHOOK_"))
            for name in env_names
        ),
        "managed_service_has_transport_or_provider_credential",
    )
    return {
        "container_id": str(item.get("Id") or ""),
        "image_reference": config.get("Image"),
        "image_config_digest": item.get("Image"),
        "release_sha256": labels.get("livingip.release.sha256"),
        "role": labels.get("livingip.container.role"),
        "running": state.get("Running"),
        "health": health.get("Status"),
        "restart_count": item.get("RestartCount"),
        "started_at": state.get("StartedAt"),
        "entrypoint": config.get("Entrypoint"),
        "command": config.get("Cmd"),
        "auto_remove": host.get("AutoRemove"),
        "read_only_rootfs": host.get("ReadonlyRootfs"),
        "cap_add": sorted(host.get("CapAdd") or []),
        "cap_drop": host.get("CapDrop"),
        "pids_limit": host.get("PidsLimit"),
        "security_opt": host.get("SecurityOpt"),
        "network_names": sorted((network.get("Networks") or {})),
        "tmpfs_paths": sorted(tmpfs),
        "published_port_count": sum(bool(value) for value in ports.values()),
        "provider_or_transport_env_present": False,
    }

def stage_payload():
    caller_uid = int(os.environ.get("SUDO_UID", "-1"))
    observed = os.stat(uploaded, follow_symlinks=False)
    require(
        caller_uid > 0
        and stat.S_ISREG(observed.st_mode)
        and observed.st_uid == caller_uid
        and observed.st_nlink == 1
        and not stat.S_IMODE(observed.st_mode) & 0o022
        and observed.st_size <= 1024 * 1024,
        "uploaded_payload_unsafe",
    )
    with open(uploaded, "rb") as handle:
        raw = handle.read(1024 * 1024 + 1)
    require(len(raw) == observed.st_size and sha(raw) == payload_hash, "uploaded_payload_mismatch")
    os.makedirs(stage_root, mode=0o700, exist_ok=True)
    root_state = os.stat(stage_root, follow_symlinks=False)
    require(root_state.st_uid == 0 and stat.S_IMODE(root_state.st_mode) == 0o700, "stage_root_unsafe")
    os.mkdir(stage, 0o700)
    descriptor = os.open(payload, os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0), 0o444)
    with os.fdopen(descriptor, "wb") as handle:
        handle.write(raw)
        handle.flush()
        os.fsync(handle.fileno())
    os.unlink(uploaded)

def container_argv(prompt_id, container_name):
    profile_tmpfs = "/run/leoclean-profile:rw,noexec,nosuid,nodev,size=64m,uid=0,gid=0,mode=0700"
    temp_tmpfs = "/tmp:rw,noexec,nosuid,nodev,size=64m,uid=65532,gid=65532,mode=0700"
    postgres_tmpfs = "/var/lib/postgresql/data:ro,noexec,nosuid,nodev,size=64k,uid=0,gid=0,mode=0000"
    return [
        *docker,
        "run",
        "--rm",
        "--interactive",
        f"--name={container_name}",
        "--pull=never",
        "--read-only",
        "--cap-drop=ALL",
        "--cap-add=CHOWN",
        "--cap-add=SETGID",
        "--cap-add=SETUID",
        "--cap-add=SETPCAP",
        "--security-opt=no-new-privileges:true",
        "--pids-limit=512",
        "--network=bridge",
        "--stop-timeout=30",
        f"--tmpfs={profile_tmpfs}",
        f"--tmpfs={temp_tmpfs}",
        f"--tmpfs={postgres_tmpfs}",
        f"--label=livingip.m5.request={request_id}",
        "--label=livingip.container.role=leoclean-m5-prompt-ingress",
        f"--mount=type=bind,src={payload},dst=/run/livingip-m5-prompt-ingress.py,readonly",
        "--entrypoint=/opt/livingip/leoclean-nosend/venv/bin/python",
        image_ref,
        "/run/livingip-m5-prompt-ingress.py",
        "--prompt-id",
        prompt_id,
    ]

def request_containers():
    listed = command(
        [*docker, "ps", "-aq", "--filter", f"label=livingip.m5.request={request_id}",
         "--filter", "label=livingip.container.role=leoclean-m5-prompt-ingress"],
        timeout=30,
    )
    return [row for row in listed.stdout.decode("ascii", "strict").splitlines() if row]

def cleanup():
    for name in tuple(transient_names):
        subprocess.run(
            [*docker, "rm", "-f", name],
            stdin=subprocess.DEVNULL,
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL,
            check=False,
            timeout=45,
        )
    remaining = request_containers()
    try:
        if os.path.isfile(payload) and not os.path.islink(payload):
            os.unlink(payload)
        if os.path.isdir(stage) and not os.path.islink(stage):
            os.rmdir(stage)
    except OSError:
        pass
    try:
        if os.path.isfile(uploaded) and not os.path.islink(uploaded):
            os.unlink(uploaded)
    except OSError:
        pass
    return remaining

secret = b""
before = None
after = None
turns = []
turn_failure = None
failure_stage = "remote_setup"
failure_reason = "unknown"
try:
    require(re.fullmatch(r"sha256:[0-9a-f]{64}", config_digest) is not None, "config_digest_invalid")
    require(re.fullmatch(r"[0-9a-f]{64}", release_hash) is not None, "release_hash_invalid")
    require(re.fullmatch(r"[0-9a-f]{40}", runtime_revision) is not None, "runtime_revision_invalid")
    require(re.fullmatch(r"m5-[a-z0-9]{12,24}", request_id) is not None, "request_id_invalid")
    stage_payload()
    secret = sys.stdin.buffer.read(4098)
    if secret.endswith(b"\n"):
        secret = secret[:-1]
    require(16 <= len(secret) <= 4096 and b"\n" not in secret and b"\r" not in secret and b"\0" not in secret, "provider_credential_invalid")
    failure_stage = "managed_service_before"
    before = managed_posture()
    for prompt_id in prompt_ids:
        failure_stage = f"prompt_{prompt_id.lower()}"
        suffix = prompt_id.lower().replace("-", "")
        name = f"livingip-{request_id}-{suffix}"
        transient_names.append(name)
        completed = command(container_argv(prompt_id, name), input_bytes=secret + b"\n", timeout=420, accepted=(0, 65))
        if completed.returncode == 65:
            turn_failure = strict_json(completed.stderr, "prompt_failure_receipt_invalid")
            turn_stable = {key: item for key, item in turn_failure.items() if key != "receipt_sha256"}
            require(
                turn_failure.get("schema") == "livingip.leocleanNoSendPromptIngressFailure.v1"
                and turn_failure.get("status") == "fail"
                and turn_failure.get("prompt_id") == prompt_id
                and turn_failure.get("receipt_sha256") == sha(canonical(turn_stable)),
                "prompt_failure_receipt_invalid",
            )
            raise RuntimeError(
                f"{turn_failure.get('failure_stage')}/{turn_failure.get('failure_reason')}"
            )
        require(completed.returncode == 0, "prompt_container_failed")
        value = strict_json(completed.stdout, "prompt_receipt_invalid")
        require(
            value.get("schema") == "livingip.leocleanNoSendPromptIngressTurn.v1"
            and value.get("status") == "pass"
            and value.get("prompt_id") == prompt_id
            and value.get("ingress_sha256") == payload_hash
            and value.get("prompt_catalog_sha256") == catalog_hash,
            "prompt_receipt_contract_mismatch",
        )
        require((value.get("runtime") or {}).get("teleo_git_head") == runtime_revision, "prompt_runtime_revision_mismatch")
        require((value.get("authority") or {}) == {
            "canonical_proposal_applied": False,
            "canonical_proposal_approved": False,
            "posted_to_telegram": False,
            "production_traffic_changed": False,
            "public_endpoint_created": False,
            "sending_enabled": False,
            "vps_touched": False,
        }, "prompt_authority_mismatch")
        require(
            value.get("database_observation_consistent") is True
            and value.get("database_write_path_exposed") is False,
            "prompt_database_boundary_invalid",
        )
        absent = command([*docker, "ps", "-aq", "--filter", f"name=^/{name}$"]).stdout.strip()
        require(not absent, "prompt_container_remained")
        transient_names.remove(name)
        turns.append(value)
    failure_stage = "managed_service_after"
    after = managed_posture()
    require(before == after, "managed_service_changed")
    remaining = cleanup()
    require(not remaining, "prompt_container_cleanup_failed")
    stable = {
        "schema": "livingip.leocleanNoSendPromptIngressRemoteResult.v1",
        "status": "pass",
        "request_id": request_id,
        "target": {"project": "teleo-501523", "zone": "europe-west6-a", "instance": "teleo-staging-1"},
        "bindings": {
            "image_reference": image_ref,
            "image_config_digest": config_digest,
            "release_sha256": release_hash,
            "runtime_revision": runtime_revision,
            "ingress_sha256": payload_hash,
            "prompt_catalog_sha256": catalog_hash,
        },
        "service_before": before,
        "service_after": after,
        "service_unchanged": True,
        "turns": turns,
        "cleanup": {
            "transient_containers_remaining": [],
            "staged_payload_removed": True,
        },
        "authority": {
            "canonical_proposal_applied": False,
            "canonical_proposal_approved": False,
            "posted_to_telegram": False,
            "production_traffic_changed": False,
            "public_endpoint_created": False,
            "sending_enabled": False,
            "vps_touched": False,
        },
        "claim_ceiling": (
            "Live execution proves the exact immutable image answered the fixed prompts through "
            "the external hash-bound private ingress. Scoring and behavioral parity are separate."
        ),
    }
    result = {**stable, "receipt_sha256": sha(canonical(stable))}
    encoded = json.dumps(result, allow_nan=False, separators=(",", ":"), sort_keys=True).encode()
    require(secret not in encoded, "provider_credential_reached_receipt")
    sys.stdout.buffer.write(encoded + b"\n")
except Exception as exc:
    failure_reason = str(exc)
    try:
        remaining = cleanup()
    except Exception:
        remaining = ["cleanup_failed"]
    try:
        after = managed_posture()
    except Exception:
        after = None
    stable = {
        "schema": "livingip.leocleanNoSendPromptIngressRemoteFailure.v1",
        "status": "fail",
        "request_id": request_id,
        "failure_stage": failure_stage,
        "failure_reason": failure_reason[:160] if failure_reason else "unknown",
        "service_before": before,
        "service_after": after,
        "completed_prompt_ids": [row.get("prompt_id") for row in turns],
        "turn_failure": turn_failure,
        "cleanup": {
            "transient_containers_remaining": remaining,
            "staged_payload_removed": not os.path.exists(payload),
        },
        "authority": {
            "canonical_proposal_applied": False,
            "canonical_proposal_approved": False,
            "posted_to_telegram": False,
            "production_traffic_changed": False,
            "public_endpoint_created": False,
            "sending_enabled": False,
            "vps_touched": False,
        },
    }
    result = {**stable, "receipt_sha256": sha(canonical(stable))}
    encoded = json.dumps(result, allow_nan=False, separators=(",", ":"), sort_keys=True).encode()
    if secret and secret in encoded:
        stable["failure_reason"] = "secret_redaction"
        result = {**stable, "receipt_sha256": sha(canonical(stable))}
        encoded = json.dumps(result, allow_nan=False, separators=(",", ":"), sort_keys=True).encode()
    sys.stdout.buffer.write(encoded + b"\n")
    raise SystemExit(65)
finally:
    secret = b""
    cleanup()
"""

CLEANUP_SOURCE = r"""
import json, os, re, shutil, subprocess, sys
uploaded, stage, request_id = sys.argv[1:]
if re.fullmatch(r"m5-[a-z0-9]{12,24}", request_id) is None:
    raise SystemExit("invalid cleanup request")
docker = ["/usr/bin/docker", "--host=unix:///var/run/docker.sock", "--config=/var/lib/livingip/leoclean-nosend/docker-config"]
expected = {f"livingip-{request_id}-{prompt_id}" for prompt_id in ("dc01", "dc02", "dc03", "dc04", "dc05", "dc06")}
listed = subprocess.run(
    [*docker, "ps", "-aq", "--filter", f"label=livingip.m5.request={request_id}",
     "--filter", "label=livingip.container.role=leoclean-m5-prompt-ingress"],
    stdin=subprocess.DEVNULL, capture_output=True, check=False, timeout=30,
)
if listed.returncode != 0:
    raise SystemExit("cleanup inspect failed")
container_ids = [row for row in listed.stdout.decode("ascii", "strict").splitlines() if row]
for container_id in container_ids:
    inspected = subprocess.run(
        [*docker, "inspect", "--format={{json .Name}}", container_id],
        stdin=subprocess.DEVNULL, capture_output=True, check=False, timeout=30,
    )
    if inspected.returncode != 0:
        raise SystemExit("cleanup container inspect failed")
    name = json.loads(inspected.stdout.decode("utf-8", "strict")).lstrip("/")
    if name not in expected:
        raise SystemExit("cleanup container identity mismatch")
    removed = subprocess.run(
        [*docker, "rm", "-f", container_id],
        stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
        check=False, timeout=45,
    )
    if removed.returncode != 0:
        raise SystemExit("cleanup container removal failed")
remaining = subprocess.run(
    [*docker, "ps", "-aq", "--filter", f"label=livingip.m5.request={request_id}",
     "--filter", "label=livingip.container.role=leoclean-m5-prompt-ingress"],
    stdin=subprocess.DEVNULL, capture_output=True, check=False, timeout=30,
)
if remaining.returncode != 0 or remaining.stdout.strip():
    raise SystemExit("cleanup did not prove container absence")
try:
    if os.path.isfile(uploaded) and not os.path.islink(uploaded):
        os.unlink(uploaded)
except OSError:
    pass
try:
    if os.path.isdir(stage) and not os.path.islink(stage):
        shutil.rmtree(stage)
except OSError:
    pass
"""

Runner = Callable[..., subprocess.CompletedProcess[bytes]]


class PromptIngressPlanError(RuntimeError):
    """The M5 ingress could not be planned or executed safely."""


def _require(condition: bool, message: str) -> None:
    if not condition:
        raise PromptIngressPlanError(message)


def _sha256_bytes(value: bytes) -> str:
    return hashlib.sha256(value).hexdigest()


def _canonical_json(value: Mapping[str, Any]) -> bytes:
    return (json.dumps(value, allow_nan=False, separators=(",", ":"), sort_keys=True) + "\n").encode("utf-8")


def _strict_json(raw: bytes, label: str) -> dict[str, Any]:
    def reject_duplicates(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
        result: dict[str, Any] = {}
        for key, value in pairs:
            if key in result:
                raise ValueError("duplicate key")
            result[key] = value
        return result

    try:
        value = json.loads(
            raw.decode("utf-8", "strict"),
            object_pairs_hook=reject_duplicates,
            parse_constant=lambda _value: (_ for _ in ()).throw(ValueError("constant")),
        )
    except (UnicodeError, ValueError, json.JSONDecodeError, RecursionError) as exc:
        raise PromptIngressPlanError(f"{label} was invalid JSON") from exc
    _require(isinstance(value, dict), f"{label} was not a JSON object")
    return value


def _write_private(path: Path, value: Mapping[str, Any]) -> None:
    parent = path.parent.resolve(strict=True)
    observed = parent.stat()
    _require(
        parent.is_dir() and observed.st_uid == os.geteuid() and observed.st_mode & 0o077 == 0,
        "output parent must be private and owned by the operator",
    )
    _require(not path.exists() and not path.is_symlink(), "output path already existed")
    descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0), 0o600)
    with os.fdopen(descriptor, "wb") as handle:
        handle.write(_canonical_json(value))
        handle.flush()
        os.fsync(handle.fileno())


def _validate_bindings(
    runner_revision: str,
    runtime_revision: str,
    image_digest: str,
    config_digest: str,
    release_sha256: str,
) -> dict[str, str]:
    _require(HEX_40.fullmatch(runner_revision) is not None, "runner revision must be one full Git SHA")
    _require(HEX_40.fullmatch(runtime_revision) is not None, "runtime revision must be one full Git SHA")
    _require(DIGEST.fullmatch(image_digest) is not None, "image digest must be one full immutable digest")
    _require(DIGEST.fullmatch(config_digest) is not None, "config digest must be one full immutable digest")
    _require(HEX_64.fullmatch(release_sha256) is not None, "release SHA-256 was invalid")
    return {
        "runner_revision": runner_revision,
        "runtime_revision": runtime_revision,
        "image_reference": f"{IMAGE_REPOSITORY}@{image_digest}",
        "image_digest": image_digest,
        "image_config_digest": config_digest,
        "release_sha256": release_sha256,
    }


def _remote_paths(request_id: str) -> tuple[str, str]:
    _require(REQUEST_ID.fullmatch(request_id) is not None, "request ID was invalid")
    return (
        f"/tmp/livingip-{request_id}-prompt-ingress.py",
        f"{REMOTE_ROOT}/{request_id}",
    )


def build_gcloud_commands(
    *,
    request_id: str,
    bindings: Mapping[str, str],
    payload_sha256: str,
    prompt_catalog_sha256: str,
    ssh_key: Path,
) -> tuple[list[str], list[str], list[str]]:
    upload, stage = _remote_paths(request_id)
    _require(HEX_64.fullmatch(payload_sha256) is not None, "payload hash was invalid")
    _require(HEX_64.fullmatch(prompt_catalog_sha256) is not None, "prompt catalog hash was invalid")
    _require(ssh_key.is_absolute(), "SSH key path was not absolute")
    key_flag = f"--ssh-key-file={ssh_key}"
    scp = [
        GCLOUD,
        "compute",
        "scp",
        f"--project={PROJECT}",
        f"--zone={ZONE}",
        "--tunnel-through-iap",
        f"--ssh-key-expire-after={KEY_LIFETIME}",
        key_flag,
        "--quiet",
        str(PAYLOAD),
        f"{INSTANCE}:{upload}",
    ]
    remote = [
        "sudo",
        "--",
        "/usr/bin/python3.11",
        "-I",
        "-c",
        REMOTE_EXECUTOR_SOURCE,
        upload,
        payload_sha256,
        bindings["image_reference"],
        bindings["image_config_digest"],
        bindings["release_sha256"],
        bindings["runtime_revision"],
        request_id,
        prompt_catalog_sha256,
    ]
    ssh = [
        GCLOUD,
        "compute",
        "ssh",
        INSTANCE,
        f"--project={PROJECT}",
        f"--zone={ZONE}",
        "--tunnel-through-iap",
        f"--ssh-key-expire-after={KEY_LIFETIME}",
        key_flag,
        "--quiet",
        f"--command={shlex.join(remote)}",
    ]
    cleanup_remote = [
        "sudo",
        "--",
        "/usr/bin/python3.11",
        "-I",
        "-c",
        CLEANUP_SOURCE,
        upload,
        stage,
        request_id,
    ]
    cleanup = [*ssh[:-1], f"--command={shlex.join(cleanup_remote)}"]
    return scp, ssh, cleanup


def prepare_plan(
    *,
    request_id: str,
    runner_revision: str,
    runtime_revision: str,
    image_digest: str,
    config_digest: str,
    release_sha256: str,
    provider_secret_name: str,
    output: Path,
) -> dict[str, Any]:
    bindings = _validate_bindings(
        runner_revision,
        runtime_revision,
        image_digest,
        config_digest,
        release_sha256,
    )
    _require(PAYLOAD.is_file() and not PAYLOAD.is_symlink(), "ingress payload was unavailable")
    _require(SECRET_NAME.fullmatch(provider_secret_name) is not None, "provider secret name was invalid")
    payload_sha256 = _sha256_bytes(PAYLOAD.read_bytes())
    catalog_sha256 = ingress.prompt_catalog_sha256()
    ssh_key = output.parent / f"{request_id}-ssh-key"
    commands = build_gcloud_commands(
        request_id=request_id,
        bindings=bindings,
        payload_sha256=payload_sha256,
        prompt_catalog_sha256=catalog_sha256,
        ssh_key=ssh_key,
    )
    stable = {
        "schema": PLAN_SCHEMA,
        "status": "pass",
        "mode": "dry_run",
        "request_id": request_id,
        "target": {
            "project": PROJECT,
            "zone": ZONE,
            "instance": INSTANCE,
            "service": SERVICE,
            "container": CONTAINER_NAME,
            "transport": "iap_only",
        },
        "bindings": bindings,
        "ingress": {
            "payload": str(PAYLOAD),
            "payload_sha256": payload_sha256,
            "remote_executor_sha256": _sha256_bytes(REMOTE_EXECUTOR_SOURCE.encode("utf-8")),
            "prompt_catalog_sha256": catalog_sha256,
            "prompt_ids": list(PROMPT_IDS),
            "container_count": len(PROMPT_IDS),
            "session_policy": "one_fresh_transient_container_per_prompt",
            "provider_secret_name": provider_secret_name,
            "claim_ceiling": CLAIM_CEILING,
        },
        "actions": [
            {"name": name, "argv_sha256": _sha256_bytes(_canonical_json({"argv": argv}))}
            for name, argv in zip(("upload_payload", "run_ingress", "cleanup_failed_transfer"), commands, strict=True)
        ],
        "authority": {
            "gcp_read": True,
            "transient_container_execution": True,
            "managed_service_mutation": False,
            "database_write": False,
            "telegram": False,
            "vps": False,
            "production_traffic": False,
            "public_endpoint": False,
            "image_rebuild": False,
        },
    }
    return {**stable, "plan_sha256": _sha256_bytes(_canonical_json(stable))}


def _run_bounded(
    argv: list[str],
    *,
    runner: Runner,
    environment: Mapping[str, str],
    label: str,
    input_bytes: bytes | None = None,
    timeout: int = 300,
    accepted: tuple[int, ...] = (0,),
) -> subprocess.CompletedProcess[bytes]:
    try:
        completed = runner(
            argv,
            input=input_bytes,
            stdin=subprocess.DEVNULL if input_bytes is None else None,
            capture_output=True,
            check=False,
            timeout=timeout,
            env=dict(environment),
        )
    except (OSError, subprocess.SubprocessError) as exc:
        raise PromptIngressPlanError(f"{label} failed") from exc
    _require(
        len(completed.stdout) <= MAX_OUTPUT_BYTES and len(completed.stderr) <= MAX_OUTPUT_BYTES,
        f"{label} output exceeded the limit",
    )
    _require(completed.returncode in accepted, f"{label} failed")
    return completed


def pinned_gcloud_environment(*, runner: Runner = subprocess.run) -> dict[str, str]:
    home_value = os.environ.get("HOME", "")
    _require(home_value, "HOME was not configured")
    home = iap._validate_owned_directory(Path(home_value), "HOME")
    config_value = os.environ.get("CLOUDSDK_CONFIG") or str(home / ".config/gcloud")
    config = iap._validate_owned_directory(Path(config_value), "Cloud SDK configuration")
    uv = shutil.which("uv", path="/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin")
    _require(uv is not None and Path(uv).is_absolute(), "uv was unavailable")
    uv_path = Path(uv).resolve(strict=True)
    uv_state = uv_path.stat(follow_symlinks=False)
    _require(
        stat.S_ISREG(uv_state.st_mode) and os.access(uv_path, os.X_OK) and not uv_state.st_mode & 0o022,
        "uv was unsafe",
    )
    base = {
        "PATH": "/usr/bin:/bin:/usr/sbin:/sbin:/opt/homebrew/bin",
        "HOME": str(home),
        "CLOUDSDK_CONFIG": str(config),
    }
    found = _run_bounded(
        [str(uv_path), "python", "find", "3.11"],
        runner=runner,
        environment=base,
        label="pinned Python resolution",
    )
    raw_path = found.stdout.decode("utf-8", "strict").strip()
    _require(raw_path and Path(raw_path).is_absolute(), "pinned Python resolution was invalid")
    python = Path(raw_path).resolve(strict=True)
    python_state = python.stat(follow_symlinks=False)
    _require(
        stat.S_ISREG(python_state.st_mode)
        and os.access(python, os.X_OK)
        and not python_state.st_mode & 0o022,
        "pinned Python was unsafe",
    )
    verified = _run_bounded(
        [str(python), "--version"],
        runner=runner,
        environment={"PATH": "/usr/bin:/bin"},
        label="pinned Python verification",
    )
    version = (verified.stdout + verified.stderr).decode("ascii", "strict").strip()
    _require(re.fullmatch(r"Python 3\.11\.[0-9]+", version) is not None, "pinned Python was not 3.11")
    return {**base, "CLOUDSDK_PYTHON": str(python)}


def _fetch_provider_secret(
    secret_name: str,
    *,
    runner: Runner,
    environment: Mapping[str, str],
) -> bytes:
    _require(SECRET_NAME.fullmatch(secret_name) is not None, "provider secret name was invalid")
    argv = [
        GCLOUD,
        "secrets",
        "versions",
        "access",
        "latest",
        f"--project={PROJECT}",
        f"--secret={secret_name}",
    ]
    completed = _run_bounded(argv, runner=runner, environment=environment, label="provider credential read")
    value = completed.stdout
    if value.endswith(b"\n"):
        value = value[:-1]
    _require(
        16 <= len(value) <= ingress.MAX_SECRET_BYTES
        and b"\n" not in value
        and b"\r" not in value
        and b"\0" not in value,
        "provider credential read was invalid",
    )
    return value


def _validate_remote_result(plan: Mapping[str, Any], value: Mapping[str, Any]) -> None:
    _require(
        value.get("schema") == REMOTE_RESULT_SCHEMA
        and value.get("status") == "pass"
        and value.get("request_id") == plan.get("request_id"),
        "remote result contract was invalid",
    )
    bindings = value.get("bindings")
    expected = plan["bindings"]
    _require(
        isinstance(bindings, dict)
        and bindings
        == {
            "image_reference": expected["image_reference"],
            "image_config_digest": expected["image_config_digest"],
            "release_sha256": expected["release_sha256"],
            "runtime_revision": expected["runtime_revision"],
            "ingress_sha256": plan["ingress"]["payload_sha256"],
            "prompt_catalog_sha256": plan["ingress"]["prompt_catalog_sha256"],
        },
        "remote result bindings were invalid",
    )
    turns = value.get("turns")
    _require(
        isinstance(turns, list)
        and [row.get("prompt_id") for row in turns if isinstance(row, dict)] == list(PROMPT_IDS),
        "remote result prompt set was invalid",
    )
    _require(
        value.get("service_unchanged") is True
        and value.get("service_before") == value.get("service_after")
        and value.get("cleanup")
        == {
            "transient_containers_remaining": [],
            "staged_payload_removed": True,
        },
        "remote result did not prove cleanup and service stability",
    )
    _require(value.get("authority") == NO_SEND_AUTHORITY, "remote result authority was invalid")
    stable = {key: item for key, item in value.items() if key != "receipt_sha256"}
    _require(value.get("receipt_sha256") == _sha256_bytes(_canonical_json(stable)), "remote result hash was invalid")


def _validate_remote_failure(plan: Mapping[str, Any], value: Mapping[str, Any]) -> None:
    _require(
        value.get("schema") == REMOTE_FAILURE_SCHEMA
        and value.get("status") == "fail"
        and value.get("request_id") == plan.get("request_id"),
        "remote failure contract was invalid",
    )
    _require(
        value.get("authority") == NO_SEND_AUTHORITY
        and value.get("cleanup")
        == {
            "transient_containers_remaining": [],
            "staged_payload_removed": True,
        },
        "remote failure did not prove authority and cleanup",
    )
    before = value.get("service_before")
    after = value.get("service_after")
    _require(before is None or before == after, "remote failure changed the managed service")
    turn_failure = value.get("turn_failure")
    if turn_failure is not None:
        _require(isinstance(turn_failure, dict), "remote turn failure was invalid")
        turn_stable = {key: item for key, item in turn_failure.items() if key != "receipt_sha256"}
        _require(
            turn_failure.get("schema") == ingress.FAILURE_SCHEMA
            and turn_failure.get("status") == "fail"
            and turn_failure.get("receipt_sha256") == _sha256_bytes(_canonical_json(turn_stable)),
            "remote turn failure was invalid",
        )
    stable = {key: item for key, item in value.items() if key != "receipt_sha256"}
    _require(value.get("receipt_sha256") == _sha256_bytes(_canonical_json(stable)), "remote failure hash was invalid")


def execute_plan(
    plan: Mapping[str, Any],
    *,
    output: Path,
    runner: Runner = subprocess.run,
    git_runner: Runner = subprocess.run,
    gcloud_env: Mapping[str, str] | None = None,
) -> dict[str, Any]:
    _require(
        set(plan)
        == {
            "schema",
            "status",
            "mode",
            "request_id",
            "target",
            "bindings",
            "ingress",
            "actions",
            "authority",
            "plan_sha256",
        }
        and plan.get("schema") == PLAN_SCHEMA
        and plan.get("status") == "pass"
        and plan.get("mode") == "dry_run",
        "plan was invalid",
    )
    stable_plan = {key: item for key, item in plan.items() if key != "plan_sha256"}
    _require(plan.get("plan_sha256") == _sha256_bytes(_canonical_json(stable_plan)), "plan hash was invalid")
    _require(
        plan.get("target")
        == {
            "project": PROJECT,
            "zone": ZONE,
            "instance": INSTANCE,
            "service": SERVICE,
            "container": CONTAINER_NAME,
            "transport": "iap_only",
        },
        "plan target was invalid",
    )
    _require(
        plan.get("authority")
        == {
            "gcp_read": True,
            "transient_container_execution": True,
            "managed_service_mutation": False,
            "database_write": False,
            "telegram": False,
            "vps": False,
            "production_traffic": False,
            "public_endpoint": False,
            "image_rebuild": False,
        },
        "plan authority was invalid",
    )
    _require(
        isinstance(plan.get("ingress"), dict)
        and plan["ingress"].get("payload") == str(PAYLOAD)
        and plan["ingress"].get("payload_sha256") == _sha256_bytes(PAYLOAD.read_bytes())
        and plan["ingress"].get("remote_executor_sha256")
        == _sha256_bytes(REMOTE_EXECUTOR_SOURCE.encode("utf-8"))
        and plan["ingress"].get("prompt_catalog_sha256") == ingress.prompt_catalog_sha256()
        and plan["ingress"].get("prompt_ids") == list(PROMPT_IDS)
        and plan["ingress"].get("container_count") == len(PROMPT_IDS)
        and SECRET_NAME.fullmatch(str(plan["ingress"].get("provider_secret_name") or ""))
        is not None
        and plan["ingress"].get("claim_ceiling") == CLAIM_CEILING,
        "plan ingress binding was invalid",
    )
    runner_revision = str(plan["bindings"]["runner_revision"])
    iap.validate_clean_revision(runner_revision, runner=git_runner)
    iap.validate_remote_main(runner_revision, runner=git_runner)
    environment = dict(gcloud_env or pinned_gcloud_environment())
    provider_secret_name = str(plan["ingress"].get("provider_secret_name") or "")
    _require(SECRET_NAME.fullmatch(provider_secret_name) is not None, "plan provider secret name was invalid")
    secret = _fetch_provider_secret(provider_secret_name, runner=runner, environment=environment)
    request_id = str(plan["request_id"])
    ssh_key = output.parent / f"{request_id}-ssh-key"
    _require(
        not ssh_key.exists()
        and not ssh_key.is_symlink()
        and not Path(f"{ssh_key}.pub").exists()
        and not Path(f"{ssh_key}.pub").is_symlink(),
        "request SSH key path already existed",
    )
    commands = build_gcloud_commands(
        request_id=request_id,
        bindings=plan["bindings"],
        payload_sha256=str(plan["ingress"]["payload_sha256"]),
        prompt_catalog_sha256=str(plan["ingress"]["prompt_catalog_sha256"]),
        ssh_key=ssh_key,
    )
    expected_actions = [
        {"name": name, "argv_sha256": _sha256_bytes(_canonical_json({"argv": argv}))}
        for name, argv in zip(("upload_payload", "run_ingress", "cleanup_failed_transfer"), commands, strict=True)
    ]
    _require(plan.get("actions") == expected_actions, "plan actions were invalid")
    scp, ssh, cleanup = commands
    completed: subprocess.CompletedProcess[bytes] | None = None
    try:
        try:
            _run_bounded(scp, runner=runner, environment=environment, label="IAP payload upload")
            completed = _run_bounded(
                ssh,
                runner=runner,
                environment=environment,
                label="IAP prompt ingress",
                input_bytes=secret + b"\n",
                timeout=2700,
                accepted=(0, 65),
            )
        except BaseException:
            _run_bounded(cleanup, runner=runner, environment=environment, label="IAP ingress cleanup")
            raise
    finally:
        secret = b""
        iap._cleanup_local_ssh_key(ssh_key)
    _require(completed is not None and completed.stdout, "remote result was absent")
    result = _strict_json(completed.stdout, "remote result")
    normalized = json.dumps(result, allow_nan=False, sort_keys=True).casefold()
    _require(
        not any(marker in normalized for marker in SECRET_OUTPUT_MARKERS)
        and TELEGRAM_TOKEN.search(normalized) is None,
        "remote result was not sanitized",
    )
    if completed.returncode == 65:
        _validate_remote_failure(plan, result)
        _write_private(output, result)
        raise PromptIngressPlanError(
            f"prompt ingress failed closed at {result.get('failure_stage')}/{result.get('failure_reason')}"
        )
    _validate_remote_result(plan, result)
    stable = {
        "schema": RESULT_SCHEMA,
        "status": "pass",
        "plan_sha256": plan["plan_sha256"],
        "request_id": request_id,
        "runner_revision": runner_revision,
        "provider_secret_name": provider_secret_name,
        "remote_receipt": result,
        "authority": dict(plan["authority"]),
    }
    receipt = {**stable, "receipt_sha256": _sha256_bytes(_canonical_json(stable))}
    _write_private(output, receipt)
    return receipt


def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--request-id", default=f"m5-{uuid.uuid4().hex[:16]}")
    parser.add_argument("--runner-revision", required=True)
    parser.add_argument("--runtime-revision", required=True)
    parser.add_argument("--image-digest", required=True)
    parser.add_argument("--image-config-digest", required=True)
    parser.add_argument("--release-sha256", required=True)
    parser.add_argument("--provider-secret-name", required=True)
    parser.add_argument("--output", required=True, type=Path)
    parser.add_argument("--execute", action="store_true")
    return parser.parse_args(argv)


def main(argv: list[str] | None = None) -> int:
    args = parse_args(argv)
    try:
        output = args.output.expanduser()
        _require(output.is_absolute(), "--output must be absolute")
        plan = prepare_plan(
            request_id=args.request_id,
            runner_revision=args.runner_revision,
            runtime_revision=args.runtime_revision,
            image_digest=args.image_digest,
            config_digest=args.image_config_digest,
            release_sha256=args.release_sha256,
            provider_secret_name=args.provider_secret_name,
            output=output,
        )
        if not args.execute:
            print(json.dumps(plan, indent=2, sort_keys=True))
            return 0
        execute_plan(
            plan,
            output=output,
        )
        print(json.dumps({"status": "pass", "output": str(output)}, sort_keys=True))
        return 0
    except PromptIngressPlanError as exc:
        print(json.dumps({"status": "fail", "error": str(exc)}, sort_keys=True), file=sys.stderr)
        return 65


if __name__ == "__main__":
    raise SystemExit(main())
