#!/usr/bin/env python3
"""Run and seal LAB E4 full-session EoMT semantic segmentation."""

from __future__ import annotations

import argparse
import hashlib
import importlib.metadata
import json
import os
import platform
import resource
import shutil
import time
from collections import Counter
from datetime import UTC, datetime
from pathlib import Path
from typing import Any

from run_e3_rectified_segmentation import (
    _dependency_manifest,
    _model_snapshot,
    _profile,
    _resource_delta,
    _resource_snapshot,
    _verify_model_files,
)
from run_recorded_perception_epoch import (
    FRAME_SCHEMA,
    REPORT_SCHEMA,
    RESULT_SCHEMA,
    _artifact,
    _canonical_json,
    _GpuTelemetry,
    _palette,
    _percentiles,
    _read_timeline,
    _sha256,
    _valid_sha256,
    _validate_job,
    _write_json,
)

IDENTITY_SCHEMA = "missioncore.recorded-perception-identity/v2"
VALID_FOV_SCHEMA = "missioncore.k1-valid-fov-mask/v1"
PIPELINE_ID = "recorded-semantic-eomt-fisheye-mask/v1"
SEMANTIC_ALPHA = 0.48
TARGET_CLASS_COUNT = 16


def _arguments() -> argparse.Namespace:
    parser = argparse.ArgumentParser()
    commands = parser.add_subparsers(dest="command", required=True)

    preflight = commands.add_parser("preflight")
    preflight.add_argument("--job", type=Path, required=True)
    preflight.add_argument("--profile", type=Path, required=True)
    preflight.add_argument("--valid-fov-root", type=Path, required=True)
    preflight.add_argument("--cache", type=Path, required=True)
    preflight.add_argument("--environment", type=Path, required=True)

    run = commands.add_parser("run")
    run.add_argument("--job", type=Path, required=True)
    run.add_argument("--profile", type=Path, required=True)
    run.add_argument("--valid-fov-root", type=Path, required=True)
    run.add_argument("--frames", type=Path, required=True)
    run.add_argument("--timeline", type=Path, required=True)
    run.add_argument("--cache", type=Path, required=True)
    run.add_argument("--environment", type=Path, required=True)
    run.add_argument("--output", type=Path, required=True)
    run.add_argument("--frame-limit", type=int, default=0)
    run.add_argument("--free-bytes-floor", type=int, default=0)
    run.add_argument("--orchestrator-sha256", required=True)
    run.add_argument("--container-image", required=True)
    run.add_argument("--telemetry-interval-seconds", type=float, default=1.0)

    finalize = commands.add_parser("finalize")
    finalize.add_argument("--output", type=Path, required=True)
    finalize.add_argument("--video", type=Path, required=True)
    finalize.add_argument("--masks", type=Path, required=True)
    finalize.add_argument("--extract-seconds", type=float, required=True)
    finalize.add_argument("--encode-seconds", type=float, required=True)
    finalize.add_argument("--archive-seconds", type=float, required=True)
    finalize.add_argument("--wall-seconds", type=float, required=True)
    finalize.add_argument("--encoder", required=True)
    finalize.add_argument("--disk-free-before-bytes", type=int, required=True)
    finalize.add_argument("--disk-free-post-extract-bytes", type=int, required=True)
    finalize.add_argument("--disk-free-post-inference-bytes", type=int, required=True)
    finalize.add_argument("--disk-free-post-artifacts-bytes", type=int, required=True)
    finalize.add_argument("--disk-floor-bytes", type=int, required=True)
    finalize.add_argument("--working-set-reserve-bytes", type=int, required=True)
    return parser.parse_args()


def _read_object(path: Path) -> dict[str, Any]:
    value = json.loads(path.read_text(encoding="utf-8-sig"))
    if not isinstance(value, dict):
        raise RuntimeError(f"JSON root is not an object: {path}")
    return value


def _validate_source(job: dict[str, Any], profile: dict[str, Any]) -> None:
    source = profile["source"]
    input_document = job["input"]
    if (
        input_document.get("kind") != "canonical-camera-epoch"
        or input_document.get("source_id") != source["source_id"]
        or source.get("resolution") != [800, 600]
    ):
        raise RuntimeError("LAB E4 profile does not match the camera job")


def _load_valid_fov(
    root: Path,
    job: dict[str, Any],
    profile: dict[str, Any],
) -> tuple[Any, dict[str, Any]]:
    import numpy as np
    from PIL import Image

    resolved = root.resolve(strict=True)
    manifest = _read_object(resolved / "manifest.json")
    identity = manifest.get("identity")
    identity_sha256 = manifest.get("identity_sha256")
    artifact = manifest.get("artifact")
    source = profile["source"]
    if (
        manifest.get("schema_version") != VALID_FOV_SCHEMA
        or not isinstance(identity, dict)
        or not _valid_sha256(identity_sha256)
        or hashlib.sha256(_canonical_json(identity)).hexdigest() != identity_sha256
        or manifest.get("generation_id") != f"valid-fov-mask-{identity_sha256}"
        or identity.get("calibration_sha256") != source["calibration_sha256"]
        or identity.get("calibration_slot") != source["calibration_slot"]
        or identity.get("source_id") != job["input"]["source_id"]
        or identity.get("admitted_resolution") != source["resolution"]
        or not isinstance(artifact, dict)
        or artifact.get("path") != "mask.png"
        or artifact.get("mode") != "L"
        or artifact.get("inside_value") != 255
        or artifact.get("outside_value") != 0
        or not _valid_sha256(artifact.get("sha256"))
    ):
        raise RuntimeError("LAB E4 valid-FOV binding is invalid")
    mask_path = (resolved / "mask.png").resolve(strict=True)
    if (
        mask_path.parent != resolved
        or mask_path.stat().st_size != artifact.get("byte_length")
        or _sha256(mask_path) != artifact["sha256"]
    ):
        raise RuntimeError("LAB E4 valid-FOV artifact changed")
    with Image.open(mask_path) as opened:
        mask = np.asarray(opened, dtype=np.uint8)
    if mask.shape != (600, 800) or not np.isin(mask, (0, 255)).all():
        raise RuntimeError("LAB E4 valid-FOV mask pixels are invalid")
    valid = mask > 0
    geometry = manifest.get("geometry")
    if (
        not isinstance(geometry, dict)
        or geometry.get("valid_pixel_count") != int(valid.sum())
        or int(valid.sum()) < 1
    ):
        raise RuntimeError("LAB E4 valid-FOV geometry changed")
    return valid, {
        "generation_id": manifest["generation_id"],
        "identity_sha256": identity_sha256,
        "mask_sha256": artifact["sha256"],
        "valid_pixel_count": int(valid.sum()),
        "total_pixel_count": int(valid.size),
    }


def _load_model(
    profile: dict[str, Any],
    cache: Path,
    device: Any,
) -> tuple[Any, Any, dict[int, str], Any, list[dict[str, Any]]]:
    import numpy as np
    import torch
    from transformers import AutoImageProcessor, EomtForUniversalSegmentation

    snapshot = _model_snapshot(profile, cache, offline=True)
    model_files = _verify_model_files(profile, snapshot)
    processor = AutoImageProcessor.from_pretrained(
        snapshot,
        local_files_only=True,
        use_fast=True,
    )
    model, loading = EomtForUniversalSegmentation.from_pretrained(
        snapshot,
        local_files_only=True,
        output_loading_info=True,
    )
    problems = {
        name: loading.get(name, [])
        for name in ("missing_keys", "unexpected_keys", "mismatched_keys", "error_msgs")
        if loading.get(name)
    }
    if problems:
        raise RuntimeError("EoMT checkpoint did not load exactly: " + json.dumps(problems))
    model = model.to(device=device, dtype=torch.float16).eval()
    labels = {int(key): str(value) for key, value in model.config.id2label.items()}
    mapping = profile["cityscapes_to_target"]
    if set(labels.values()) != set(mapping):
        raise RuntimeError("EoMT runtime taxonomy changed")
    target_lut = np.asarray([mapping[labels[index]] for index in range(19)], dtype=np.uint8)
    return processor, model, labels, target_lut, model_files


def _preflight(args: argparse.Namespace) -> int:
    import torch

    job = _validate_job(args.job.resolve(strict=True))
    profile, profile_sha256 = _profile(args.profile)
    _validate_source(job, profile)
    dependency = _dependency_manifest(args.environment.resolve(strict=True))
    if dependency["identity"]["profile_sha256"] != profile_sha256:
        raise RuntimeError("LAB E4 dependencies belong to another profile")
    _load_valid_fov(args.valid_fov_root, job, profile)
    if not torch.cuda.is_available() or torch.cuda.device_count() < 1:
        raise RuntimeError("CUDA device 0 is unavailable")
    device = torch.device("cuda:0")
    processor, model, _labels, _target_lut, model_files = _load_model(
        profile,
        args.cache.resolve(strict=True),
        device,
    )
    del processor, model, _labels, _target_lut
    torch.cuda.empty_cache()
    print(
        json.dumps(
            {
                "state": "preflight-ready",
                "job_id": job["job_id"],
                "source_id": job["input"]["source_id"],
                "frames": job["input"]["segment_count"],
                "pipeline": PIPELINE_ID,
                "model_files": model_files,
                "cuda_device": torch.cuda.get_device_name(),
            },
            sort_keys=True,
        ),
        flush=True,
    )
    return 0


def _class_document(
    semantic: Any,
    valid_mask: Any,
    target_names: dict[int, str],
) -> list[dict[str, Any]]:
    import numpy as np

    counts = np.bincount(semantic[valid_mask].reshape(-1), minlength=TARGET_CLASS_COUNT)
    total = int(valid_mask.sum())
    return [
        {
            "id": index,
            "label": target_names[index],
            "pixels": int(counts[index]),
            "fraction_of_valid_fov": round(float(counts[index]) / total, 9),
        }
        for index in range(1, TARGET_CLASS_COUNT)
        if counts[index] > 0
    ]


def _overlay(image: Any, semantic: Any) -> Any:
    import numpy as np

    colors = np.zeros_like(image)
    for category_id in range(1, TARGET_CLASS_COUNT):
        colors[semantic == category_id] = _palette(category_id)
    blended = np.rint(
        image.astype(np.float32) * (1.0 - SEMANTIC_ALPHA)
        + colors.astype(np.float32) * SEMANTIC_ALPHA
    )
    return (
        np.where(
            (semantic > 0)[..., None],
            blended,
            image,
        )
        .clip(0, 255)
        .astype(np.uint8)
    )


def _write_png(path: Path, array: Any) -> None:
    from PIL import Image

    Image.fromarray(array).save(path, format="PNG", optimize=False)


def _assert_disk_floor(path: Path, floor: int, frame: int) -> None:
    if floor < 0:
        raise RuntimeError("disk free-space floor is invalid")
    free = shutil.disk_usage(path).free
    if floor and free < floor:
        raise RuntimeError(f"D-backed output crossed its free-space floor at frame {frame}")


def _run(args: argparse.Namespace) -> int:
    import numpy as np
    import torch
    import transformers
    from PIL import Image

    job_root = args.job.resolve(strict=True)
    if not _valid_sha256(args.orchestrator_sha256):
        raise RuntimeError("LAB E4 orchestrator SHA-256 is invalid")
    if not 1 <= len(args.container_image) <= 256:
        raise RuntimeError("LAB E4 container image identity is invalid")
    job = _validate_job(job_root)
    profile, profile_sha256 = _profile(args.profile)
    _validate_source(job, profile)
    dependency = _dependency_manifest(args.environment.resolve(strict=True))
    if dependency["identity"]["profile_sha256"] != profile_sha256:
        raise RuntimeError("LAB E4 dependencies belong to another profile")
    valid_mask, valid_fov = _load_valid_fov(args.valid_fov_root, job, profile)

    input_document = job["input"]
    full_frame_count = int(input_document["segment_count"])
    if args.frame_limit < 0 or args.frame_limit > full_frame_count:
        raise RuntimeError("LAB E4 frame limit escapes the camera job")
    frame_count = args.frame_limit or full_frame_count
    frames_root = args.frames.resolve(strict=True)
    frame_paths = [frames_root / f"frame-{index:06d}.png" for index in range(1, frame_count + 1)]
    if not all(path.is_file() for path in frame_paths):
        raise RuntimeError("decoded LAB E4 frame set is incomplete")
    if len(list(frames_root.glob("frame-*.png"))) != frame_count:
        raise RuntimeError("decoded LAB E4 frame set contains unexpected files")
    timeline = input_document["timeline"]
    timestamps = _read_timeline(
        args.timeline.resolve(strict=True),
        frame_count,
        float(timeline["start_seconds"]),
        float(timeline["end_seconds"]),
    )

    output = args.output.resolve()
    if output.exists():
        raise RuntimeError("LAB E4 output must be absent")
    output.mkdir(mode=0o700, parents=True, exist_ok=False)
    masks_root = output / "semantic-masks"
    overlays_root = output / "overlay-frames"
    masks_root.mkdir(mode=0o700)
    overlays_root.mkdir(mode=0o700)
    _assert_disk_floor(output, args.free_bytes_floor, 0)

    if not torch.cuda.is_available():
        raise RuntimeError("CUDA is required for LAB E4")
    device = torch.device("cuda:0")
    processor, model, model_labels, target_lut, model_files = _load_model(
        profile,
        args.cache.resolve(strict=True),
        device,
    )
    target_names = {int(key): str(value) for key, value in profile["target_taxonomy"].items()}
    if set(target_names) != set(range(TARGET_CLASS_COUNT)):
        raise RuntimeError("LAB E4 target taxonomy changed")

    def infer(image: Any) -> tuple[Any, dict[str, float]]:
        processor_started = time.perf_counter()
        inputs = processor(images=Image.fromarray(image), return_tensors="pt")
        processor_ms = (time.perf_counter() - processor_started) * 1000.0
        torch.cuda.synchronize()
        transfer_started = time.perf_counter()
        inputs = {
            name: value.to(device) if isinstance(value, torch.Tensor) else value
            for name, value in inputs.items()
        }
        torch.cuda.synchronize()
        transfer_ms = (time.perf_counter() - transfer_started) * 1000.0
        forward_started = time.perf_counter()
        with torch.inference_mode(), torch.amp.autocast("cuda", dtype=torch.float16):
            outputs = model(**inputs)
        torch.cuda.synchronize()
        forward_ms = (time.perf_counter() - forward_started) * 1000.0
        post_started = time.perf_counter()
        semantic = processor.post_process_semantic_segmentation(
            outputs,
            target_sizes=[image.shape[:2]],
        )[0]
        semantic = semantic.detach().cpu().numpy().astype(np.uint8)
        post_ms = (time.perf_counter() - post_started) * 1000.0
        del inputs, outputs
        return semantic, {
            "processor_ms": processor_ms,
            "host_to_device_ms": transfer_ms,
            "forward_ms": forward_ms,
            "model_postprocess_ms": post_ms,
        }

    with Image.open(frame_paths[0]) as opened:
        warm_image = np.asarray(opened.convert("RGB"), dtype=np.uint8)
    if warm_image.shape != (600, 800, 3):
        raise RuntimeError("LAB E4 input resolution changed")
    warm_image = np.where(valid_mask[..., None], warm_image, 0).astype(np.uint8)
    warm_semantic, _warm_latency = infer(warm_image)
    del warm_semantic, _warm_latency

    latency = {
        name: []
        for name in (
            "image_decode_ms",
            "valid_fov_fill_ms",
            "processor_ms",
            "host_to_device_ms",
            "forward_ms",
            "model_postprocess_ms",
            "overlay_ms",
            "artifact_write_ms",
            "end_to_end_ms",
        )
    }
    total_pixels = Counter()
    metadata_path = output / "frames.jsonl"
    telemetry_path = output / "gpu-telemetry.jsonl"
    resource_before = _resource_snapshot()
    disk_before = shutil.disk_usage(output).free
    started = time.perf_counter()

    with (
        telemetry_path.open("x", encoding="utf-8", newline="\n") as telemetry_stream,
        metadata_path.open("x", encoding="utf-8", newline="\n") as metadata_stream,
        _GpuTelemetry(telemetry_stream, args.telemetry_interval_seconds) as telemetry,
    ):
        for frame_index, (path, session_seconds) in enumerate(
            zip(frame_paths, timestamps, strict=True)
        ):
            frame_started = time.perf_counter()
            decode_started = time.perf_counter()
            with Image.open(path) as opened:
                image = np.asarray(opened.convert("RGB"), dtype=np.uint8)
            latency["image_decode_ms"].append((time.perf_counter() - decode_started) * 1000.0)
            if image.shape != (600, 800, 3):
                raise RuntimeError("LAB E4 input resolution changed")

            fill_started = time.perf_counter()
            model_input = np.where(valid_mask[..., None], image, 0).astype(np.uint8)
            latency["valid_fov_fill_ms"].append((time.perf_counter() - fill_started) * 1000.0)
            semantic, measured = infer(model_input)
            if semantic.max() >= len(target_lut):
                raise RuntimeError("EoMT emitted an unknown category")
            target = target_lut[semantic]
            target = target.copy()
            target[~valid_mask] = 0
            if target.shape != valid_mask.shape or np.any(target[~valid_mask] != 0):
                raise RuntimeError("LAB E4 semantic mask escaped valid FOV")
            for name, value in measured.items():
                latency[name].append(value)

            overlay_started = time.perf_counter()
            overlay = _overlay(image, target)
            classes = _class_document(target, valid_mask, target_names)
            latency["overlay_ms"].append((time.perf_counter() - overlay_started) * 1000.0)
            counts = np.bincount(target[valid_mask], minlength=TARGET_CLASS_COUNT)
            for category_id in range(1, TARGET_CLASS_COUNT):
                total_pixels[target_names[category_id]] += int(counts[category_id])

            write_started = time.perf_counter()
            _write_png(masks_root / f"frame-{frame_index + 1:06d}.png", target)
            _write_png(overlays_root / f"frame-{frame_index + 1:06d}.png", overlay)
            metadata_stream.write(
                json.dumps(
                    {
                        "schema_version": FRAME_SCHEMA,
                        "frame_index": frame_index,
                        "sequence": frame_index + 1,
                        "session_seconds": round(session_seconds, 9),
                        "instances": [],
                        "semantic_classes": classes,
                    },
                    ensure_ascii=False,
                    sort_keys=True,
                    separators=(",", ":"),
                    allow_nan=False,
                )
                + "\n"
            )
            latency["artifact_write_ms"].append((time.perf_counter() - write_started) * 1000.0)
            latency["end_to_end_ms"].append((time.perf_counter() - frame_started) * 1000.0)

            completed = frame_index + 1
            if completed % 100 == 0 or completed == frame_count:
                metadata_stream.flush()
                telemetry_stream.flush()
                _assert_disk_floor(output, args.free_bytes_floor, completed)
                print(
                    json.dumps(
                        {
                            "phase": "semantic",
                            "frames_processed": completed,
                            "frames_total": frame_count,
                            "free_bytes": shutil.disk_usage(output).free,
                        },
                        sort_keys=True,
                    ),
                    flush=True,
                )
        metadata_stream.flush()
        os.fsync(metadata_stream.fileno())

    inference_elapsed = time.perf_counter() - started
    resource_after = _resource_snapshot()
    disk_after = shutil.disk_usage(output).free
    report = {
        "schema_version": REPORT_SCHEMA,
        "run_id": f"{job['job_id']}-e4-eomt-full-session-v1",
        "created_at_utc": datetime.now(UTC)
        .isoformat(timespec="milliseconds")
        .replace("+00:00", "Z"),
        "state": (
            "inference-complete-awaiting-publication"
            if frame_count == full_frame_count
            else "technical-pilot-complete-not-publishable"
        ),
        "ground_truth": False,
        "input": {
            "job_id": job["job_id"],
            "input_sha256": job["input_sha256"],
            "session_id": input_document["session_id"],
            "source_id": input_document["source_id"],
            "codec_epoch": input_document["codec_epoch"],
            "segment_count": full_frame_count,
            "frames_admitted": frame_count,
            "byte_length": input_document["byte_length"],
            "timeline_start_seconds": timeline["start_seconds"],
            "timeline_end_seconds": timeline["end_seconds"],
            "frame_timeline_sha256": _sha256(args.timeline.resolve(strict=True)),
        },
        "calibration": {
            "content_identity_sha256": profile["source"]["calibration_sha256"],
            "camera_slot": profile["source"]["calibration_slot"],
        },
        "configuration": {
            "pipeline": PIPELINE_ID,
            "semantic_alpha": SEMANTIC_ALPHA,
            "batch_size": 1,
            "precision": "fp16-autocast",
            "frame_policy": (
                "all-frames-no-sampling"
                if frame_count == full_frame_count
                else f"technical-pilot-first-{frame_count}-frames"
            ),
            "instance_branch": "disabled",
            "profile_sha256": profile_sha256,
            "dependency_identity_sha256": dependency["identity_sha256"],
            "valid_fov": valid_fov,
            "runner_sha256": _sha256(Path(__file__).resolve(strict=True)),
            "orchestrator_sha256": args.orchestrator_sha256,
            "container_image": args.container_image,
        },
        "models": {
            "semantic": {
                "id": profile["model"]["id"],
                "revision": profile["model"]["revision"],
                "architecture": profile["model"]["architecture"],
                "checkpoint_load": "exact-no-missing-unexpected-or-mismatched-keys",
                "runtime_labels": {
                    str(index): label for index, label in sorted(model_labels.items())
                },
            },
            "files": model_files,
        },
        "runtime": {
            "hostname": platform.node(),
            "platform": platform.platform(),
            "python": platform.python_version(),
            "torch": torch.__version__,
            "transformers": transformers.__version__,
            "cuda_runtime": torch.version.cuda,
            "gpu": torch.cuda.get_device_name(),
            "gpu_compute_capability": list(torch.cuda.get_device_capability()),
        },
        "metrics": {
            "frames_expected": frame_count,
            "frames_processed": frame_count,
            "frames_failed": 0,
            "frames_skipped": 0,
            "instances": 0,
            "inference_wall_seconds": round(inference_elapsed, 6),
            "inference_frames_per_second": round(frame_count / inference_elapsed, 6),
            "latency_ms": {name: _percentiles(values) for name, values in latency.items()},
            "semantic_pixel_totals_inside_valid_fov": dict(sorted(total_pixels.items())),
            "cuda_peak_memory_allocated_mib": round(
                torch.cuda.max_memory_allocated() / 2**20,
                3,
            ),
            "cuda_peak_memory_reserved_mib": round(
                torch.cuda.max_memory_reserved() / 2**20,
                3,
            ),
            "process_peak_rss_mib": round(
                resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024,
                3,
            ),
            "resource_delta": _resource_delta(resource_before, resource_after),
            "gpu_telemetry": telemetry.summary(),
            "disk": {
                "free_bytes_before_inference": disk_before,
                "free_bytes_after_inference": disk_after,
                "free_bytes_floor": args.free_bytes_floor,
            },
        },
        "versions": {
            name: importlib.metadata.version(name)
            for name in ("numpy", "pillow", "torch", "transformers")
        },
    }
    _write_json(output / "run-report.partial.json", report)
    print(
        json.dumps(
            {
                "state": report["state"],
                "frames": frame_count,
                "inference_seconds": round(inference_elapsed, 6),
            },
            sort_keys=True,
        ),
        flush=True,
    )
    return 0


def _finalize(args: argparse.Namespace) -> int:
    output = args.output.resolve(strict=True)
    video = args.video.resolve(strict=True)
    masks = args.masks.resolve(strict=True)
    if video.parent != output or masks.parent != output:
        raise RuntimeError("published LAB E4 artifacts must be direct result children")
    partial_path = output / "run-report.partial.json"
    frames_path = output / "frames.jsonl"
    telemetry_path = output / "gpu-telemetry.jsonl"
    partial = _read_object(partial_path)
    input_document = partial.get("input")
    metrics = partial.get("metrics")
    if (
        partial.get("schema_version") != REPORT_SCHEMA
        or partial.get("state") != "inference-complete-awaiting-publication"
        or not isinstance(input_document, dict)
        or not isinstance(metrics, dict)
        or input_document.get("frames_admitted") != input_document.get("segment_count")
        or metrics.get("frames_expected") != input_document.get("segment_count")
        or metrics.get("frames_processed") != input_document.get("segment_count")
    ):
        raise RuntimeError("only a complete LAB E4 camera epoch can be finalized")
    for value in (
        args.extract_seconds,
        args.encode_seconds,
        args.archive_seconds,
        args.wall_seconds,
    ):
        if value <= 0:
            raise RuntimeError("LAB E4 publication timing is invalid")
    disk_values = (
        args.disk_free_before_bytes,
        args.disk_free_post_extract_bytes,
        args.disk_free_post_inference_bytes,
        args.disk_free_post_artifacts_bytes,
        args.disk_floor_bytes,
        args.working_set_reserve_bytes,
    )
    if any(value < 0 for value in disk_values):
        raise RuntimeError("LAB E4 publication disk telemetry is invalid")
    if any(
        value < args.disk_floor_bytes
        for value in (
            args.disk_free_before_bytes,
            args.disk_free_post_extract_bytes,
            args.disk_free_post_inference_bytes,
            args.disk_free_post_artifacts_bytes,
        )
    ):
        raise RuntimeError("LAB E4 publication crossed its D: free-space floor")

    identity = {
        "schema_version": IDENTITY_SCHEMA,
        "job_id": input_document["job_id"],
        "input_sha256": input_document["input_sha256"],
        "calibration": partial["calibration"],
        "configuration": partial["configuration"],
        "models": partial["models"],
        "publication": {
            "video_encoder": args.encoder,
            "video_media_type": "video/mp4",
            "mask_archive_media_type": "application/gzip",
            "content": "semantic-overlay-and-semantic-masks",
        },
    }
    identity_sha256 = hashlib.sha256(_canonical_json(identity)).hexdigest()
    result_id = f"result-{identity_sha256}"
    final_report = {
        **partial,
        "state": "published",
        "result_id": result_id,
        "publication": {
            "extract_seconds": round(args.extract_seconds, 6),
            "encode_seconds": round(args.encode_seconds, 6),
            "archive_seconds": round(args.archive_seconds, 6),
            "wall_seconds": round(args.wall_seconds, 6),
            "end_to_end_frames_per_second": round(
                int(metrics["frames_processed"]) / args.wall_seconds,
                6,
            ),
            "encoder": args.encoder,
            "disk": {
                "free_bytes_before": args.disk_free_before_bytes,
                "free_bytes_post_extract": args.disk_free_post_extract_bytes,
                "free_bytes_post_inference": args.disk_free_post_inference_bytes,
                "free_bytes_post_artifacts": args.disk_free_post_artifacts_bytes,
                "free_bytes_floor": args.disk_floor_bytes,
                "working_set_reserve_bytes": args.working_set_reserve_bytes,
            },
        },
    }
    report_path = output / "run-report.json"
    _write_json(report_path, final_report)
    artifacts = [
        _artifact(video, "panoptic-overlay-video", "video/mp4"),
        _artifact(masks, "panoptic-mask-archive", "application/gzip"),
        _artifact(frames_path, "panoptic-frame-metadata", "application/x-ndjson", FRAME_SCHEMA),
        _artifact(telemetry_path, "worker-gpu-telemetry", "application/x-ndjson"),
        _artifact(report_path, "perception-run-report", "application/json", REPORT_SCHEMA),
    ]
    result = {
        "schema_version": RESULT_SCHEMA,
        "result_id": result_id,
        "identity_sha256": identity_sha256,
        "identity": identity,
        "created_at_utc": final_report["created_at_utc"],
        "job_id": input_document["job_id"],
        "input_sha256": input_document["input_sha256"],
        "session_id": input_document["session_id"],
        "source_id": input_document["source_id"],
        "codec_epoch": input_document["codec_epoch"],
        "timestamp_basis": "session-time-seconds",
        "timeline_start_seconds": input_document["timeline_start_seconds"],
        "timeline_end_seconds": input_document["timeline_end_seconds"],
        "frames_processed": metrics["frames_processed"],
        "ground_truth": False,
        "artifacts": artifacts,
    }
    _write_json(output / "result.json", result)
    partial_path.unlink()
    print(
        json.dumps(
            {"result_id": result_id, "identity_sha256": identity_sha256},
            sort_keys=True,
        ),
        flush=True,
    )
    return 0


def main() -> int:
    args = _arguments()
    if args.command == "preflight":
        return _preflight(args)
    if args.command == "run":
        return _run(args)
    return _finalize(args)


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