#!/usr/bin/env python3
"""Run the LAB E3 K1 KB4 multiview semantic-segmentation comparison."""

from __future__ import annotations

import argparse
import hashlib
import json
import math
import os
import platform
import resource
import subprocess
import sys
import time
import urllib.request
from collections import Counter
from datetime import UTC, datetime
from pathlib import Path, PurePosixPath
from typing import Any

from run_evaluation_prelabels import _load_valid_fov, _validate_pack
from run_recorded_perception_epoch import (
    _canonical_json,
    _GpuTelemetry,
    _palette,
    _percentiles,
    _sha256,
    _valid_sha256,
    _write_json,
)

PROFILE_SCHEMA = "missioncore.k1-e3-rectified-segmentation-profile/v1"
DEPENDENCY_SCHEMA = "missioncore.k1-e3-dependency-manifest/v1"
PRELABEL_SCHEMA = "missioncore.perception-evaluation-prelabels/v1"
PRELABEL_IDENTITY_SCHEMA = "missioncore.perception-evaluation-prelabels-identity/v1"
REPORT_SCHEMA = "missioncore.k1-e3-rectified-segmentation-report/v1"
RESULT_SCHEMA = "missioncore.k1-e3-rectified-segmentation-result/v1"
RESULT_IDENTITY_SCHEMA = "missioncore.k1-e3-rectified-segmentation-identity/v1"
EXPECTED_VARIANTS = (
    "eomt-fisheye-mask",
    "eomt-fisheye-mask-clahe",
    "eomt-kb4-cubemap5-clahe",
)
PREVIEW_COUNT = 16


def _valid_git_revision(value: object) -> bool:
    return (
        isinstance(value, str)
        and len(value) == 40
        and all(character in "0123456789abcdef" for character in value)
    )


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

    prepare = commands.add_parser("prepare")
    prepare.add_argument("--profile", type=Path, required=True)
    prepare.add_argument("--cache", type=Path, required=True)
    prepare.add_argument("--environment", type=Path, required=True)

    run = commands.add_parser("run")
    run.add_argument("--profile", type=Path, required=True)
    run.add_argument("--evaluation-pack", type=Path, required=True)
    run.add_argument("--e2-prelabels", type=Path, required=True)
    run.add_argument("--valid-fov-root", 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("--max-frames", type=int, default=0)
    run.add_argument("--telemetry-interval-seconds", type=float, default=1.0)
    return parser.parse_args()


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


def _profile(path: Path) -> tuple[dict[str, Any], str]:
    resolved = path.resolve(strict=True)
    profile = _read_object(resolved)
    source = profile.get("source")
    rectification = profile.get("rectification")
    contrast = profile.get("contrast")
    model = profile.get("model")
    opencv = profile.get("opencv")
    taxonomy = profile.get("target_taxonomy")
    mapping = profile.get("cityscapes_to_target")
    if (
        profile.get("schema_version") != PROFILE_SCHEMA
        or profile.get("profile_id")
        != "k1-camera1-kb4-cubemap5-eomt-cityscapes/v1"
        or tuple(profile.get("variants", ())) != EXPECTED_VARIANTS
        or not isinstance(source, dict)
        or source.get("source_id") != "sensor.camera.right"
        or source.get("calibration_slot") != "camera_1"
        or not _valid_sha256(source.get("calibration_sha256"))
        or source.get("resolution") != [800, 600]
        or not isinstance(rectification, dict)
        or rectification.get("projection") != "five-perspective-gnomonic/v1"
        or rectification.get("tile_selection")
        != "maximum-optical-axis-cosine/v1"
        or not isinstance(contrast, dict)
        or contrast.get("method") != "clahe-lab-luminance"
        or not isinstance(model, dict)
        or model.get("id") != "tue-mps/cityscapes_semantic_eomt_large_1024"
        or not _valid_git_revision(model.get("revision"))
        or not isinstance(opencv, dict)
        or opencv.get("distribution") != "opencv-python-headless"
        or opencv.get("runtime_version") != "4.13.0"
        or not isinstance(taxonomy, dict)
        or set(taxonomy) != {str(index) for index in range(16)}
        or not isinstance(mapping, dict)
        or set(mapping.values()) - set(range(1, 16))
    ):
        raise RuntimeError("LAB E3 profile is incompatible")
    intrinsic = source.get("intrinsic_fx_fy_cx_cy")
    distortion = source.get("distortion_kb4")
    tiles = rectification.get("tiles")
    if (
        not isinstance(intrinsic, list)
        or len(intrinsic) != 4
        or not all(type(value) in {int, float} for value in intrinsic)
        or not isinstance(distortion, list)
        or len(distortion) != 4
        or not all(type(value) in {int, float} for value in distortion)
        or not isinstance(tiles, list)
        or len(tiles) != 5
        or {tile.get("name") for tile in tiles if isinstance(tile, dict)}
        != {"front", "left", "right", "up", "down"}
    ):
        raise RuntimeError("LAB E3 KB4 geometry is invalid")
    return profile, _sha256(resolved)


def _safe_artifact(root: Path, encoded: object) -> Path:
    if not isinstance(encoded, str):
        raise RuntimeError("artifact path is not a string")
    relative = PurePosixPath(encoded)
    if relative.is_absolute() or ".." in relative.parts or not relative.parts:
        raise RuntimeError("artifact path is unsafe")
    path = root.joinpath(*relative.parts).resolve(strict=True)
    if not path.is_file() or not path.is_relative_to(root):
        raise RuntimeError("artifact path escapes its root")
    return path


def _verify_file(path: Path, descriptor: dict[str, Any], label: str) -> None:
    if (
        path.stat().st_size != descriptor.get("bytes")
        or not _valid_sha256(descriptor.get("sha256"))
        or _sha256(path) != descriptor["sha256"]
    ):
        raise RuntimeError(f"{label} identity changed")


def _download(url: str, destination: Path, descriptor: dict[str, Any]) -> None:
    if destination.exists():
        _verify_file(destination, descriptor, destination.name)
        return
    temporary = destination.with_suffix(destination.suffix + ".partial")
    if temporary.exists():
        temporary.unlink()
    with (
        urllib.request.urlopen(url, timeout=120) as response,  # noqa: S310
        temporary.open("xb") as stream,
    ):
        while chunk := response.read(1024 * 1024):
            stream.write(chunk)
    _verify_file(temporary, descriptor, destination.name)
    temporary.replace(destination)


def _model_snapshot(profile: dict[str, Any], cache: Path, *, offline: bool) -> Path:
    from huggingface_hub import snapshot_download

    model = profile["model"]
    return Path(
        snapshot_download(
            repo_id=model["id"],
            revision=model["revision"],
            cache_dir=cache / "huggingface",
            allow_patterns=tuple(model["files"]),
            local_files_only=offline,
        )
    )


def _verify_model_files(profile: dict[str, Any], snapshot: Path) -> list[dict[str, Any]]:
    records: list[dict[str, Any]] = []
    for name, descriptor in sorted(profile["model"]["files"].items()):
        path = snapshot / name
        if path.parent.resolve(strict=True) != snapshot.resolve(strict=True):
            raise RuntimeError("model file escaped the snapshot")
        _verify_file(path, descriptor, f"model file {name}")
        records.append(
            {
                "name": name,
                "bytes": path.stat().st_size,
                "sha256": _sha256(path),
            }
        )
    config = _read_object(snapshot / "config.json")
    labels = config.get("id2label")
    if (
        config.get("model_type") != "eomt"
        or config.get("architectures") != ["EomtForUniversalSegmentation"]
        or not isinstance(labels, dict)
        or set(labels.values()) != set(profile["cityscapes_to_target"])
    ):
        raise RuntimeError("EoMT checkpoint taxonomy changed")
    return records


def _dependency_manifest(environment: Path) -> dict[str, Any]:
    path = environment / "manifest.json"
    manifest = _read_object(path.resolve(strict=True))
    identity = manifest.get("identity")
    identity_sha256 = manifest.get("identity_sha256")
    if (
        manifest.get("schema_version") != DEPENDENCY_SCHEMA
        or not isinstance(identity, dict)
        or not _valid_sha256(identity_sha256)
        or hashlib.sha256(_canonical_json(identity)).hexdigest() != identity_sha256
    ):
        raise RuntimeError("LAB E3 dependency manifest is invalid")
    return manifest


def _prepare(args: argparse.Namespace) -> int:
    profile, profile_sha256 = _profile(args.profile)
    cache = args.cache.resolve(strict=True)
    environment = args.environment.resolve()
    environment.mkdir(mode=0o700, parents=True, exist_ok=True)
    packages = environment / "packages"
    wheels = environment / "wheels"
    packages.mkdir(mode=0o700, exist_ok=True)
    wheels.mkdir(mode=0o700, exist_ok=True)

    wheel = profile["opencv"]["wheel"]
    wheel_path = wheels / wheel["filename"]
    _download(wheel["url"], wheel_path, wheel)
    subprocess.run(
        [
            sys.executable,
            "-m",
            "pip",
            "install",
            "--disable-pip-version-check",
            "--no-deps",
            "--target",
            os.fspath(packages),
            os.fspath(wheel_path),
        ],
        check=True,
    )
    sys.path.insert(0, os.fspath(packages))
    import cv2
    import huggingface_hub
    import transformers

    if cv2.__version__ != profile["opencv"]["runtime_version"]:
        raise RuntimeError("OpenCV version differs from the LAB E3 profile")
    snapshot = _model_snapshot(profile, cache, offline=False)
    model_files = _verify_model_files(profile, snapshot)
    identity = {
        "schema_version": "missioncore.k1-e3-dependency-identity/v1",
        "profile_sha256": profile_sha256,
        "opencv": {
            "distribution": profile["opencv"]["distribution"],
            "distribution_version": profile["opencv"]["version"],
            "runtime_version": cv2.__version__,
            "wheel": {
                "filename": wheel_path.name,
                "bytes": wheel_path.stat().st_size,
                "sha256": _sha256(wheel_path),
            },
        },
        "model": {
            "id": profile["model"]["id"],
            "revision": profile["model"]["revision"],
            "files": model_files,
        },
        "python": platform.python_version(),
        "transformers": transformers.__version__,
        "huggingface_hub": huggingface_hub.__version__,
    }
    identity_sha256 = hashlib.sha256(_canonical_json(identity)).hexdigest()
    manifest = {
        "schema_version": DEPENDENCY_SCHEMA,
        "created_at_utc": datetime.now(UTC)
        .isoformat(timespec="milliseconds")
        .replace("+00:00", "Z"),
        "identity_sha256": identity_sha256,
        "identity": identity,
    }
    _write_json(environment / "manifest.json", manifest)
    print(
        json.dumps(
            {
                "state": "prepared",
                "dependency_identity_sha256": identity_sha256,
                "opencv": cv2.__version__,
                "model_revision": profile["model"]["revision"],
            },
            sort_keys=True,
        ),
        flush=True,
    )
    return 0


def _prelabels(
    root: Path,
    pack: dict[str, Any],
) -> tuple[dict[str, Any], list[Path], str]:
    resolved = root.resolve(strict=True)
    result = _read_object(resolved / "result.json")
    identity = result.get("identity")
    identity_sha256 = result.get("identity_sha256")
    observed_identity_sha256 = (
        hashlib.sha256(_canonical_json(identity)).hexdigest()
        if isinstance(identity, dict)
        else ""
    )
    if (
        result.get("schema_version") != PRELABEL_SCHEMA
        or not isinstance(identity, dict)
        or identity.get("schema_version") != PRELABEL_IDENTITY_SCHEMA
        or not _valid_sha256(identity_sha256)
        or result.get("result_id") != f"evaluation-prelabels-{identity_sha256}"
        or identity.get("evaluation_pack_id") != pack["generation_id"]
        or identity.get("evaluation_identity_sha256") != pack["identity_sha256"]
    ):
        raise RuntimeError("LAB E2 prelabels are not bound to the evaluation pack")
    artifacts = result.get("artifacts")
    if not isinstance(artifacts, list):
        raise RuntimeError("LAB E2 prelabel artifact list is invalid")
    descriptors = {
        artifact.get("path"): artifact
        for artifact in artifacts
        if isinstance(artifact, dict) and isinstance(artifact.get("path"), str)
    }
    paths: list[Path] = []
    for image_id in range(1, 65):
        encoded = f"semantic-prelabels/image-{image_id:03d}.png"
        descriptor = descriptors.get(encoded)
        if not isinstance(descriptor, dict):
            raise RuntimeError(f"LAB E2 semantic artifact is missing: {encoded}")
        path = _safe_artifact(resolved, encoded)
        if (
            path.stat().st_size != descriptor.get("byte_length")
            or not _valid_sha256(descriptor.get("sha256"))
            or _sha256(path) != descriptor["sha256"]
        ):
            raise RuntimeError(f"LAB E2 semantic artifact changed: {encoded}")
        paths.append(path)
    return result, paths, observed_identity_sha256


def _rotation_tile_to_camera(yaw_degrees: float, pitch_degrees: float) -> Any:
    import numpy as np

    yaw = math.radians(yaw_degrees)
    pitch = math.radians(pitch_degrees)
    yaw_matrix = np.asarray(
        [
            [math.cos(yaw), 0.0, math.sin(yaw)],
            [0.0, 1.0, 0.0],
            [-math.sin(yaw), 0.0, math.cos(yaw)],
        ],
        dtype=np.float64,
    )
    pitch_matrix = np.asarray(
        [
            [1.0, 0.0, 0.0],
            [0.0, math.cos(pitch), -math.sin(pitch)],
            [0.0, math.sin(pitch), math.cos(pitch)],
        ],
        dtype=np.float64,
    )
    return yaw_matrix @ pitch_matrix


def _invert_kb4(theta_distorted: Any, coefficients: Any) -> Any:
    import numpy as np

    theta = np.asarray(theta_distorted, dtype=np.float64).copy()
    k1, k2, k3, k4 = coefficients
    for _ in range(12):
        squared = theta * theta
        polynomial = (
            1.0
            + k1 * squared
            + k2 * squared**2
            + k3 * squared**3
            + k4 * squared**4
        )
        derivative = (
            1.0
            + 3.0 * k1 * squared
            + 5.0 * k2 * squared**2
            + 7.0 * k3 * squared**3
            + 9.0 * k4 * squared**4
        )
        if np.any(np.abs(derivative) < 1e-9):
            raise RuntimeError("KB4 inverse derivative became singular")
        theta -= (theta * polynomial - theta_distorted) / derivative
    if not np.isfinite(theta).all() or np.any(theta < 0.0):
        raise RuntimeError("KB4 inverse produced invalid angles")
    return theta


def _raw_camera_directions(profile: dict[str, Any], valid_mask: Any) -> Any:
    import numpy as np

    width, height = profile["source"]["resolution"]
    fx, fy, cx, cy = profile["source"]["intrinsic_fx_fy_cx_cy"]
    coefficients = np.asarray(profile["source"]["distortion_kb4"], dtype=np.float64)
    y, x = np.mgrid[:height, :width]
    distorted_x = (x - cx) / fx
    distorted_y = (y - cy) / fy
    theta_distorted = np.hypot(distorted_x, distorted_y)
    theta = np.zeros_like(theta_distorted)
    theta[valid_mask] = _invert_kb4(theta_distorted[valid_mask], coefficients)
    scale = np.divide(
        np.sin(theta),
        theta_distorted,
        out=np.ones_like(theta),
        where=theta_distorted > 1e-12,
    )
    return np.stack(
        (
            distorted_x * scale,
            distorted_y * scale,
            np.cos(theta),
        ),
        axis=-1,
    )


def _project_camera_to_raw(directions: Any, profile: dict[str, Any]) -> tuple[Any, Any]:
    import numpy as np

    fx, fy, cx, cy = profile["source"]["intrinsic_fx_fy_cx_cy"]
    k1, k2, k3, k4 = profile["source"]["distortion_kb4"]
    x = directions[..., 0]
    y = directions[..., 1]
    z = directions[..., 2]
    radial = np.hypot(x, y)
    theta = np.arctan2(radial, z)
    squared = theta * theta
    theta_distorted = theta * (
        1.0
        + k1 * squared
        + k2 * squared**2
        + k3 * squared**3
        + k4 * squared**4
    )
    scale = np.divide(
        theta_distorted,
        radial,
        out=np.ones_like(theta_distorted),
        where=radial > 1e-12,
    )
    return (fx * x * scale + cx).astype(np.float32), (
        fy * y * scale + cy
    ).astype(np.float32)


def _rectification_maps(profile: dict[str, Any], valid_mask: Any) -> dict[str, Any]:
    import numpy as np

    rectification = profile["rectification"]
    size = int(rectification["tile_size"])
    horizontal_fov = float(rectification["horizontal_fov_degrees"])
    vertical_fov = float(rectification["vertical_fov_degrees"])
    center = (size - 1) / 2.0
    fx = (size / 2.0) / math.tan(math.radians(horizontal_fov) / 2.0)
    fy = (size / 2.0) / math.tan(math.radians(vertical_fov) / 2.0)
    y, x = np.mgrid[:size, :size]
    local = np.stack(
        ((x - center) / fx, (y - center) / fy, np.ones_like(x)),
        axis=-1,
    ).astype(np.float64)
    local /= np.linalg.norm(local, axis=-1, keepdims=True)

    raw_directions = _raw_camera_directions(profile, valid_mask)
    best_score = np.full(valid_mask.shape, -np.inf, dtype=np.float64)
    selected_tile = np.full(valid_mask.shape, -1, dtype=np.int8)
    tile_maps: list[dict[str, Any]] = []
    overlap = np.zeros(valid_mask.shape, dtype=np.uint8)
    for tile_index, tile in enumerate(rectification["tiles"]):
        rotation = _rotation_tile_to_camera(
            float(tile["yaw_degrees"]),
            float(tile["pitch_degrees"]),
        )
        camera_directions = local @ rotation.T
        map_x, map_y = _project_camera_to_raw(camera_directions, profile)

        raw_to_tile = raw_directions @ rotation
        tile_z = raw_to_tile[..., 2]
        with np.errstate(divide="ignore", invalid="ignore"):
            raw_map_x = fx * raw_to_tile[..., 0] / tile_z + center
            raw_map_y = fy * raw_to_tile[..., 1] / tile_z + center
        admitted = (
            valid_mask
            & (tile_z > 0.0)
            & np.isfinite(raw_map_x)
            & np.isfinite(raw_map_y)
            & (raw_map_x >= 0.0)
            & (raw_map_x <= size - 1)
            & (raw_map_y >= 0.0)
            & (raw_map_y <= size - 1)
        )
        overlap += admitted
        better = admitted & (tile_z > best_score)
        selected_tile[better] = tile_index
        best_score[better] = tile_z[better]
        tile_maps.append(
            {
                "name": tile["name"],
                "raw_map_x": map_x,
                "raw_map_y": map_y,
                "tile_map_x": raw_map_x.astype(np.float32),
                "tile_map_y": raw_map_y.astype(np.float32),
            }
        )
    uncovered = valid_mask & (selected_tile < 0)
    if np.any(uncovered):
        raise RuntimeError(
            f"KB4 multiview leaves {int(np.count_nonzero(uncovered))} valid pixels uncovered"
        )
    valid_count = int(np.count_nonzero(valid_mask))
    return {
        "tiles": tile_maps,
        "selected_tile": selected_tile,
        "coverage": {
            "valid_pixel_count": valid_count,
            "covered_pixel_count": int(np.count_nonzero(valid_mask & (selected_tile >= 0))),
            "coverage_fraction": 1.0,
            "overlap_count": {
                "min": int(overlap[valid_mask].min()),
                "max": int(overlap[valid_mask].max()),
                "mean": round(float(overlap[valid_mask].mean()), 9),
            },
        },
    }


def _clahe(image: Any, profile: dict[str, Any], cv2: Any) -> Any:
    contrast = profile["contrast"]
    lab = cv2.cvtColor(image, cv2.COLOR_RGB2LAB)
    luminance, a, b = cv2.split(lab)
    clahe = cv2.createCLAHE(
        clipLimit=float(contrast["clip_limit"]),
        tileGridSize=tuple(int(value) for value in contrast["tile_grid_size"]),
    )
    return cv2.cvtColor(cv2.merge((clahe.apply(luminance), a, b)), cv2.COLOR_LAB2RGB)


def _fuse_tiles(tile_semantics: list[Any], maps: dict[str, Any], valid_mask: Any) -> Any:
    import numpy as np

    selected = maps["selected_tile"]
    result = np.zeros(valid_mask.shape, dtype=np.uint8)
    for tile_index, (semantic, tile_map) in enumerate(
        zip(tile_semantics, maps["tiles"], strict=True)
    ):
        admitted = valid_mask & (selected == tile_index)
        x = np.rint(tile_map["tile_map_x"][admitted]).astype(np.int64)
        y = np.rint(tile_map["tile_map_y"][admitted]).astype(np.int64)
        x = np.clip(x, 0, semantic.shape[1] - 1)
        y = np.clip(y, 0, semantic.shape[0] - 1)
        result[admitted] = semantic[y, x]
    return result


def _resource_snapshot() -> dict[str, float]:
    usage = resource.getrusage(resource.RUSAGE_SELF)
    result = {
        "user_cpu_seconds": float(usage.ru_utime),
        "system_cpu_seconds": float(usage.ru_stime),
        "minor_page_faults": float(usage.ru_minflt),
        "major_page_faults": float(usage.ru_majflt),
        "voluntary_context_switches": float(usage.ru_nvcsw),
        "involuntary_context_switches": float(usage.ru_nivcsw),
    }
    try:
        for line in Path("/proc/self/io").read_text(encoding="ascii").splitlines():
            name, value = line.split(":", 1)
            if name in {"read_bytes", "write_bytes", "rchar", "wchar"}:
                result[f"proc_io_{name}"] = float(value.strip())
    except (OSError, UnicodeDecodeError, ValueError):
        pass
    return result


def _resource_delta(before: dict[str, float], after: dict[str, float]) -> dict[str, float]:
    return {
        name: round(value - before[name], 6)
        for name, value in after.items()
        if name in before
    }


def _latency_state() -> dict[str, list[float]]:
    return {
        "image_preprocess_ms": [],
        "processor_ms": [],
        "host_to_device_ms": [],
        "forward_ms": [],
        "model_postprocess_ms": [],
        "fusion_ms": [],
        "end_to_end_ms": [],
        "tile_forward_ms": [],
    }


def _latency_document(state: dict[str, list[float]]) -> dict[str, Any]:
    return {name: _percentiles(values) for name, values in state.items()}


def _preview_indices(frame_count: int) -> set[int]:
    admitted = min(PREVIEW_COUNT, frame_count)
    if admitted == 1:
        return {0}
    return {
        (position * (frame_count - 1) + (admitted - 1) // 2) // (admitted - 1)
        for position in range(admitted)
    }


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

    colors = np.zeros_like(image)
    for category_id in range(1, 16):
        colors[semantic == category_id] = _palette(category_id)
    return np.where(
        (semantic > 0)[..., None],
        np.rint(image.astype(np.float32) * 0.52 + colors.astype(np.float32) * 0.48),
        image,
    ).astype(np.uint8)


def _preview(
    image: Any,
    variants: dict[str, Any],
    e2_semantic: Any,
    *,
    image_id: int,
) -> Any:
    from PIL import Image, ImageDraw

    panels = [
        ("raw", image),
        ("E2 BEiT draft", _overlay(image, e2_semantic)),
        ("EoMT fisheye", _overlay(image, variants[EXPECTED_VARIANTS[0]])),
        ("EoMT fisheye + CLAHE", _overlay(image, variants[EXPECTED_VARIANTS[1]])),
        ("EoMT KB4 cubemap5 + CLAHE", _overlay(image, variants[EXPECTED_VARIANTS[2]])),
    ]
    width = 400
    height = 300
    header = 28
    canvas = Image.new("RGB", (width * len(panels), height + header), "black")
    draw = ImageDraw.Draw(canvas)
    for index, (label, panel) in enumerate(panels):
        resized = Image.fromarray(panel).resize((width, height), Image.Resampling.LANCZOS)
        canvas.paste(resized, (index * width, header))
        draw.text((index * width + 6, 7), label, fill="white")
    draw.text((width * len(panels) - 120, 7), f"image {image_id:03d}", fill="white")
    return canvas


def _atlas(image: Any, maps: dict[str, Any], profile: dict[str, Any], cv2: Any) -> Any:
    from PIL import Image, ImageDraw

    tiles = []
    for tile_map in maps["tiles"]:
        tile = cv2.remap(
            image,
            tile_map["raw_map_x"],
            tile_map["raw_map_y"],
            interpolation=cv2.INTER_LINEAR,
            borderMode=cv2.BORDER_CONSTANT,
        )
        tiles.append((tile_map["name"], _clahe(tile, profile, cv2)))
    panel = 320
    header = 28
    canvas = Image.new("RGB", (panel * 3, (panel + header) * 2), "black")
    draw = ImageDraw.Draw(canvas)
    for index, (name, tile) in enumerate(tiles):
        column = index % 3
        row = index // 3
        resized = Image.fromarray(tile).resize((panel, panel), Image.Resampling.LANCZOS)
        x = column * panel
        y = row * (panel + header)
        canvas.paste(resized, (x, y + header))
        draw.text((x + 6, y + 7), name, fill="white")
    return canvas


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

    profile, profile_sha256 = _profile(args.profile)
    dependency = _dependency_manifest(args.environment.resolve(strict=True))
    if dependency["identity"]["profile_sha256"] != profile_sha256:
        raise RuntimeError("LAB E3 dependencies belong to another profile")
    sys.path.insert(0, os.fspath(args.environment.resolve(strict=True) / "packages"))
    import cv2
    import torch
    import transformers
    from transformers import AutoImageProcessor, EomtForUniversalSegmentation

    if cv2.__version__ != profile["opencv"]["runtime_version"]:
        raise RuntimeError("LAB E3 OpenCV runtime changed")
    if not torch.cuda.is_available():
        raise RuntimeError("CUDA is required for LAB E3")

    pack_root = args.evaluation_pack.resolve(strict=True)
    pack, all_frames = _validate_pack(pack_root)
    source = profile["source"]
    pack_identity = pack["identity"]
    if (
        pack_identity.get("source_id") != source["source_id"]
        or pack_identity.get("calibration_slot") != source["calibration_slot"]
        or pack_identity.get("calibration_sha256") != source["calibration_sha256"]
        or pack_identity.get("resolution") != source["resolution"]
    ):
        raise RuntimeError("LAB E3 profile does not match the evaluation pack")
    valid_mask = _load_valid_fov(args.valid_fov_root, pack)
    e2_result, all_e2_paths, e2_observed_identity_sha256 = _prelabels(
        args.e2_prelabels,
        pack,
    )

    if args.max_frames < 0 or args.max_frames > len(all_frames):
        raise RuntimeError("--max-frames escapes the evaluation pack")
    frame_count = args.max_frames or len(all_frames)
    frames = all_frames[:frame_count]
    e2_paths = all_e2_paths[:frame_count]
    output = args.output.resolve()
    if output.exists():
        raise RuntimeError("LAB E3 output must be absent")
    output.mkdir(mode=0o700, parents=True, exist_ok=False)
    masks_root = output / "semantic-masks"
    previews_root = output / "previews"
    masks_root.mkdir(mode=0o700)
    previews_root.mkdir(mode=0o700)
    for variant in EXPECTED_VARIANTS:
        (masks_root / variant).mkdir(mode=0o700)

    maps = _rectification_maps(profile, valid_mask)
    cache = args.cache.resolve(strict=True)
    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,
    )
    load_problems = {
        name: loading.get(name, [])
        for name in ("missing_keys", "unexpected_keys", "mismatched_keys", "error_msgs")
        if loading.get(name)
    }
    if load_problems:
        raise RuntimeError("EoMT checkpoint did not load exactly: " + json.dumps(load_problems))
    device = torch.device("cuda:0")
    model = model.to(device=device, dtype=torch.float16).eval()
    model_labels = {int(key): str(value) for key, value in model.config.id2label.items()}
    mapping = profile["cityscapes_to_target"]
    if set(model_labels.values()) != set(mapping):
        raise RuntimeError("EoMT runtime taxonomy changed")
    target_lut = np.asarray([mapping[model_labels[index]] for index in range(19)], dtype=np.uint8)

    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
        torch.cuda.synchronize()
        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)
        torch.cuda.synchronize()
        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,
        }

    first_name = f"image-{frames[0]['image_id']:03d}-frame-{frames[0]['frame_index']:06d}.png"
    with Image.open(pack_root / "images" / "valid-fov-fill" / first_name) as opened:
        warm_image = np.asarray(opened.convert("RGB"), dtype=np.uint8)
    _warm_semantic, _warm_latency = infer(warm_image)
    del _warm_semantic, _warm_latency

    target_names = {int(key): str(value) for key, value in profile["target_taxonomy"].items()}
    latency = {variant: _latency_state() for variant in EXPECTED_VARIANTS}
    pixel_counts = {variant: Counter() for variant in EXPECTED_VARIANTS}
    disagreement_e2 = {variant: [] for variant in EXPECTED_VARIANTS}
    disagreement_pair = []
    temporal_change = {variant: [] for variant in EXPECTED_VARIANTS}
    previous_temporal: dict[str, tuple[str, Any] | None] = {
        variant: None for variant in EXPECTED_VARIANTS
    }
    preview_indices = _preview_indices(frame_count)
    artifacts: list[dict[str, Any]] = []
    telemetry_path = output / "gpu-telemetry.jsonl"
    resource_before = _resource_snapshot()
    wall_started = time.perf_counter()

    with telemetry_path.open("x", encoding="utf-8", newline="\n") as telemetry_stream:
        with _GpuTelemetry(telemetry_stream, args.telemetry_interval_seconds) as telemetry:
            for order, (frame, e2_path) in enumerate(
                zip(frames, e2_paths, strict=True),
                start=1,
            ):
                name = (
                    f"image-{frame['image_id']:03d}-frame-{frame['frame_index']:06d}.png"
                )
                decode_started = time.perf_counter()
                with Image.open(pack_root / "images" / "valid-fov-fill" / name) as opened:
                    image = np.asarray(opened.convert("RGB"), dtype=np.uint8)
                with Image.open(e2_path) as opened:
                    e2_semantic = np.asarray(opened.convert("L"), dtype=np.uint8)
                decode_ms = (time.perf_counter() - decode_started) * 1000.0
                if image.shape != (600, 800, 3) or e2_semantic.shape != valid_mask.shape:
                    raise RuntimeError("LAB E3 input image shape changed")
                semantic_by_variant: dict[str, Any] = {}

                frame_started = time.perf_counter()
                semantic, measured = infer(image)
                target = target_lut[semantic]
                target = target.copy()
                target[~valid_mask] = 0
                semantic_by_variant[EXPECTED_VARIANTS[0]] = target
                state = latency[EXPECTED_VARIANTS[0]]
                state["image_preprocess_ms"].append(decode_ms)
                for key, value in measured.items():
                    state[key].append(value)
                state["fusion_ms"].append(0.0)
                state["end_to_end_ms"].append((time.perf_counter() - frame_started) * 1000.0)

                frame_started = time.perf_counter()
                preprocess_started = time.perf_counter()
                clahe_image = _clahe(image, profile, cv2)
                preprocess_ms = (time.perf_counter() - preprocess_started) * 1000.0
                semantic, measured = infer(clahe_image)
                target = target_lut[semantic]
                target = target.copy()
                target[~valid_mask] = 0
                semantic_by_variant[EXPECTED_VARIANTS[1]] = target
                state = latency[EXPECTED_VARIANTS[1]]
                state["image_preprocess_ms"].append(decode_ms + preprocess_ms)
                for key, value in measured.items():
                    state[key].append(value)
                state["fusion_ms"].append(0.0)
                state["end_to_end_ms"].append((time.perf_counter() - frame_started) * 1000.0)

                frame_started = time.perf_counter()
                preprocess_started = time.perf_counter()
                tiles = [
                    _clahe(
                        cv2.remap(
                            image,
                            tile_map["raw_map_x"],
                            tile_map["raw_map_y"],
                            interpolation=cv2.INTER_LINEAR,
                            borderMode=cv2.BORDER_CONSTANT,
                        ),
                        profile,
                        cv2,
                    )
                    for tile_map in maps["tiles"]
                ]
                preprocess_ms = (time.perf_counter() - preprocess_started) * 1000.0
                tile_semantics = []
                aggregate = Counter()
                tile_forward = []
                for tile in tiles:
                    semantic, measured = infer(tile)
                    tile_semantics.append(target_lut[semantic])
                    tile_forward.append(measured["forward_ms"])
                    aggregate.update(measured)
                fusion_started = time.perf_counter()
                target = _fuse_tiles(tile_semantics, maps, valid_mask)
                fusion_ms = (time.perf_counter() - fusion_started) * 1000.0
                semantic_by_variant[EXPECTED_VARIANTS[2]] = target
                state = latency[EXPECTED_VARIANTS[2]]
                state["image_preprocess_ms"].append(decode_ms + preprocess_ms)
                for key in (
                    "processor_ms",
                    "host_to_device_ms",
                    "forward_ms",
                    "model_postprocess_ms",
                ):
                    state[key].append(float(aggregate[key]))
                state["fusion_ms"].append(fusion_ms)
                state["tile_forward_ms"].extend(tile_forward)
                state["end_to_end_ms"].append((time.perf_counter() - frame_started) * 1000.0)

                for variant, target in semantic_by_variant.items():
                    labels, counts = np.unique(target[valid_mask], return_counts=True)
                    for label_id, count in zip(labels, counts, strict=True):
                        pixel_counts[variant][target_names[int(label_id)]] += int(count)
                    disagreement_e2[variant].append(
                        float(np.mean(target[valid_mask] != e2_semantic[valid_mask]))
                    )
                    encoded = f"semantic-masks/{variant}/image-{order:03d}.png"
                    path = output / encoded
                    Image.fromarray(target, mode="L").save(path, format="PNG", optimize=True)
                    artifacts.append(
                        {
                            "path": encoded,
                            "bytes": path.stat().st_size,
                            "sha256": _sha256(path),
                        }
                    )
                    if frame.get("role") == "temporal":
                        previous = previous_temporal[variant]
                        if previous is not None and previous[0] == frame.get("group_id"):
                            temporal_change[variant].append(
                                float(np.mean(previous[1][valid_mask] != target[valid_mask]))
                            )
                        previous_temporal[variant] = (str(frame.get("group_id")), target.copy())
                    else:
                        previous_temporal[variant] = None
                disagreement_pair.append(
                    float(
                        np.mean(
                            semantic_by_variant[EXPECTED_VARIANTS[0]][valid_mask]
                            != semantic_by_variant[EXPECTED_VARIANTS[2]][valid_mask]
                        )
                    )
                )

                if order - 1 in preview_indices:
                    preview_path = previews_root / f"image-{order:03d}.png"
                    _preview(
                        image,
                        semantic_by_variant,
                        e2_semantic,
                        image_id=int(frame["image_id"]),
                    ).save(preview_path, format="PNG", optimize=True)
                    artifacts.append(
                        {
                            "path": preview_path.relative_to(output).as_posix(),
                            "bytes": preview_path.stat().st_size,
                            "sha256": _sha256(preview_path),
                        }
                    )
                if order == 1:
                    atlas_path = output / "rectification-atlas.png"
                    _atlas(image, maps, profile, cv2).save(
                        atlas_path,
                        format="PNG",
                        optimize=True,
                    )
                    artifacts.append(
                        {
                            "path": atlas_path.name,
                            "bytes": atlas_path.stat().st_size,
                            "sha256": _sha256(atlas_path),
                        }
                    )
                if order % 4 == 0 or order == frame_count:
                    print(
                        json.dumps(
                            {
                                "phase": "e3-segmentation",
                                "processed": order,
                                "total": frame_count,
                            },
                            sort_keys=True,
                        ),
                        flush=True,
                    )
        telemetry_summary = telemetry.summary()

    wall_seconds = time.perf_counter() - wall_started
    resource_after = _resource_snapshot()
    identity = {
        "schema_version": RESULT_IDENTITY_SCHEMA,
        "evaluation_pack_id": pack["generation_id"],
        "evaluation_identity_sha256": pack["identity_sha256"],
        "e2_prelabel_result_id": e2_result["result_id"],
        "e2_prelabel_declared_identity_sha256": e2_result["identity_sha256"],
        "e2_prelabel_observed_identity_sha256": e2_observed_identity_sha256,
        "e2_prelabel_identity_consistent": (
            e2_result["identity_sha256"] == e2_observed_identity_sha256
        ),
        "profile_id": profile["profile_id"],
        "profile_sha256": profile_sha256,
        "dependency_identity_sha256": dependency["identity_sha256"],
        "source_id": source["source_id"],
        "calibration_slot": source["calibration_slot"],
        "calibration_sha256": source["calibration_sha256"],
        "frame_count": frame_count,
        "image_ids": [int(frame["image_id"]) for frame in frames],
        "variants": list(EXPECTED_VARIANTS),
        "execution": {
            "precision": profile["model"]["precision"],
            "batch_size": profile["model"]["batch_size"],
            "tile_execution": "sequential-five-views-per-frame",
            "runner_sha256": _sha256(Path(__file__).resolve(strict=True)),
        },
        "model": {
            "id": profile["model"]["id"],
            "revision": profile["model"]["revision"],
            "files": model_files,
        },
    }
    identity_sha256 = hashlib.sha256(_canonical_json(identity)).hexdigest()
    result_id = f"e3-segmentation-{identity_sha256}"
    report = {
        "schema_version": REPORT_SCHEMA,
        "result_id": result_id,
        "created_at_utc": datetime.now(UTC)
        .isoformat(timespec="milliseconds")
        .replace("+00:00", "Z"),
        "state": "completed-unreviewed-model-draft",
        "identity": identity,
        "rectification": maps["coverage"],
        "metrics": {
            variant: {
                "frames": frame_count,
                "latency_ms": _latency_document(latency[variant]),
                "semantic_pixels_inside_valid_fov": dict(pixel_counts[variant].most_common()),
                "disagreement_with_e2_draft_inside_valid_fov": _percentiles(
                    disagreement_e2[variant]
                ),
                "temporal_change_inside_valid_fov": _percentiles(temporal_change[variant]),
            }
            for variant in EXPECTED_VARIANTS
        },
        "pairwise_proxy": {
            "fisheye_vs_kb4_cubemap5_disagreement_inside_valid_fov": _percentiles(
                disagreement_pair
            )
        },
        "runtime": {
            "wall_seconds": round(wall_seconds, 6),
            "semantic_model_evaluations": frame_count * 7,
            "gpu": torch.cuda.get_device_name(),
            "gpu_compute_capability": list(torch.cuda.get_device_capability()),
            "torch": torch.__version__,
            "transformers": transformers.__version__,
            "opencv": cv2.__version__,
            "cuda_runtime": torch.version.cuda,
            "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,
        },
        "quality_status": {
            "ground_truth": False,
            "decision_scope": "preprocessing/model proxy comparison only",
            "next_gate": "two-pass CVAT review and reviewed export",
            "upstream_warnings": (
                []
                if identity["e2_prelabel_identity_consistent"]
                else [
                    "LAB E2 declared identity hash differs from the recomputed canonical hash; "
                    "pack binding and every consumed semantic artifact were independently verified"
                ]
            ),
            "not_accepted": [
                "mIoU",
                "AP",
                "distance accuracy",
                "3D geometry",
                "tracking",
                "safety",
            ],
        },
    }
    _write_json(output / "run-report.json", report)
    artifacts.extend(
        [
            {
                "path": "gpu-telemetry.jsonl",
                "bytes": telemetry_path.stat().st_size,
                "sha256": _sha256(telemetry_path),
            },
            {
                "path": "run-report.json",
                "bytes": (output / "run-report.json").stat().st_size,
                "sha256": _sha256(output / "run-report.json"),
            },
        ]
    )
    result = {
        "schema_version": RESULT_SCHEMA,
        "result_id": result_id,
        "identity_sha256": identity_sha256,
        "identity": identity,
        "ground_truth": False,
        "artifacts": sorted(artifacts, key=lambda item: item["path"]),
    }
    _write_json(output / "result.json", result)
    print(
        json.dumps(
            {
                "state": "completed-unreviewed-model-draft",
                "result_id": result_id,
                "frames": frame_count,
                "wall_seconds": round(wall_seconds, 6),
                "ground_truth": False,
            },
            sort_keys=True,
        ),
        flush=True,
    )
    return 0


def main() -> int:
    args = _arguments()
    if args.command == "prepare":
        return _prepare(args)
    if args.command == "run":
        return _run(args)
    raise AssertionError(args.command)


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