"""Run the signed-release example in a disposable, disconnected Docker service.

The caller supplies the digest accepted by its promotion verifier and a journal
callback. This module checks bytes and runtime controls; it does not authorize
release, contact GitLab, or grant Docker access. Docker-host administrators are
trusted. Operations are sequential and never replay an uncertain mutation.
"""
from __future__ import annotations

import hashlib
import json
from pathlib import Path
import re
import subprocess
import time
import uuid


# Immutable multi-platform index, resolved locally for the stated platform.
IMAGE = "python@sha256:f77ac9e44ae96ef2c90b8053ea08c31f8be030f824196b0ae4db6d462c84e51f"
PLATFORM = "linux/arm64"


class DockerRuntime:
    """Manage only exact, labelled containers belonging to one release exercise.

    Args:
        event: Callable accepting a kind and keyword fields, persisting evidence.
        run_id: Unique lowercase hexadecimal identifier, 16 to 32 characters.
        context: Explicit Docker context owned by the trusted release operator.

    Side effects:
        Methods read Docker state, start/remove containers and append evidence.
        No daemon, network port or persistent Docker credential is installed.

    Raises:
        ValueError for invalid identities; RuntimeError for failed checks or
        uncertain operations. Callers must serialize calls and reconcile a
        stopped operation using its exact recorded name before continuing.
    """

    def __init__(self, event, run_id, context="desktop-linux"):
        """Store the caller's evidence sink and explicit runtime identity.

        Validates a hexadecimal run ID without contacting Docker. Construction
        is deterministic and creates no resource; invalid input raises ValueError.
        """
        if not re.fullmatch(r"[0-9a-f]{16,32}", run_id):
            raise ValueError("Use a unique hexadecimal run ID")
        self.event, self.run_id, self.context = event, run_id, context

    def command(self, label, args, allowed=(0,), mutation=False):
        """Execute one Docker command and retain its response before checking it.

        Args:
            label: Human-readable evidence label.
            args: Docker arguments, with no shell interpolation or secrets.
            allowed: Accepted return codes for this specific operation.
            mutation: Whether a timeout could have left a changed Docker resource.

        Returns:
            CompletedProcess with bounded captured text.

        Raises:
            RuntimeError after preserving a nonzero or timeout result. A timeout
            never proves absence and never causes automatic replay. Appends two
            journal events on an ordinary response. Commands run sequentially.
        """
        attempt = uuid.uuid4().hex
        argv = ["docker", "--context", self.context, *args]
        self.event("docker_intent", attempt_id=attempt, label=label,
                   mutation=mutation, argv=argv)
        try:
            result = subprocess.run(argv, capture_output=True, text=True, timeout=45)
        except subprocess.TimeoutExpired:
            self.event("docker_result", attempt_id=attempt, label=label,
                       outcome="outcome_unknown" if mutation else "read_interrupted")
            raise RuntimeError("Docker request timed out; reconcile the recorded identity") from None
        self.event("docker_result", attempt_id=attempt, label=label,
                   returncode=result.returncode, stdout=result.stdout, stderr=result.stderr)
        if result.returncode not in allowed:
            raise RuntimeError(f"Docker operation failed: {label}")
        return result

    def absent(self, name):
        """Require an exact name to be absent using Docker's object-not-found reply.

        Reads one container, returns True only for the explicit missing-object
        response, and journals that reply. Other errors and existing containers
        raise RuntimeError; this read performs no mutation or retry.
        """
        result = self.command("inspect exact container absence",
                              ["container", "inspect", name], allowed=(0, 1))
        if result.returncode != 1 or not any(
                message in result.stderr.lower() for message in ("no such object", "no such container")):
            raise RuntimeError("Exact container absence was not established")
        return True

    def start(self, artifact, expected_sha256, version, label):
        """Start accepted bytes once and return the exact resource identity.

        Args:
            artifact: Existing regular artifact file, outside application write access.
            expected_sha256: Digest already accepted by the promotion verifier.
            version: Expected harmless fixture version, checked by verify().
            label: Simple unique name within this run, such as initial-a or rollback-a.

        Side effects:
            Creates one restricted container and journals its identity. The caller
            keeps it alive until explicit removal; a failed/unknown creation is
            reconciled by exact name, never repeated. No host port is published.

        Raises:
            RuntimeError before creation on byte/image/absence mismatch. A later
            error can leave the recorded container requiring explicit cleanup.
        """
        artifact = Path(artifact).resolve(strict=True)
        if not artifact.is_file() or not re.fullmatch(r"[0-9a-f]{64}", expected_sha256):
            raise ValueError("Expected a regular artifact and full SHA-256 digest")
        observed = hashlib.sha256(artifact.read_bytes()).hexdigest()
        if observed != expected_sha256:
            self.event("artifact_rejected", expected=expected_sha256, observed=observed)
            raise RuntimeError("Artifact bytes differ from the accepted digest")
        if not re.fullmatch(r"[a-z][a-z0-9-]{0,30}", label):
            raise ValueError("Invalid container label")
        name = f"gss-connected-{self.run_id[:16]}-{label}"
        self.absent(name)
        image = json.loads(self.command("inspect pinned runtime image",
                           ["image", "inspect", IMAGE]).stdout)[0]
        if image.get("Os") != "linux" or image.get("Architecture") != "arm64" \
                or IMAGE not in image.get("RepoDigests", []):
            raise RuntimeError("Pinned runtime image or platform differs")
        receipt = {"name": name, "run_id": self.run_id, "artifact": str(artifact),
                   "artifact_sha256": expected_sha256, "version": version,
                   "image_id": image["Id"], "image_reference": IMAGE, "platform": PLATFORM}
        self.event("container_create_pending", receipt=receipt)
        result = self.command("start accepted release", [
            "run", "--detach", "--pull=never", "--name", name,
            "--label", f"gss.connected.release={self.run_id}",
            "--platform", PLATFORM, "--network", "none", "--read-only",
            "--user", "65532:65532", "--cap-drop", "ALL",
            "--security-opt", "no-new-privileges", "--memory", "64m",
            "--cpus", "0.5", "--pids-limit", "64",
            "--mount", f"type=bind,src={artifact},dst=/artifact/release.pyz,readonly",
            IMAGE, "python", "/artifact/release.pyz"], mutation=True)
        container_id = result.stdout.strip()
        if not re.fullmatch(r"[0-9a-f]{64}", container_id):
            raise RuntimeError("Create response lacks an exact container ID; reconcile its name")
        receipt["container_id"] = container_id
        self.event("container_created", receipt=receipt)
        return receipt

    def inspect(self, receipt):
        """Read a recorded container and enforce ID/run-label ownership.

        Returns the full inspect object. Journals the read and raises RuntimeError
        for an unexpected identity, without changing Docker state or retrying.
        """
        body = json.loads(self.command("inspect recorded release",
                          ["container", "inspect", receipt["container_id"]]).stdout)[0]
        if body.get("Id") != receipt["container_id"] \
                or body.get("Name") != "/" + receipt["name"] \
                or body.get("Config", {}).get("Labels", {}).get("gss.connected.release") != self.run_id:
            raise RuntimeError("Container identity or ownership differs")
        return body

    def verify(self, receipt):
        """Verify running bytes, health, version and selected runtime restrictions.

        Uses the exact ID and run label from start(); performs read-only Docker
        inspect and exec probes. Returns a proof dictionary after all checks.
        Up to ten health reads allow normal startup; other failures raise without
        replacing the container. The caller owns recovery and final removal.
        """
        body = self.inspect(receipt)
        host, config = body.get("HostConfig", {}), body.get("Config", {})
        mounts = body.get("Mounts", [])
        expected_mount = [x for x in mounts if x.get("Destination") == "/artifact/release.pyz"]
        if body.get("State", {}).get("Running") is not True \
                or body.get("Image") != receipt["image_id"] \
                or host.get("NetworkMode") != "none" or host.get("ReadonlyRootfs") is not True \
                or host.get("CapDrop") != ["ALL"] or config.get("User") != "65532:65532" \
                or "no-new-privileges" not in host.get("SecurityOpt", []) \
                or host.get("Memory") != 64 * 1024 * 1024 or host.get("NanoCpus") != 500000000 \
                or host.get("PidsLimit") != 64 \
                or body.get("NetworkSettings", {}).get("Ports") not in ({}, None) \
                or len(mounts) != 1 or len(expected_mount) != 1 \
                or expected_mount[0].get("RW") is not False \
                or expected_mount[0].get("Source") != receipt["artifact"]:
            raise RuntimeError("Selected runtime controls differ")
        container_id = receipt["container_id"]
        health = None
        for poll in range(1, 11):
            result = self.command(f"health read {poll}", ["exec", container_id, "python", "-c",
                "import urllib.request; print(urllib.request.urlopen('http://127.0.0.1:8080/healthz', timeout=3).read().decode())"],
                allowed=(0, 1))
            if result.returncode == 0:
                health = json.loads(result.stdout)
                break
            time.sleep(1)
        if health != {"status": "ok", "version": receipt["version"]}:
            raise RuntimeError("Service health does not match the accepted release")
        version = json.loads(self.command("version read", ["exec", container_id, "python", "-c",
            "import urllib.request; print(urllib.request.urlopen('http://127.0.0.1:8080/version', timeout=3).read().decode())"]).stdout)
        digest = self.command("mounted artifact digest", ["exec", container_id, "python", "-c",
            "import hashlib; print(hashlib.sha256(open('/artifact/release.pyz','rb').read()).hexdigest())"]).stdout.strip()
        if version != {"version": receipt["version"]} or digest != receipt["artifact_sha256"]:
            raise RuntimeError("Running artifact identity differs")
        proof = {**receipt, "health": health, "version_response": version, "mounted_sha256": digest}
        self.event("runtime_verified", proof=proof)
        return proof

    def remove(self, receipt):
        """Remove one exact owned container and prove its name is absent.

        Reads and checks the current ID/name/run label before one forced removal.
        Journals removal and absence. Unknown responses raise for reconciliation;
        no wildcard deletion or automatic mutation retry is permitted.
        """
        self.inspect(receipt)
        self.command("remove exact release container",
                     ["container", "rm", "--force", receipt["container_id"]], mutation=True)
        self.absent(receipt["name"])
        self.event("container_removed", receipt=receipt)
