#!/usr/bin/env python3
"""Lower one exact BeamNG configuration into deterministic HELIX vehicle sidecars.

This is intentionally a source compiler, not a BeamNG runtime.  Literal JBeam
values are retained where the HELIX v2 contract has an equivalent; every
fallback and unsupported feature is emitted in the provenance ledger.
"""
from __future__ import annotations

import argparse
import hashlib
import json
import math
import re
import stat
import sys
import uuid
from pathlib import Path
from typing import Any, Callable, Iterable

from beamng_jbeam import (JBeamDocumentCache, MAX_SELECTED_PART_INDEX_BYTES,
                          SELECTED_PART_INDEX_SCHEMA, BRAKE_AXLE_PATTERN,
                          build_part_catalog, bounded_asset_paths,
                          decode_jbeam_table, pressure_wheel_options,
                          resolve_part_closure, selected_part_axle)
from beamng_expression import ExpressionResolution, resolve_beamng_expression
from beamng_abs import lower_selected_abs
from beamng_engine import derive_cylinders
from beamng_audio import (AudioExtractionError, AudioUnavailable, extract_engine_bank, locate_ffmpeg,
                          resolve_layers, stock_reason)

SCHEMA = "helix.beamng-functional-lowering/3"
SOURCE_SCHEMA = "helix.beamng-vehicle-source/1"
AUDIO_SLOTS = [
    "engineLadder", "exhaustLadder", "idle", "startup", "shutdown", "shiftUp", "shiftDown", "clutch",
    "transmissionWhine", "turboSpool", "blowOff", "intake", "revLimiter", "backfire", "suspension",
    "impactLight", "impactMedium", "impactHeavy", "reverseBeep", "horn", "doorOpen", "doorClose",
]

# BeamNG slot types are namespaced by vehicle and frequently carry axle, side,
# or engine-variant qualifiers. Reduce only those structural qualifiers, then
# perform an exact lookup. In particular, never classify by substring:
# ``flywheel`` is not a road wheel, and unknown source slots are not body kits.
ADDON_SLOT_TYPES = {
    "ecu": "vehicle.ecu@1",
    "intake": "vehicle.induction@1",
    "turbo": "vehicle.induction@1",
    "supercharger": "vehicle.induction@1",
    "engine": "vehicle.engine@1",
    "engine_internals": "vehicle.engine@1",
    "transaxle": "vehicle.transmission@1",
    "transmission": "vehicle.transmission@1",
    "gearbox": "vehicle.transmission@1",
    "flywheel": "vehicle.transmission@1",
    "gear_ratio": "vehicle.transmission@1",
    "shifter": "vehicle.transmission@1",
    "differential": "vehicle.driveline@1",
    "finaldrive": "vehicle.driveline@1",
    "driveshaft": "vehicle.driveline@1",
    "halfshafts": "vehicle.driveline@1",
    "transfer_case": "vehicle.driveline@1",
    "brake": "vehicle.brakes@1",
    "brakepad": "vehicle.brakes@1",
    "strut": "vehicle.suspension@1",
    "suspension": "vehicle.suspension@1",
    "spring": "vehicle.suspension@1",
    "coilover": "vehicle.suspension@1",
    "swaybar": "vehicle.suspension@1",
    "steering_wheel": "vehicle.steering_wheel@1",
    "steering": "vehicle.steering@1",
    "steer": "vehicle.steering@1",
    "power_steering": "vehicle.steering@1",
    "wheel": "vehicle.wheel@1",
    "wheeldata": "vehicle.wheel@1",
    "rim": "vehicle.wheel@1",
    "tire": "vehicle.tyre@1",
    "tyre": "vehicle.tyre@1",
    "headlight": "vehicle.headlight@1",
    "taillight": "vehicle.taillight@1",
    "foglight": "vehicle.aux_light@1",
    "rallylight": "vehicle.aux_light@1",
    "rallylights": "vehicle.aux_light@1",
    "markerlight": "vehicle.aux_light@1",
    "reverselight": "vehicle.aux_light@1",
    "chmsl": "vehicle.aux_light@1",
    "seat": "vehicle.seats@1",
    "seats": "vehicle.seats@1",
    "dashboard": "vehicle.dash@1",
    "dash": "vehicle.dash@1",
    "gauge": "vehicle.dash@1",
    "gauges": "vehicle.dash@1",
    "glass": "vehicle.glass@1",
    "windshield": "vehicle.glass@1",
    "backlight": "vehicle.glass@1",
    "doorglass": "vehicle.glass@1",
    "bumper_f": "vehicle.bumper_f@1",
    "bumper_r": "vehicle.bumper_r@1",
    "spoiler": "vehicle.spoiler@1",
    "wing": "vehicle.spoiler@1",
    "exhaust": "vehicle.exhaust@1",
    "horn": "vehicle.horn@1",
    "licenseplate": "vehicle.plate@1",
    "plate": "vehicle.plate@1",
    "body": "vehicle.bodykit@1",
    "door": "vehicle.bodykit@1",
    "doorpanel": "vehicle.bodykit@1",
    "hood": "vehicle.bodykit@1",
    "trunk": "vehicle.bodykit@1",
    "fender": "vehicle.bodykit@1",
    "mirror": "vehicle.bodykit@1",
    "quarterpanels": "vehicle.bodykit@1",
    "sideskirt": "vehicle.bodykit@1",
    "diffuser": "vehicle.bodykit@1",
    "bumperbar": "vehicle.bodykit@1",
    "lip": "vehicle.bodykit@1",
    "undertray": "vehicle.bodykit@1",
    "skidplate": "vehicle.bodykit@1",
    "rollcage": "vehicle.bodykit@1",
    "paint_design": "vehicle.bodykit@1",
    "skin_interior": "vehicle.bodykit@1",
}


def normalized_addon_slot_key(source_slot: str, candidate: str) -> str:
    def normalized(value: str) -> str:
        camel_split = re.sub(r"(?<=[a-z0-9])(?=[A-Z])", "_", value)
        return re.sub(r"[^a-z0-9]+", "_", camel_split.lower()).strip("_")

    name = normalized(source_slot)
    namespace = normalized(candidate)
    if name.startswith(f"{namespace}_"):
        name = name[len(namespace) + 1:]
    tokens = name.split("_") if name else []
    if not tokens:
        return ""

    # Nested engine slots contain a numeric displacement path before their
    # exact leaf type, e.g. engine_2_5_ecu. No other middle tokens are admitted.
    if tokens[0] == "engine" and len(tokens) > 1 and all(token.isdigit() for token in tokens[1:-1]):
        if tokens[-1] in ("ecu", "intake"):
            return tokens[-1]
        if tokens[-1] == "internals":
            return "engine_internals"

    if len(tokens) >= 2 and tokens[:2] in (["gear", "ratio"], ["transfer", "case"],
                                           ["steering", "wheel"], ["power", "steering"],
                                           ["paint", "design"], ["skin", "interior"]):
        return "_".join(tokens[:2])
    if tokens[0] == "bumper" and len(tokens) > 1 and tokens[1] in ("f", "r"):
        return f"bumper_{tokens[1]}"
    return tokens[0]


def canonical_addon_slot(source_slot: str, candidate: str) -> str | None:
    return ADDON_SLOT_TYPES.get(normalized_addon_slot_key(source_slot, candidate))


def fail(message: str) -> None:
    raise ValueError(message)


def stable_uuid(seed: str) -> str:
    raw = bytearray(hashlib.sha256(seed.encode()).digest()[:16])
    raw[6] = (raw[6] & 0x0F) | 0x50
    raw[8] = (raw[8] & 0x3F) | 0x80
    return str(uuid.UUID(bytes=bytes(raw)))


def slug(value: str) -> str:
    return re.sub(r"[^a-z0-9]+", "-", value.lower()).strip("-")


def rel(path: Path, root: Path) -> str:
    try:
        return path.resolve().relative_to(root.resolve()).as_posix()
    except ValueError:
        return path.name


def literal(value: Any) -> bool:
    if isinstance(value, (int, float)) and not isinstance(value, bool):
        return math.isfinite(value)
    if isinstance(value, str):
        return not value.startswith("$=")
    return False


def sha256_file(path: Path, chunk_bytes: int = 1024 * 1024) -> tuple[str, int]:
    digest = hashlib.sha256()
    size = 0
    with path.open("rb") as handle:
        while chunk := handle.read(chunk_bytes):
            digest.update(chunk)
            size += len(chunk)
    return digest.hexdigest(), size


def canonical_json_receipt(value: Any) -> tuple[str, int]:
    digest = hashlib.sha256()
    size = 0
    encoder = json.JSONEncoder(sort_keys=True, separators=(",", ":"), ensure_ascii=False)
    for chunk in encoder.iterencode(value):
        encoded = chunk.encode("utf-8")
        digest.update(encoded)
        size += len(encoded)
    return digest.hexdigest(), size


MAX_INDEX_SOURCES = 50_000
MAX_INDEX_PARTS = 100_000
LUA_SCAN_LIMIT = (20_000, 512 * 1024 * 1024, 16 * 1024 * 1024)


def portable_index_path(value: Any) -> str:
    if not isinstance(value, str) or not value or "\\" in value or value.startswith("/"):
        fail("selected-part index contains a non-portable source path")
    pieces = value.split("/")
    if any(piece in ("", ".", "..") for piece in pieces):
        fail("selected-part index source path escapes its admitted root")
    return value


def confined_file(root: Path, portable: str) -> Path:
    current = root
    for piece in portable_index_path(portable).split("/"):
        current = current / piece
        if current.is_symlink():
            fail(f"selected-part index source traverses a symlink: {portable}")
    try:
        info = current.stat()
        current.resolve().relative_to(root.resolve())
    except (FileNotFoundError, ValueError):
        fail(f"selected-part index source is outside its admitted root: {portable}")
    if not stat.S_ISREG(info.st_mode):
        fail(f"selected-part index source is not a regular file: {portable}")
    return current.resolve()


WATCHED_KEYS = {"idleRPM", "idleRpm", "revLimiterRPM", "maxRPM", "limiterRpm", "inertia", "friction",
                "dynamicFriction", "engineBrakeTorque", "gearRatios", "reverseGearRatio", "reverseRatio",
                "gearRatio", "transmissionShiftDelay", "shiftDelay", "diffTorqueSplit", "sampleName",
                "brakeTorque", "beamSpring", "beamDamp", "radius", "electricsName", "electric", "deformSound",
                "breakGroup", "breakTriggerBeam", "deformGroup"}

MESH_ROLE_RULES = [
    ("door", ("door",)), ("bonnet", ("hood", "bonnet")), ("boot", ("trunk", "tailgate")),
    ("glass", ("glass",)), ("lamp", ("light",)), ("mirror", ("mirror",)),
    ("wing", ("wing", "spoiler")), ("interior", ("seat", "dash", "interior")),
]

PANEL_RULES = [
    {"id": "doorFL", "role": "door", "slot": re.compile(r"(?:^|_)door_FL$", re.I), "openDeg": -68},
    {"id": "doorFR", "role": "door", "slot": re.compile(r"(?:^|_)door_FR$", re.I), "openDeg": 68},
    {"id": "doorRL", "role": "door", "slot": re.compile(r"(?:^|_)door_RL$", re.I), "openDeg": -68},
    {"id": "doorRR", "role": "door", "slot": re.compile(r"(?:^|_)door_RR$", re.I), "openDeg": 68},
    {"id": "hood", "role": "bonnet", "slot": re.compile(r"(?:^|_)(?:hood|bonnet)(?:_(?:sedan|wagon))?$", re.I), "openDeg": 55},
    {"id": "trunk", "role": "boot", "slot": re.compile(r"(?:^|_)(?:trunk|tailgate|boot)(?:_(?:sedan|wagon))?$", re.I), "openDeg": 55},
]


def mesh_role(node: str) -> str:
    lowered = node.lower()
    return next((role for role, tokens in MESH_ROLE_RULES if any(token in lowered for token in tokens)), "body")


def canonical_jbeam_point(point: tuple[float, float, float]) -> list[float]:
    """Map BeamNG +X-left/+Z-up/-Y-forward nodes into the HELIX frame."""
    return [round(point[0], 6), round(point[2], 6), round(-point[1], 6)]


def break_groups(value: Any) -> list[str]:
    if isinstance(value, str):
        return [value] if value else []
    if isinstance(value, list):
        return [entry for entry in value if isinstance(entry, str) and entry]
    return []


def source_hinge(body: dict[str, Any]) -> dict[str, Any] | None:
    """Derive a rigid hinge only from explicitly hinge-tagged JBeam beams.

    The two most distant panel-local hinge nodes define the axis. A lone node,
    coincident nodes, malformed coordinates, or an origin pivot is insufficient
    evidence and disables physical articulation for that panel.
    """
    positions: dict[str, tuple[float, float, float]] = {}
    for row in decode_jbeam_table(body.get("nodes")):
        node_id = row.get("id")
        values = (row.get("posX"), row.get("posY"), row.get("posZ"))
        if isinstance(node_id, str) and all(isinstance(value, (int, float)) and not isinstance(value, bool)
                                            and math.isfinite(value) for value in values):
            positions[node_id] = tuple(float(value) for value in values)
    hinge_nodes: set[str] = set()
    hinge_groups: set[str] = set()
    for row in decode_jbeam_table(body.get("beams")):
        groups = [group for group in break_groups(row.get("breakGroup")) if "hinge" in group.lower()]
        if not groups:
            continue
        hinge_groups.update(groups)
        for key in ("id1", "id2"):
            node_id = row.get(key)
            if isinstance(node_id, str) and node_id in positions:
                hinge_nodes.add(node_id)
    if len(hinge_nodes) < 2:
        return None
    pairs = []
    for index, first_id in enumerate(sorted(hinge_nodes)):
        for second_id in sorted(hinge_nodes)[index + 1:]:
            first, second = positions[first_id], positions[second_id]
            distance = math.dist(first, second)
            pairs.append((distance, first_id, second_id, first, second))
    distance, first_id, second_id, first, second = max(pairs, default=(0, "", "", (), ()))
    if distance <= 1e-4:
        return None
    first_canonical = canonical_jbeam_point(first)
    second_canonical = canonical_jbeam_point(second)
    vector = [second_canonical[index] - first_canonical[index] for index in range(3)]
    length = math.hypot(*vector)
    if length <= 1e-4:
        return None
    axis = [round(value / length, 6) for value in vector]
    pivot = [round((first_canonical[index] + second_canonical[index]) / 2, 6) for index in range(3)]
    if math.hypot(*pivot) <= 1e-4:
        return None
    return {"pivot": pivot, "axis": axis, "nodeIds": [first_id, second_id],
            "breakGroups": sorted(hinge_groups)}


def articulation_candidates(selected: list[tuple[str, str, dict[str, Any], Path]],
                            slot_rows: list[dict[str, Any]]) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
    """Return runtime panels and source-only evidence, failing closed per panel."""
    bodies = {part_name: body for _, part_name, body, _ in selected}
    meshes = {part_name: sorted({str(row.get("mesh")) for row in decode_jbeam_table(body.get("flexbodies"))
                                 if row.get("mesh")}) for part_name, body in bodies.items()}
    descendants: dict[str, set[str]] = {}
    for row in slot_rows:
        host, child = row.get("hostPart"), row.get("selectedPart")
        if row.get("resolution") == "resolved" and isinstance(host, str) and isinstance(child, str) \
                and host in bodies and child in bodies and child:
            descendants.setdefault(host, set()).add(child)

    candidates: list[dict[str, Any]] = []
    for rule in PANEL_RULES:
        roots = sorted(name for name, body in bodies.items()
                       if isinstance(body.get("slotType"), str) and rule["slot"].search(body["slotType"]))
        if len(roots) != 1:
            continue
        root = roots[0]
        hinge = source_hinge(bodies[root])
        if hinge is None:
            continue
        custody_parts: set[str] = set()
        pending = [root]
        while pending:
            part_name = pending.pop()
            if part_name in custody_parts:
                continue
            custody_parts.add(part_name)
            pending.extend(sorted(descendants.get(part_name, set()), reverse=True))
        nodes = sorted({node for part_name in custody_parts for node in meshes.get(part_name, [])})
        if not nodes:
            continue
        panel = {"id": rule["id"], "role": rule["role"],
                 "signal": f"panel.{rule['id']}.openness", "nodes": nodes,
                 "hinge": {"pivot": hinge["pivot"], "axis": hinge["axis"],
                           "closedDeg": 0, "openDeg": rule["openDeg"]},
                 "collider": {"kind": "visual-bounds-box", "minHalfExtentM": .03},
                 "dynamics": {"detents": [0, .25, 1], "latchFraction": .05,
                              "latchAngularSpeedRadS": 1.5},
                 # Detachment is future eligibility only. No production fidelity
                 # tier may activate it until the runtime has an authoritative
                 # detached-body/network ownership contract.
                 "fidelity": {"physical": ["medium", "high", "ultra"], "detachable": []}}
        candidates.append({"panel": panel, "rootPart": root,
                           "descendantParts": sorted(custody_parts - {root}),
                           "hingeNodeIds": hinge["nodeIds"], "hingeBreakGroups": hinge["breakGroups"]})

    owners: dict[str, list[str]] = {}
    for candidate in candidates:
        for node in candidate["panel"]["nodes"]:
            owners.setdefault(node, []).append(candidate["panel"]["id"])
    ambiguous_panels = {panel_id for panel_ids in owners.values() if len(panel_ids) > 1 for panel_id in panel_ids}
    accepted = [candidate for candidate in candidates if candidate["panel"]["id"] not in ambiguous_panels]
    accepted.sort(key=lambda row: next(index for index, rule in enumerate(PANEL_RULES)
                                       if rule["id"] == row["panel"]["id"]))
    return [candidate["panel"] for candidate in accepted], accepted


def lamp_functions(part_name: str, channel: str) -> list[str]:
    lowered = channel.lower()
    rules: list[tuple[Callable[[], bool], list[str]]] = [
        (lambda: "signal_l" in lowered, ["indicator_left"]),
        (lambda: "signal_r" in lowered, ["indicator_right"]),
        (lambda: "lowhighbrake" in lowered, ["tail", "brake"]),
        (lambda: "brakelight" in lowered, ["brake"]),
        (lambda: "reverse" in lowered, ["reverse"]),
        (lambda: "fog" in lowered, ["fog_front"]),
        (lambda: "highbeam" in lowered and "lowhigh" not in lowered, ["headlight_high"]),
        (lambda: "lowhighbeam" in lowered,
         ["tail" if any(token in part_name.lower() for token in ("tail", "trunklight")) else "headlight_low"]),
    ]
    return next((functions for predicate, functions in rules if predicate()), [])


def lamp_side(part_name: str, channel: str) -> str:
    lowered_channel, lowered_part = channel.lower(), part_name.lower()
    return next((side for side in ("_l", "_r")
                 if side in lowered_channel or lowered_part.endswith(side)), "")


LAMP_NODE_SEMANTICS = {
    "reverse": ("reverse",), "fog_front": ("fog", "rally"),
    "headlight_low": ("headlight",), "headlight_high": ("headlight",),
    "indicator_left": ("signal",), "indicator_right": ("signal",),
    "tail": ("taillight", "tail"), "brake": ("taillight", "tail"),
}

TRANSMISSION_DEVICE_KINDS = {
    "manualgearbox": "manual",
    "sequentialgearbox": "sequential",
    "dctgearbox": "dct",
    "cvtgearbox": "cvt",
    "automaticgearbox": "automatic",
}

TRANSMISSION_INFO_KINDS = {
    "manual": "manual",
    "sequential": "sequential",
    "dct": "dct",
    "cvt": "cvt",
    "automatic": "automatic",
}


def lamp_beam(light: str) -> dict[str, float] | None:
    if light not in ("headlight_low", "headlight_high", "fog_front"):
        return None
    high = light == "headlight_high"
    return {"halfAngleDeg": 16 if high else 28, "distance": 80 if high else 50,
            "penumbra": .3, "intensity": 1}


def selected_powertrain_devices(selected: Iterable[tuple[str, str, dict[str, Any], Path]],
                                label_source: Callable[[Path], str]) -> list[dict[str, Any]]:
    selected_parts = list(selected)
    base_devices: list[tuple[str, str, Path, list[str], dict[str, Any]]] = []
    for slot_name, part_name, body, path in selected_parts:
        controllers = sorted(str(row["fileName"]) for row in decode_jbeam_table(body.get("controller"))
                             if isinstance(row.get("fileName"), str))
        for row in decode_jbeam_table(body.get("powertrain")):
            name = row.get("name")
            if not isinstance(name, str) or not name:
                continue
            base_devices.append((slot_name, part_name, path, controllers, row))
    device_names = {row[4]["name"] for row in base_devices}
    overlay_index: dict[str, list[tuple[dict[str, Any], str]]] = {}
    overlay_count = 0
    for _, part_name, body, path in selected_parts:
        for name, options in body.items():
            if name not in device_names or not isinstance(options, dict):
                continue
            overlay_count += 1
            if overlay_count > MAX_INDEX_PARTS:
                fail(f"selected powertrain device overlays exceed {MAX_INDEX_PARTS}")
            overlay_index.setdefault(name, []).append(
                (options, f"{label_source(path)}#{part_name}.{name}"))

    devices: list[dict[str, Any]] = []
    for slot_name, part_name, path, controllers, row in base_devices:
        name = row["name"]
        merged = dict(row)
        overlay_sources: list[str] = []
        overlay_fields: dict[str, list[tuple[Any, str]]] = {}
        for options, overlay_source in overlay_index.get(name, []):
            overlay_sources.append(overlay_source)
            for field, value in options.items():
                overlay_fields.setdefault(field, []).append((value, overlay_source))
        overlay_conflicts: list[dict[str, Any]] = []
        for field, values in overlay_fields.items():
            unique_values = {json.dumps(value, sort_keys=True, separators=(",", ":")) for value, _ in values}
            if len(unique_values) == 1:
                merged[field] = values[0][0]
            else:
                sources = [source for _, source in values]
                merged[field] = {"ambiguousOverlaySources": sources}
                overlay_conflicts.append({"field": field, "sources": sources})
        devices.append({**merged, "partName": part_name, "slotType": slot_name,
                        "source": f"{label_source(path)}#{part_name}.powertrain",
                        "overlaySources": sorted(set(overlay_sources)),
                        "overlayFieldSources": {field: sorted({source for _, source in values})
                                                for field, values in sorted(overlay_fields.items())},
                        "overlayConflicts": overlay_conflicts, "controllers": controllers})
    return devices


def selected_transmission_kind(devices: Iterable[dict[str, Any]],
                               config_info: dict[str, Any]) -> tuple[str | None, str, str]:
    """Return a kind only when the selected, fingerprinted source is unambiguous."""
    evidence: list[tuple[str, str, str, str]] = []
    for row in devices:
        device_type = str(row.get("type", ""))
        kind = TRANSMISSION_DEVICE_KINDS.get(device_type.lower())
        if kind is not None:
            evidence.append((kind, row["partName"], row["source"], device_type))
    kinds = {row[0] for row in evidence}
    info_value = str(config_info.get("Transmission", "")).strip()
    info_kind = TRANSMISSION_INFO_KINDS.get(info_value.lower())
    if len(kinds) > 1:
        detail = ", ".join(sorted(f"{part}:{device}" for _, part, _, device in evidence))
        return None, "selected JBeam#powertrain.type", f"Ambiguous selected transmission devices: {detail}."
    if evidence:
        kind, part_name, source, device_type = evidence[0]
        if info_kind is not None and info_kind != kind:
            return None, source, \
                f"Selected {part_name} declares {device_type}, but configuration info declares {info_value}."
        return kind, source, f"Selected {part_name} powertrain device type is {device_type}."
    if info_kind is not None:
        return info_kind, "selected configuration info#Transmission", \
            f"No selected JBeam transmission device row was available; exact configuration info declares {info_value}."
    return None, "selected JBeam#powertrain.type", \
        "No recognized manualGearbox, sequentialGearbox, dctGearbox, cvtGearbox, or automaticGearbox device was selected."


def key_multimap(parts: Iterable[tuple[str, Any]], max_entries: int = 1_000_000,
                 max_depth: int = 128) -> dict[str, list[tuple[str, Any]]]:
    """Index keys once with pending memory proportional to nesting depth."""
    result: dict[str, list[tuple[str, Any]]] = {}
    # Each frame owns an iterator and advances only one child before descending,
    # so a million-wide object never becomes a million-entry pending stack.
    stack: list[tuple[str, str | None, Any, int]] = [("roots", None, iter(parts), -1)]
    entries = 0
    while stack:
        kind, part, iterator, parent_depth = stack[-1]
        try:
            item = next(iterator)
        except StopIteration:
            stack.pop()
            continue
        if kind == "roots":
            part, node = item
            depth = 0
        elif kind == "dict":
            name, node = item
            normalized = str(name).lstrip("$+")
            if normalized in WATCHED_KEYS:
                result.setdefault(normalized, []).append((str(part), node))
            depth = parent_depth + 1
        else:
            node = item
            depth = parent_depth + 1
        if depth > max_depth:
            fail(f"selected JBeam closure exceeds nested depth cap {max_depth}")
        entries += 1
        if entries > max_entries:
            fail(f"selected JBeam closure exceeds traversal cap {max_entries}")
        if isinstance(node, dict):
            stack.append(("dict", str(part), iter(node.items()), depth))
        elif isinstance(node, list):
            stack.append(("list", str(part), iter(node), depth))
    return result


def indexed_values(index: dict[str, list[tuple[str, Any]]], key: str,
                   part_filter: Callable[[str], bool] | None = None) -> list[Any]:
    return [value for part, value in index.get(key.lstrip("$+"), []) if part_filter is None or part_filter(part)]


def number(index: dict[str, list[tuple[str, Any]]], keys: Iterable[str], default: float,
           part_filter: Callable[[str], bool] | None = None) -> tuple[float, str]:
    for key in keys:
        values = indexed_values(index, key, part_filter)
        for value in reversed(values):
            if literal(value) and isinstance(value, (int, float)):
                return float(value), key
    return default, "HELIX-default"


def sourced(value: Any, unit: str, source: str | None = None, note: str | None = None) -> dict[str, Any]:
    row: dict[str, Any] = {"value": value, "unit": unit}
    if source:
        row["sources"] = [source]
    else:
        row["derivedFrom"] = note or "Explicit HELIX runtime prior; BeamNG source has no directly equivalent literal."
    if note:
        row["note"] = note
    return row


SUSPENSION_AXLE_PATTERN = re.compile(r"(?:^|_)(?:strut|coilover)_?([FR])(?:_|$)", re.I)
SWAYBAR_AXLE_PATTERN = re.compile(r"(?:^|_)(?:rally_)?swaybar_?([FR])(?:_|$)", re.I)
TIRE_AXLE_PATTERN = re.compile(r"(?:^|_)tire_?([FR])(?:_|$)", re.I)


def selected_variable_environment(selected: Iterable[tuple[str, str, dict[str, Any], Path]],
                                  config: dict[str, Any], config_path: Path,
                                  label_source: Callable[[Path], str]) -> tuple[dict[str, Any], dict[str, dict[str, Any]]]:
    """Resolve the selected JBeam defaults, then exact `.pc` variable overrides."""
    values: dict[str, Any] = {}
    receipts: dict[str, dict[str, Any]] = {}
    for _, part_name, body, path in selected:
        for row in decode_jbeam_table(body.get("variables")):
            name, default = row.get("name"), row.get("default")
            if not isinstance(name, str) or not re.fullmatch(r"\$[A-Za-z_][A-Za-z0-9_]*", name):
                continue
            if isinstance(default, float) and not math.isfinite(default):
                continue
            values[name] = default
            receipts[name] = {"value": default, "selection": "selected-default",
                              "source": f"{label_source(path)}#{part_name}.variables.{name}.default"}
    overrides = config.get("vars")
    if isinstance(overrides, dict):
        for name in sorted(overrides):
            value = overrides[name]
            if not isinstance(name, str) or not re.fullmatch(r"\$[A-Za-z_][A-Za-z0-9_]*", name):
                continue
            # Keep unsupported scalar/object overrides in the environment so
            # they fail the exact expression rather than silently falling back
            # to the JBeam default they override.
            values[name] = value
            receipt = {"value": value, "selection": "configuration-override",
                       "source": f"{config_path.name}#vars.{name}"}
            if isinstance(value, float) and not math.isfinite(value):
                # JSON has no portable non-finite number representation. Keep
                # the evaluator's exact value, but serialize an explicit safe
                # receipt instead of emitting invalid terminal JSON.
                receipt.update({"value": None, "raw": repr(value), "status": "unsupported"})
            receipts[name] = receipt
    return values, receipts


def numeric_resolution(value: Any, variables: dict[str, Any]) -> ExpressionResolution:
    result = resolve_beamng_expression(value, variables)
    if result.status != "unsupported" and (isinstance(result.value, bool)
                                              or not isinstance(result.value, (int, float))
                                              or not math.isfinite(result.value)):
        return ExpressionResolution("unsupported", None, result.variables,
                                    "expression did not resolve to a finite number")
    if result.status != "unsupported":
        return ExpressionResolution(result.status, round(float(result.value), 12),
                                    result.variables, result.reason)
    return result


def lower_selected_brakes(selected: list[tuple[str, str, dict[str, Any], Path]],
                          variables: dict[str, Any], variable_receipts: dict[str, dict[str, Any]],
                          label_source: Callable[[Path], str], citation_id: str,
                          provenance: list[dict[str, Any]]) -> tuple[dict[str, Any], dict[str, Any], bool]:
    """Lower the two selected brake-part option blocks into HELIX totals.

    BeamNG's torque values apply to each wheel in the part-owned axle section;
    HELIX's values are totals across the car. Front bias is therefore derived
    from the per-wheel front/rear values before both axles are doubled.
    """
    candidates: dict[str, list[dict[str, Any]]] = {"front": [], "rear": []}
    unowned: list[dict[str, Any]] = []
    for slot_name, part_name, body, path in selected:
        options = pressure_wheel_options(body)
        if "brakeTorque" not in options and "parkingTorque" not in options:
            continue
        axle = selected_part_axle(BRAKE_AXLE_PATTERN, slot_name, part_name, body)
        receipt = {"slotType": slot_name, "partName": part_name,
                   "source": f"{label_source(path)}#{part_name}.pressureWheels",
                   "options": {key: options[key] for key in ("brakeTorque", "brakeInputSplit",
                                                              "brakeSplitCoef", "parkingTorque")
                               if key in options}}
        if axle is None:
            # Suspension defaults deliberately clear inherited brake options;
            # they do not own an axle brake Package and cannot override the
            # exact selected brake part.
            if "brake" in slot_name.lower() or "brake" in part_name.lower():
                unowned.append(receipt)
            continue
        candidates[axle].append(receipt)

    axles: dict[str, dict[str, Any]] = {}
    complete = True
    for axle in ("front", "rear"):
        rows = candidates[axle]
        if len(rows) != 1:
            complete = False
            detail = f"Expected one selected {axle} brake part; found {len(rows)}."
            provenance.append({"target": f"physics.brakes.{axle}",
                               "source": "selected JBeam pressureWheels",
                               "disposition": "unsupported", "detail": detail})
            axles[axle] = {"status": "unsupported", "reason": detail,
                           "candidates": rows}
            continue
        receipt = rows[0]
        options = receipt["options"]
        fields: dict[str, Any] = {}
        for field in ("brakeTorque", "parkingTorque"):
            result = numeric_resolution(options.get(field), variables)
            disposition = "source-literal" if result.status == "literal" else result.status
            row: dict[str, Any] = {"raw": options.get(field), "status": result.status,
                                   "variables": list(result.variables)}
            if result.status != "unsupported":
                row["value"] = result.value
            else:
                row["reason"] = result.reason
                complete = False
            fields[field] = row
            provenance.append({"target": f"sourceSemantics.brakes.axles.{axle}.{field}",
                               "source": receipt["source"], "disposition": disposition,
                               "detail": result.reason or
                               (f"Selected literal {result.value:g}." if result.status == "literal" else
                                f"Resolved {options.get(field)!r} to {result.value:g} from selected variables.")})
        for field in ("brakeInputSplit", "brakeSplitCoef"):
            if field in options:
                fields[field] = {"raw": options[field], "status": "preserved-source"}
        axle_row = {key: value for key, value in receipt.items() if key != "options"}
        axle_row.update(fields)
        axles[axle] = axle_row

    front_torque = axles.get("front", {}).get("brakeTorque", {}).get("value")
    rear_torque = axles.get("rear", {}).get("brakeTorque", {}).get("value")
    front_parking = axles.get("front", {}).get("parkingTorque", {}).get("value")
    rear_parking = axles.get("rear", {}).get("parkingTorque", {}).get("value")
    complete = complete and all(isinstance(value, (int, float)) and not isinstance(value, bool)
                                for value in (front_torque, rear_torque, front_parking, rear_parking))
    if complete:
        complete = bool(front_torque > 0 and rear_torque > 0
                        and front_parking >= 0 and rear_parking >= 0
                        and front_parking + rear_parking > 0)
        if not complete:
            provenance.append({"target": "physics.brakes", "source": "selected JBeam pressureWheels",
                               "disposition": "unsupported",
                               "detail": "Selected brake torque must be positive on both axles and parking torque must be non-negative and present on at least one axle."})

    if complete:
        per_wheel_total = float(front_torque + rear_torque)
        max_torque = round(per_wheel_total * 2, 6)
        bias_front = round(float(front_torque) / per_wheel_total, 8)
        parking_by_axle = {"front": float(front_parking), "rear": float(rear_parking)}
        active_parking = [axle for axle, torque in parking_by_axle.items() if torque > 0]
        handbrake_axle = active_parking[0] if len(active_parking) == 1 else "all"
        handbrake_torque = round(sum(parking_by_axle.values()) * 2, 6)
        brakes = {
            "maxTorque": sourced(max_torque, "N.m", citation_id,
                                  "Twice the sum of selected per-wheel front and rear brake torque."),
            "biasFront": sourced(bias_front, "ratio", citation_id,
                                  "Selected front per-wheel torque divided by front plus rear per-wheel torque."),
            "handbrakeTorque": sourced(handbrake_torque, "N.m", citation_id,
                                        "Twice the selected per-wheel parking torque across its active axle(s)."),
            "handbrakeAxle": handbrake_axle,
        }
        for target, detail in (
            ("physics.brakes.maxTorque", f"2 * ({front_torque:g} + {rear_torque:g}) = {max_torque:g} N.m."),
            ("physics.brakes.biasFront", f"{front_torque:g} / ({front_torque:g} + {rear_torque:g}) = {bias_front:g}."),
            ("physics.brakes.handbrakeTorque", f"2 * ({front_parking:g} + {rear_parking:g}) = {handbrake_torque:g} N.m on {handbrake_axle}."),
        ):
            provenance.append({"target": target, "source": "selected JBeam brake-part pressureWheels rows",
                               "disposition": "derived", "detail": detail})
    else:
        brakes = {
            "maxTorque": sourced(3900, "N.m", note="HELIX functional fallback; selected brake rows were incomplete or unsupported."),
            "biasFront": sourced(.6923, "ratio", note="HELIX functional fallback; selected axle torque was incomplete or unsupported."),
            "handbrakeTorque": sourced(1800, "N.m", note="HELIX functional fallback; selected parking torque was incomplete or unsupported."),
            "handbrakeAxle": "rear",
        }
        provenance.append({"target": "physics.brakes", "source": "HELIX functional fallback",
                           "disposition": "defaulted",
                           "detail": "Selected front/rear brake and parking torque rows did not all resolve; brake domain remains non-functional."})

    used_variables = sorted({name for row in axles.values() if isinstance(row, dict)
                             for field in ("brakeTorque", "parkingTorque")
                             for name in row.get(field, {}).get("variables", [])})
    semantics = {"variables": {name: variable_receipts[name] for name in used_variables
                                if name in variable_receipts},
                 "axles": axles, "unownedPressureWheelOptions": sorted(
                     unowned, key=lambda row: (row["slotType"], row["partName"], row["source"]))}
    return brakes, semantics, complete


def suspension_row_side(row: dict[str, Any]) -> str | None:
    labels = [row.get("name"), row.get("id1"), row.get("id2")]
    sides: set[str] = set()
    for label in labels:
        if not isinstance(label, str):
            continue
        match = re.search(r"(?:_|[0-9])([LR])$", label, re.I)
        if match:
            sides.add("left" if match.group(1).lower() == "l" else "right")
    return next(iter(sides)) if len(sides) == 1 else None


def resolution_receipt(raw: Any, variables: dict[str, Any], unit: str,
                       source: str, provenance: list[dict[str, Any]], target: str) -> dict[str, Any]:
    row, _ = numeric_receipt(raw, variables, unit)
    disposition = "source-literal" if row["status"] == "literal" else row["status"]
    detail = row.get("reason") or (f"Selected literal {row['value']:g} {unit}."
                                   if row["status"] == "literal" else
                                   f"Resolved {raw!r} to {row['value']:g} {unit} from selected variables.")
    provenance.append({"target": target, "source": source,
                       "disposition": disposition, "detail": detail})
    return row


def symmetric_suspension_field(rows: list[dict[str, Any]], field: str,
                               variables: dict[str, Any], unit: str, source: str,
                               provenance: list[dict[str, Any]], target: str,
                               positive: bool = False,
                               require_velocity_split: bool = False) -> dict[str, Any]:
    """Collapse only a matching left/right pair from one selected leaf part."""
    by_side: dict[str, list[tuple[Any, ExpressionResolution, dict[str, Any]]]] = {
        "left": [], "right": []}
    unsupported: list[ExpressionResolution] = []
    unsupported_variables: set[str] = set()
    for row in rows:
        if field not in row:
            continue
        raw = row[field]
        result = numeric_resolution(raw, variables)
        if result.status == "unsupported":
            unsupported.append(result)
            unsupported_variables.update(result.variables)
            continue
        if positive and not (result.value > 0):
            continue
        side = suspension_row_side(row)
        if side:
            by_side[side].append((raw, result, row))
    reason = None
    chosen: list[tuple[Any, ExpressionResolution, dict[str, Any]]] = []
    if unsupported:
        reason = unsupported[0].reason
    else:
        for side in ("left", "right"):
            values = by_side[side]
            if len(values) != 1:
                reason = f"expected one selected {side} {field} row; found {len(values)}"
                break
            chosen.append(values[0])
        if reason is None and chosen[0][1].value != chosen[1][1].value:
            reason = f"selected left/right {field} values do not match"
    velocity_split = None
    if reason is None and require_velocity_split:
        split_rows = []
        for _, _, row in chosen:
            if "beamDampVelocitySplit" not in row:
                reason = f"selected {field} rows are missing beamDampVelocitySplit"
                break
            split_rows.append((row["beamDampVelocitySplit"],
                               numeric_resolution(row["beamDampVelocitySplit"], variables)))
        if reason is None:
            unsupported_split = next((result for _, result in split_rows
                                      if result.status == "unsupported"), None)
            if unsupported_split:
                unsupported_variables.update(unsupported_split.variables)
                reason = unsupported_split.reason
            elif split_rows[0][1].value != split_rows[1][1].value:
                reason = f"selected left/right {field} beamDampVelocitySplit values do not match"
            elif not isinstance(split_rows[0][1].value, (int, float)):
                reason = f"selected {field} beamDampVelocitySplit is not numeric"
            elif split_rows[0][1].value < 0:
                reason = f"selected {field} beamDampVelocitySplit must be non-negative"
            else:
                velocity_split = split_rows[0]
    if reason is not None:
        receipt = {"status": "unsupported", "unit": unit, "reason": reason,
                   "variables": sorted(unsupported_variables)}
        provenance.append({"target": target, "source": source,
                           "disposition": "unsupported", "detail": reason})
        return receipt
    raw = chosen[0][0]
    result = chosen[0][1]
    receipt = {"raw": raw, "status": result.status, "value": result.value,
               "unit": unit, "variables": list(result.variables), "symmetricRows": 2}
    if velocity_split is not None:
        split_raw, split_result = velocity_split
        receipt["velocitySplit"] = {
            "raw": split_raw, "status": split_result.status, "value": split_result.value,
            "unit": "m/s", "variables": list(split_result.variables), "symmetricRows": 2,
        }
        receipt["variables"] = sorted(set(receipt["variables"]) | set(split_result.variables))
    disposition = "source-literal" if result.status == "literal" else "derived"
    provenance.append({"target": target, "source": source, "disposition": disposition,
                       "detail": (f"Matching selected left/right rows resolve to {result.value:g} {unit}.")})
    return receipt


def lower_selected_suspension(selected: list[tuple[str, str, dict[str, Any], Path]],
                              variables: dict[str, Any], variable_receipts: dict[str, dict[str, Any]],
                              label_source: Callable[[Path], str],
                              chassis_mass: float, weight_front: float,
                              provenance: list[dict[str, Any]]) -> tuple[dict[str, Any], dict[str, Any]]:
    """Extract selected strut/coilover semantics without treating structure as suspension.

    BeamNG authors spring and velocity-sensitive damper beams at the selected
    strut. HELIX currently authors wheel rate plus one global slow damper
    triplet. The exact source values and their beam-space derivations are
    retained here, while the runtime projection remains fail-closed until a
    motion ratio and axle-specific fast/slow damping contract are available.
    """
    leaves: dict[str, list[tuple[str, str, dict[str, Any], Path]]] = {"front": [], "rear": []}
    excluded: list[dict[str, Any]] = []
    anti_roll_candidates: dict[str, list[tuple[str, str, dict[str, Any], Path]]] = {
        "front": [], "rear": []}
    for slot_name, part_name, body, path in selected:
        axle = selected_part_axle(SUSPENSION_AXLE_PATTERN, slot_name, part_name, body)
        if axle:
            leaves[axle].append((slot_name, part_name, body, path))
            continue
        sway_axle = selected_part_axle(SWAYBAR_AXLE_PATTERN, slot_name, part_name, body)
        if sway_axle:
            anti_roll_candidates[sway_axle].append((slot_name, part_name, body, path))
        label = " ".join(str(value) for value in (slot_name, body.get("slotType"), part_name)).lower()
        if not any(token in label for token in ("suspension", "strut", "swaybar")):
            continue
        structural_rows = [row for row in decode_jbeam_table(body.get("beams"))
                           if "beamSpring" in row or "beamDamp" in row]
        if structural_rows:
            reason = ("swaybar construction beams do not own anti-roll stiffness" if sway_axle else
                      "not selected through a strut/coilover leaf slot")
            excluded.append({"slotType": slot_name, "partName": part_name,
                             "source": f"{label_source(path)}#{part_name}.beams",
                             "beamRows": len(structural_rows), "reason": reason})

    axles: dict[str, dict[str, Any]] = {}
    used_variables: set[str] = set()
    extraction_complete = True
    for axle in ("front", "rear"):
        candidates = leaves[axle]
        if len(candidates) != 1:
            reason = f"Expected one selected {axle} strut/coilover leaf part; found {len(candidates)}."
            provenance.append({"target": f"sourceSemantics.suspension.axles.{axle}",
                               "source": "selected JBeam part custody",
                               "disposition": "unsupported", "detail": reason})
            axles[axle] = {"status": "unsupported", "reason": reason,
                           "candidates": [part for _, part, _, _ in candidates]}
            extraction_complete = False
            continue
        slot_name, part_name, body, path = candidates[0]
        source = f"{label_source(path)}#{part_name}.beams"
        beams = decode_jbeam_table(body.get("beams"))
        variable_springs = [row for row in beams if isinstance(row.get("beamSpring"), str)
                            and "precompressionRange" in row
                            and row["beamSpring"].startswith("$")]
        literal_springs = [] if variable_springs else [
            row for row in beams if isinstance(row.get("beamSpring"), (int, float))
            and not isinstance(row.get("beamSpring"), bool)
            and row["beamSpring"] > 0 and row.get("beamDamp") == 0
            and "precompressionRange" in row]
        spring_rows = variable_springs or literal_springs
        spring = symmetric_suspension_field(
            spring_rows, "beamSpring", variables, "N/m", source, provenance,
            f"sourceSemantics.suspension.axles.{axle}.springRate", positive=True)
        precompression = symmetric_suspension_field(
            spring_rows, "precompressionRange", variables, "m", source, provenance,
            f"sourceSemantics.suspension.axles.{axle}.precompressionRange")
        damper_rows = [row for row in beams if row.get("beamSpring") == 0
                       and ("beamDampVelocitySplit" in row
                            or re.match(r"^(?:shock|damper)_", str(row.get("name", "")), re.I))]
        damping = {}
        for output_name, field in (("slowBump", "beamDamp"), ("fastBump", "beamDampFast"),
                                   ("slowRebound", "beamDampRebound"),
                                   ("fastRebound", "beamDampReboundFast")):
            damping[output_name] = symmetric_suspension_field(
                damper_rows, field, variables, "N.s/m", source, provenance,
                f"sourceSemantics.suspension.axles.{axle}.damping.{output_name}",
                positive=True, require_velocity_split=True)
        travel_rows = [row for row in beams if row.get("beamSpring") == 0 and row.get("beamDamp") == 0
                       and not row.get("name") and "beamDampVelocitySplit" not in row
                       and isinstance(row.get("shortBoundRange"), (int, float))
                       and 0 < row["shortBoundRange"] <= .5]
        bump_limit = symmetric_suspension_field(
            travel_rows, "shortBoundRange", variables, "m", source, provenance,
            f"sourceSemantics.suspension.axles.{axle}.bumpLimit", positive=True)
        required = [spring, precompression, bump_limit, *damping.values()]
        axle_complete = not any(row.get("status") == "unsupported" for row in required)
        if not axle_complete:
            extraction_complete = False
        for row in required:
            used_variables.update(row.get("variables", []))
        derived: dict[str, Any] = {}
        if spring.get("status") != "unsupported":
            corner_mass = chassis_mass * (weight_front if axle == "front" else 1 - weight_front) / 2
            critical = 2 * math.sqrt(float(spring["value"]) * corner_mass)
            derived = {
                "cornerMassKg": round(corner_mass, 6),
                "beamNaturalHz": round(math.sqrt(float(spring["value"]) / corner_mass) / (2 * math.pi), 8),
                "criticalDampingNsPerM": round(critical, 6),
            }
            for output_name, ratio_name in (("slowBump", "slowBumpRatio"),
                                            ("fastBump", "fastBumpRatio"),
                                            ("slowRebound", "slowReboundRatio"),
                                            ("fastRebound", "fastReboundRatio")):
                value = damping[output_name].get("value")
                if isinstance(value, (int, float)):
                    derived[ratio_name] = round(float(value) / critical, 8)
            provenance.append({"target": f"sourceSemantics.suspension.axles.{axle}.derived",
                               "source": source, "disposition": "derived",
                               "detail": "Beam natural frequency and damping ratios derived from selected beam rates and the emitted HELIX corner mass; not claimed as wheel-space ride values without motion ratio."})
        axles[axle] = {"status": "resolved" if axle_complete else "unsupported",
                       "slotType": slot_name, "partName": part_name, "source": source,
                       "springRate": spring, "precompressionRange": precompression,
                       "damping": damping, "bumpLimit": bump_limit, "derived": derived,
                       "rowCounts": {"spring": len(spring_rows), "damper": len(damper_rows),
                                     "travelLimit": len(travel_rows)}}

    anti_roll: dict[str, Any] = {}
    for axle in ("front", "rear"):
        candidates = anti_roll_candidates[axle]
        if len(candidates) != 1:
            anti_roll[axle] = {"status": "unsupported",
                               "reason": f"expected one selected {axle} swaybar part; found {len(candidates)}"}
            extraction_complete = False
            continue
        slot_name, part_name, body, path = candidates[0]
        source = f"{label_source(path)}#{part_name}.torsionbars"
        torsion_rows = [row for row in decode_jbeam_table(body.get("torsionbars")) if "spring" in row]
        if len(torsion_rows) == 1:
            torsion = resolution_receipt(torsion_rows[0]["spring"], variables, "N.m/rad", source,
                                         provenance, f"sourceSemantics.suspension.antiRoll.{axle}.torsionSpring")
            used_variables.update(torsion.get("variables", []))
        else:
            reason = f"expected one selected torsionbar spring row; found {len(torsion_rows)}"
            torsion = {"status": "unsupported", "unit": "N.m/rad", "reason": reason,
                       "variables": []}
            provenance.append({"target": f"sourceSemantics.suspension.antiRoll.{axle}.torsionSpring",
                               "source": source, "disposition": "unsupported", "detail": reason})
        if torsion.get("status") == "unsupported":
            extraction_complete = False
        anti_roll[axle] = {"slotType": slot_name, "partName": part_name, "source": source,
                           "torsionSpring": torsion, "runtimeStatus": "unsupported",
                           "reason": "BeamNG torsional stiffness requires selected lever-arm and wheel motion-ratio geometry before HELIX N/m conversion."}

    runtime_blockers = [
        "Selected beam spring rate requires wheel motion ratio before it is a HELIX wheel-space ride frequency.",
        "HELIX PackageSuspension has one global damping triplet and no axle-specific fast/slow velocity split.",
        "BeamNG strut bounds and precompression require suspension motion geometry before HELIX static ride height/travel conversion.",
        "BeamNG torsionbar stiffness requires lever-arm and wheel motion-ratio geometry before HELIX anti-roll N/m conversion.",
    ]
    for target, detail in (("rideHzFront", runtime_blockers[0]), ("rideHzRear", runtime_blockers[0]),
                           ("dampingRatio", runtime_blockers[1]), ("bumpScale", runtime_blockers[1]),
                           ("reboundScale", runtime_blockers[1]), ("staticRideHeight", runtime_blockers[2]),
                           ("bumpTravel", runtime_blockers[2]), ("antiRollBarFront", runtime_blockers[3]),
                           ("antiRollBarRear", runtime_blockers[3])):
        provenance.append({"target": f"physics.suspension.{target}",
                           "source": "selected JBeam suspension semantics",
                           "disposition": "unsupported", "detail": detail})
    suspension = {
        "rideHzFront": sourced(1.8, "Hz", note="HELIX sports prior; selected beam rate lacks wheel motion ratio."),
        "rideHzRear": sourced(1.8, "Hz", note="HELIX sports prior; selected beam rate lacks wheel motion ratio."),
        "dampingRatio": sourced(.45, "ratio", note="HELIX sports prior; selected axle fast/slow damping cannot fit the global runtime field exactly."),
        "bumpScale": sourced(1, "ratio", note="HELIX solver prior; selected axle damping is retained in source semantics."),
        "reboundScale": sourced(1, "ratio", note="HELIX solver prior; selected axle damping is retained in source semantics."),
        "staticRideHeight": sourced(.34, "m", note="Wheel-radius-derived prior; selected strut geometry does not yet provide wheel-space ride height."),
        "bumpTravel": sourced(.1, "m", note="HELIX sports prior; selected strut bound is retained in beam space."),
        "antiRollBarFront": sourced(0, "N/m", note="HELIX off fallback; selected torsionbar lacks exact wheel-space conversion."),
        "antiRollBarRear": sourced(0, "N/m", note="HELIX off fallback; selected torsionbar lacks exact wheel-space conversion."),
    }
    provenance.append({"target": "physics.suspension", "source": "HELIX functional fallback",
                       "disposition": "defaulted",
                       "detail": "Exact selected leaf semantics were retained, but runtime suspension remains non-functional until every wheel-space blocker is resolved."})
    counts = {"selectedLeafParts": sum(len(rows) for rows in leaves.values()),
              "excludedStructuralParts": len(excluded),
              "resolvedAxles": sum(row.get("status") != "unsupported" for row in axles.values()),
              "sourceRows": sum(sum(row.get("rowCounts", {}).values()) for row in axles.values())}
    semantics = {"variables": {name: variable_receipts[name] for name in sorted(used_variables)
                                if name in variable_receipts},
                 "axles": axles, "antiRoll": anti_roll,
                 "excludedStructuralParts": sorted(excluded, key=lambda row: (row["slotType"], row["partName"])),
                 "runtimeBlockers": runtime_blockers, "extractionComplete": extraction_complete,
                 "counts": counts}
    return suspension, semantics


def diff(kind: str, ratio: float, *, preload: float = 0, lock: float = 0, reverse: float = 0,
         torque_split: float = .5, friction: float = 0, dynamic: float = 0,
         lock_torque: float = 0, viscous_coef: float = 0,
         viscous_torque: float = 0) -> dict[str, Any]:
    return {"type": kind, "torqueSplit": torque_split, "gearRatio": ratio, "lockTorque": lock_torque,
            "viscousCoef": viscous_coef, "viscousTorque": viscous_torque, "lsdPreload": preload,
            "lsdLockCoef": lock, "lsdRevLockCoef": reverse, "friction": friction, "dynamicFriction": dynamic}


def numeric_receipt(raw: Any, variables: dict[str, Any], unit: str,
                    minimum: float | None = None, positive: bool = False) -> tuple[dict[str, Any], bool]:
    result = numeric_resolution(raw, variables)
    row: dict[str, Any] = {"raw": raw, "status": result.status, "unit": unit,
                           "variables": list(result.variables)}
    valid = result.status != "unsupported"
    if valid:
        value = float(result.value)
        row["value"] = value
        if (positive and value <= 0) or (minimum is not None and value < minimum):
            row["status"] = "unsupported"
            row["reason"] = "resolved value is outside the admitted runtime range"
            valid = False
    else:
        row["reason"] = result.reason
    return row, valid


MU_LUT_POINTS = 24
MU_LUT_FZ = [round(math.exp(math.log(100) + ((math.log(40000) - math.log(100)) * index)
                           / (MU_LUT_POINTS - 1)), 9) for index in range(MU_LUT_POINTS)]
TYRE_SHAPE_PRIOR = {"alphaPeakRad": .139626, "cxMult": 1.05, "sigmaX": .048,
                    "sigmaY": .08, "camberGain": .15, "dxOverDy": 1, "sFall": .3,
                    "rollingResistance": .013, "angularInertia": 1.3}


def lower_selected_tyres(selected: list[tuple[str, str, dict[str, Any], Path]],
                          variables: dict[str, Any], variable_receipts: dict[str, dict[str, Any]],
                          label_source: Callable[[Path], str],
                          provenance: list[dict[str, Any]]) -> tuple[list[dict[str, Any]], dict[str, Any], bool]:
    """Lower one exact selected pressure-wheel tire Package per axle.

    BeamNG supplies load-sensitivity coefficients while HELIX consumes its
    engine-wide exponential kernel as a compact LUT. Sampling uses the same
    fixed 24-knot logarithmic grid as the engine; it is not a per-vehicle fit.
    """
    candidates: dict[str, list[dict[str, Any]]] = {"front": [], "rear": []}
    for slot_name, part_name, body, path in selected:
        options = pressure_wheel_options(body)
        if not any(key in options for key in ("pressurePSI", "frictionCoef", "noLoadCoef")):
            continue
        axle = selected_part_axle(TIRE_AXLE_PATTERN, slot_name, part_name, body)
        if axle is not None:
            candidates[axle].append({"slotType": slot_name, "partName": part_name,
                                     "source": f"{label_source(path)}#{part_name}.pressureWheels",
                                     "options": options})

    field_specs = {
        "pressurePSI": ("psi", 0.0, False), "radius": ("m", None, True),
        "tireWidth": ("m", None, True), "frictionCoef": ("ratio", None, True),
        "slidingFrictionCoef": ("ratio", None, True), "noLoadCoef": ("ratio", None, True),
        "fullLoadCoef": ("ratio", None, True), "loadSensitivitySlope": ("1/N", 0.0, False),
    }
    fz = MU_LUT_FZ
    axles: dict[str, Any] = {}
    runtime: list[dict[str, Any]] = []
    blockers: list[str] = []
    used_variables: set[str] = set()
    for axle in ("front", "rear"):
        rows = candidates[axle]
        if len(rows) != 1:
            reason = f"Expected one selected {axle} tire part; found {len(rows)}."
            blockers.append(reason)
            axles[axle] = {"status": "unsupported", "reason": reason,
                           "candidates": [{key: row[key] for key in ("slotType", "partName", "source")}
                                          for row in rows]}
            continue
        candidate = rows[0]
        receipts: dict[str, Any] = {}
        complete = True
        for field, (unit, minimum, positive) in field_specs.items():
            receipt, valid = numeric_receipt(candidate["options"].get(field), variables, unit,
                                             minimum=minimum, positive=positive)
            receipts[field] = receipt
            complete = complete and valid
            used_variables.update(receipt["variables"])
            disposition = "source-literal" if receipt["status"] == "literal" else receipt["status"]
            provenance.append({"target": f"sourceSemantics.wheelsTyres.axles.{axle}.{field}",
                               "source": candidate["source"], "disposition": disposition,
                               "detail": receipt.get("reason") or
                               f"Selected {field} resolved to {receipt.get('value'):g} {unit}."})
        axle_row = {key: candidate[key] for key in ("slotType", "partName", "source")}
        axle_row.update(receipts)
        axle_row["status"] = "functional" if complete else "unsupported"
        axles[axle] = axle_row
        if not complete:
            blockers.append(f"Selected {axle} tire contains unresolved or invalid numeric semantics.")
            continue
        values = {field: float(receipt["value"]) for field, receipt in receipts.items()}
        slide_ratio = values["slidingFrictionCoef"] / values["frictionCoef"]
        if not 0 < slide_ratio <= 1:
            receipts["slidingFrictionCoef"]["status"] = "unsupported"
            receipts["slidingFrictionCoef"]["reason"] = "HELIX muLut.slideRatio must be in (0, 1]."
            axle_row["status"] = "unsupported"
            for receipt_provenance in reversed(provenance):
                if receipt_provenance["target"] == \
                        f"sourceSemantics.wheelsTyres.axles.{axle}.slidingFrictionCoef":
                    receipt_provenance["disposition"] = "unsupported"
                    receipt_provenance["detail"] = receipts["slidingFrictionCoef"]["reason"]
                    break
            blockers.append(f"Selected {axle} tire sliding/friction ratio is outside (0, 1].")
            continue
        mu = [round(values["frictionCoef"] * (values["fullLoadCoef"]
                    + (values["noLoadCoef"] - values["fullLoadCoef"])
                    * math.exp(-values["loadSensitivitySlope"] * load)), 9) for load in fz]
        runtime.append({
            **TYRE_SHAPE_PRIOR,
            "loadSensitivity": {key: values[key] for key in ("frictionCoef", "slidingFrictionCoef",
                                "noLoadCoef", "fullLoadCoef", "loadSensitivitySlope")},
            "muLut": {"fz": fz, "mu": mu,
                      "slideRatio": round(slide_ratio, 6)},
            "radius": values["radius"],
            "calibration": "prior",
        })

    extraction_complete = not blockers and len(runtime) == 2
    if extraction_complete:
        blockers.extend([
            "Selected pressurePSI is retained but the HELIX tire runtime has no pressure field.",
            "Selected tireWidth is retained but the HELIX tire runtime has no width field.",
        ])
        provenance.append({"target": "simulation.land.tyreByAxle",
                           "source": "selected JBeam pressureWheels", "disposition": "unsupported",
                           "detail": "Radius and load sensitivity use the selected source with the engine-wide exponential 24-knot LUT, but pressure and width have no runtime field; shape coefficients remain explicit priors."})
    else:
        provenance.append({"target": "simulation.land.tyreByAxle",
                           "source": "selected JBeam pressureWheels", "disposition": "unsupported",
                           "detail": " ".join(blockers)})
        fallback = {**TYRE_SHAPE_PRIOR,
                    "loadSensitivity": {"frictionCoef": 1, "slidingFrictionCoef": .85,
                    "noLoadCoef": 1.1, "fullLoadCoef": 1.1, "loadSensitivitySlope": 0},
                    "muLut": {"fz": fz, "mu": [1.1] * MU_LUT_POINTS, "slideRatio": .85},
                    "radius": .3466, "calibration": "prior"}
        runtime = [fallback, dict(fallback)]
    functional = False
    semantics = {"status": "unsupported", "extractionComplete": extraction_complete, "axles": axles,
                 "variables": {name: variable_receipts[name] for name in sorted(used_variables)
                               if name in variable_receipts},
                 "lut": {"fz": fz,
                         "formula": "frictionCoef * (fullLoadCoef + (noLoadCoef - fullLoadCoef) * exp(-loadSensitivitySlope * fz))"},
                 "runtimeBlockers": blockers}
    return runtime, semantics, functional


def lower_selected_driveline(devices: list[dict[str, Any]],
                             variables: dict[str, Any], variable_receipts: dict[str, dict[str, Any]],
                             provenance: list[dict[str, Any]]) -> tuple[dict[str, dict[str, Any]], dict[str, Any], bool, float]:
    """Trace selected devices from connected wheels to the gearbox.

    Device names are BeamNG graph identities. Duplicate names, cycles,
    disconnected halfshafts, unknown differential kinds, and runtime-unsafe
    parameters keep receipts and suppress every runtime differential. Safe but
    inexact behavior fields retain an explicitly approximate runtime.
    """
    by_name: dict[str, list[dict[str, Any]]] = {}
    for row in devices:
        by_name.setdefault(row["name"], []).append(row)
    blockers = [f"Duplicate powertrain device name {name}."
                for name, rows in sorted(by_name.items()) if len(rows) != 1]
    runtime_safe = not blockers
    unique = {name: rows[0] for name, rows in by_name.items() if len(rows) == 1}
    transmission_devices = [row for row in devices
                            if str(row.get("type", "")).lower() in TRANSMISSION_DEVICE_KINDS]
    gearbox_name = transmission_devices[0]["name"] if len(transmission_devices) == 1 else None
    gearbox_semantics = ({"status": "derived", "deviceName": transmission_devices[0]["name"],
                          "deviceType": transmission_devices[0]["type"],
                          "kind": TRANSMISSION_DEVICE_KINDS[str(transmission_devices[0]["type"]).lower()],
                          "partName": transmission_devices[0]["partName"],
                          "source": transmission_devices[0]["source"]}
                         if len(transmission_devices) == 1 else
                         {"status": "unsupported",
                          "reason": f"Expected one selected recognized transmission device; found {len(transmission_devices)}."})
    if len(transmission_devices) != 1:
        blockers.append(f"Expected one selected recognized transmission device; found {len(transmission_devices)}.")
        runtime_safe = False

    def trace(start: str) -> list[str] | None:
        path: list[str] = []
        seen: set[str] = set()
        current: str | None = start
        for _ in range(128):
            if current is None or current in seen:
                return None
            seen.add(current)
            path.append(current)
            if current == gearbox_name:
                return path
            row = unique.get(current)
            if row is None:
                return path
            upstream = row.get("inputName")
            current = upstream if isinstance(upstream, str) and upstream else None
        return None

    wheel_starts: dict[str, list[str]] = {}
    for row in devices:
        wheel = row.get("connectedWheel")
        if isinstance(wheel, str) and wheel in ("FL", "FR", "RL", "RR"):
            wheel_starts.setdefault(wheel, []).append(row["name"])
    wheel_paths: dict[str, list[str]] = {}
    for wheel in ("FL", "FR", "RL", "RR"):
        starts = wheel_starts.get(wheel, [])
        traced = trace(starts[0]) if len(starts) == 1 else None
        if traced is not None and gearbox_name is not None and gearbox_name in traced:
            wheel_paths[wheel] = traced
        elif len(starts) > 1:
            blockers.append(f"Ambiguous connected-wheel endpoint {wheel}; found {len(starts)} devices.")
            runtime_safe = False

    driven_axles: list[str] = []
    axle_wheels = {"front": ("FL", "FR"), "rear": ("RL", "RR")}
    for axle, wheels in axle_wheels.items():
        present = [wheel in wheel_paths for wheel in wheels]
        if all(present):
            driven_axles.append(axle)
        elif any(present):
            blockers.append(f"Only one selected {axle} wheel has a complete path to gearbox.")
            runtime_safe = False
    if not driven_axles:
        blockers.append("No selected axle has two complete wheel-to-gearbox paths.")
        runtime_safe = False

    differential_names = {name for name, row in unique.items() if row.get("type") == "differential"}
    common_all: set[str] = set()
    if driven_axles:
        driven_paths = [set(wheel_paths[wheel]) for axle in driven_axles for wheel in axle_wheels[axle]]
        common_all = set.intersection(*driven_paths) & differential_names
    axle_diff_names: dict[str, str] = {}
    for axle in driven_axles:
        left, right = axle_wheels[axle]
        candidates = (set(wheel_paths[left]) & set(wheel_paths[right]) & differential_names)
        if len(driven_axles) == 2:
            candidates -= common_all
        if len(candidates) != 1:
            blockers.append(f"Expected one selected {axle} axle differential; found {len(candidates)}.")
            runtime_safe = False
        else:
            axle_diff_names[axle] = next(iter(candidates))
    centre_name: str | None = None
    if len(driven_axles) == 2:
        candidates = common_all - set(axle_diff_names.values())
        if len(candidates) != 1:
            blockers.append(f"Expected one selected AWD centre differential; found {len(candidates)}.")
            runtime_safe = False
        else:
            centre_name = next(iter(candidates))

    selected_diffs = {axle: unique[name] for axle, name in axle_diff_names.items()}
    if centre_name is not None:
        selected_diffs["centre"] = unique[centre_name]

    def branch_port(diff_name: str, wheels: tuple[str, ...]) -> int | None:
        children: set[str] = set()
        ports: set[int] = set()
        for wheel in wheels:
            path = wheel_paths[wheel]
            index = path.index(diff_name)
            if index == 0:
                return None
            child_name = path[index - 1]
            child = unique.get(child_name)
            port = child.get("inputIndex") if child else None
            if not isinstance(port, int):
                return None
            children.add(child_name)
            ports.add(port)
        return next(iter(ports)) if len(children) == 1 and len(ports) == 1 else None

    runtime: dict[str, dict[str, Any]] = {}
    semantics_diffs: dict[str, Any] = {}
    used_variables: set[str] = set()
    field_specs = {
        "lockTorque": "N.m", "activeLockTorque": "N.m",
        "viscousCoef": "N.m/(rad/s)", "viscousTorque": "N.m", "lsdPreload": "N.m",
        "lsdLockCoef": "ratio", "lsdRevLockCoef": "ratio", "friction": "N.m",
        "dynamicFriction": "N.m/(rad/s)", "torqueLossCoef": "ratio",
        "defaultVirtualInertia": "kg.m^2", "speedLimitCoef": "ratio",
    }
    for location, row in selected_diffs.items():
        dtype = str(row.get("diffType", ""))
        kind = dtype.lower()
        if kind not in ("open", "locked", "viscous", "lsd"):
            blockers.append(f"Selected {location} differential type {dtype or '<missing>'} is unsupported.")
            runtime_safe = False
        fields: dict[str, Any] = {}
        values: dict[str, float] = {}
        for field, unit in field_specs.items():
            raw = row.get(field, 0)
            receipt, valid = numeric_receipt(raw, variables, unit, minimum=0)
            if field not in row and valid:
                receipt["status"] = "defaulted"
                receipt["reason"] = "BeamNG field absent; HELIX neutral value 0."
            fields[field] = receipt
            if valid:
                values[field] = float(receipt["value"])
            else:
                blockers.append(f"Selected {location} differential field {field} is unresolved.")
                runtime_safe = False
            used_variables.update(receipt["variables"])
        split_raw = row.get("diffTorqueSplit", .5)
        split, split_valid = numeric_receipt(split_raw, variables, "ratio", minimum=0)
        if "diffTorqueSplit" not in row and split_valid:
            split["status"] = "defaulted"
            split["reason"] = "BeamNG field absent; equal HELIX split 0.5."
        if split_valid and float(split["value"]) > 1:
            split["status"] = "unsupported"
            split["reason"] = "torque split must be within [0, 1]"
            split_valid = False
        fields["diffTorqueSplit"] = split
        used_variables.update(split["variables"])
        if not split_valid:
            blockers.append(f"Selected {location} differential torque split is unresolved or invalid.")
            runtime_safe = False
        if kind == "locked" and values.get("lockTorque", 0) <= 0:
            blockers.append(f"Selected {location} locked differential has no positive lockTorque.")
            runtime_safe = False
        active_controllers = [name for name in row.get("controllers", []) if "activeCenterDiff" in name]
        if values.get("activeLockTorque", 0) > 0 or active_controllers:
            blockers.append(f"Selected {location} activeLockTorque/controller cannot be represented by the HELIX differential runtime.")
        for field in ("torqueLossCoef", "defaultVirtualInertia", "speedLimitCoef"):
            if values.get(field, 0) > 0:
                blockers.append(
                    f"Selected {location} differential {field} cannot be represented by the HELIX differential runtime."
                )
        if kind == "viscous":
            exponent_raw = row.get("viscousExponent")
            exponent, exponent_valid = numeric_receipt(exponent_raw, variables, "ratio", positive=True)
            if exponent_valid and exponent.get("value") != 1:
                exponent["status"] = "unsupported"
                exponent["reason"] = "HELIX differential runtime has no viscousExponent field."
                blockers.append(f"Selected {location} viscousExponent cannot be represented exactly.")
            elif not exponent_valid:
                blockers.append(f"Selected {location} viscousExponent is unresolved.")
                runtime_safe = False
            fields["viscousExponent"] = exponent
            used_variables.update(exponent["variables"])
            if values.get("viscousCoef", 0) <= 0 or values.get("viscousTorque", 0) <= 0:
                blockers.append(f"Selected {location} viscous differential parameters must be positive.")
                runtime_safe = False
        if kind == "lsd" and any(values.get(field, -1) < 0
                                  for field in ("lsdPreload", "lsdLockCoef", "lsdRevLockCoef")):
            blockers.append(f"Selected {location} LSD parameters are invalid.")
            runtime_safe = False
        source = row["source"]
        semantics_diffs[location] = {"deviceName": row["name"], "partName": row["partName"],
                                     "source": source, "type": kind, "fields": fields,
                                     "controllers": row.get("controllers", []),
                                     "overlaySources": row.get("overlaySources", []),
                                     "overlayFieldSources": row.get("overlayFieldSources", {}),
                                     "overlayConflicts": row.get("overlayConflicts", [])}
        provenance.append({"target": f"sourceSemantics.driveline.differentials.{location}.type",
                           "source": source,
                           "disposition": "source-literal" if kind in ("open", "locked", "viscous", "lsd") else "unsupported",
                           "detail": f"Selected connected differential declares diffType {dtype or '<missing>'}."})

        ratio_raw = row.get("gearRatio", 1 if location == "centre" else None)
        ratio_receipt, ratio_valid = numeric_receipt(ratio_raw, variables, "ratio", positive=True)
        if location == "centre" and "gearRatio" not in row and ratio_valid:
            ratio_receipt["status"] = "defaulted"
            ratio_receipt["reason"] = "BeamNG centre gearRatio absent; neutral ratio 1."
        semantics_diffs[location]["gearRatio"] = ratio_receipt
        used_variables.update(ratio_receipt["variables"])
        ratio = float(ratio_receipt.get("value", 1))
        if not ratio_valid:
            blockers.append(f"Selected {location} differential gearRatio is absent or invalid.")
            runtime_safe = False

        if location == "centre":
            a_port = branch_port(row["name"], ("FL", "FR"))
            b_port = branch_port(row["name"], ("RL", "RR"))
        elif location == "front":
            a_port = branch_port(row["name"], ("FL",))
            b_port = branch_port(row["name"], ("FR",))
        else:
            a_port = branch_port(row["name"], ("RL",))
            b_port = branch_port(row["name"], ("RR",))
        semantics_diffs[location]["outputPorts"] = {"a": a_port, "b": b_port}
        if {a_port, b_port} != {1, 2}:
            blockers.append(f"Selected {location} differential output ports are missing, duplicate, or ambiguous.")
            runtime_safe = False
        if kind in ("open", "locked", "viscous", "lsd"):
            source_split = float(split.get("value", .5))
            runtime_split = source_split if a_port == 1 else round(1 - source_split, 8)
            runtime[location] = diff(kind, ratio, preload=values.get("lsdPreload", 0),
                                     lock=values.get("lsdLockCoef", 0),
                                     reverse=values.get("lsdRevLockCoef", 0), torque_split=runtime_split,
                                     friction=values.get("friction", 0),
                                     dynamic=values.get("dynamicFriction", 0),
                                     lock_torque=values.get("lockTorque", 0),
                                     viscous_coef=values.get("viscousCoef", 0),
                                     viscous_torque=values.get("viscousTorque", 0))

    functional = not blockers and len(selected_diffs) == len(driven_axles) + (1 if len(driven_axles) == 2 else 0)
    if len(selected_diffs) != len(driven_axles) + (1 if len(driven_axles) == 2 else 0):
        runtime_safe = False
    if not runtime_safe:
        runtime = {}
    if driven_axles == ["front"]:
        bias_front = 1.0
    elif driven_axles == ["rear"]:
        bias_front = 0.0
    elif centre_name and isinstance(selected_diffs.get("centre"), dict):
        centre = semantics_diffs["centre"]
        centre_split = centre["fields"]["diffTorqueSplit"]
        if centre_split["status"] != "unsupported":
            source_split = float(centre_split["value"])
            bias_front = source_split if centre["outputPorts"]["a"] == 1 else round(1 - source_split, 8)
        else:
            bias_front = .5
    else:
        bias_front = .5
    if not runtime:
        bias_front = .5
    axle_ratios = [row["gearRatio"] for location, row in semantics_diffs.items()
                   if location in ("front", "rear") and row["gearRatio"]["status"] != "unsupported"]
    unique_axle_ratios = {float(row["value"]) for row in axle_ratios}
    if len(axle_ratios) == len(driven_axles) and len(unique_axle_ratios) == 1:
        legacy_final_drive = {"raw": [row["raw"] for row in axle_ratios], "status": "derived",
                              "unit": "ratio", "variables": sorted({variable for row in axle_ratios
                                                                      for variable in row["variables"]}),
                              "value": next(iter(unique_axle_ratios))}
    else:
        legacy_final_drive = {"raw": [row.get("raw") for row in axle_ratios], "status": "unsupported",
                              "unit": "ratio", "variables": sorted({variable for row in axle_ratios
                                                                      for variable in row["variables"]}),
                              "reason": "Driven axle ratios are missing or unequal; one legacy finalDrive cannot represent them."}
    provenance.append({"target": "simulation.land.driveline.differentials",
                       "source": "selected JBeam powertrain graph",
                       "disposition": "derived" if functional else "unsupported",
                       "detail": "Wheel endpoints traced to gearbox without synthesized axles or centre differential."
                                 if functional else " ".join(blockers)})
    semantics = {"status": "functional" if functional else "unsupported",
                 "runtimeStatus": "functional" if functional else "approximate" if runtime else "unsupported",
                 "gearbox": gearbox_semantics, "transmissionDevice": gearbox_name,
                 "legacyFinalDrive": legacy_final_drive,
                 "drivenAxles": driven_axles, "wheelPaths": wheel_paths,
                 "differentials": semantics_diffs,
                 "variables": {name: variable_receipts[name] for name in sorted(used_variables)
                               if name in variable_receipts},
                 "runtimeBlockers": blockers}
    return runtime, semantics, functional, bias_front


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--source-root", required=True)
    parser.add_argument("--vehicle-root", required=True)
    parser.add_argument("--configuration", required=True)
    parser.add_argument("--vehicle-source", required=True)
    parser.add_argument("--output", required=True)
    parser.add_argument("--geometry")
    parser.add_argument("--part-index")
    parser.add_argument("--abs-controller-receipt")
    parser.add_argument("--common-root", action="append", default=[])
    parser.add_argument("--engine-override", help="JSON file {\"cylinders\": N, \"reason\": ...}: operator-declared engine facts "
                                                "(the beamngEngine Bridge input)")
    parser.add_argument("--audio-dir", help="where the mod's own engine recordings are written as PCM WAV "
                                           "(default: <output dir>/audio)")
    args = parser.parse_args()

    source_root = Path(args.source_root).resolve()
    vehicle_root = Path(args.vehicle_root).resolve()
    config_path = Path(args.configuration).resolve()
    manifest_path = Path(args.vehicle_source).resolve()
    if not vehicle_root.is_dir() or not config_path.is_file() or not manifest_path.is_file():
        fail("source, vehicle, configuration, and vehicle-source inputs must exist")
    try:
        vehicle_root.relative_to(source_root)
        config_path.relative_to(vehicle_root)
    except ValueError:
        fail("vehicle root and configuration must remain inside source root")

    source_manifest = json.loads(manifest_path.read_text())
    if source_manifest.get("schemaVersion") != SOURCE_SCHEMA:
        fail(f"vehicle source must use {SOURCE_SCHEMA}")
    candidate = vehicle_root.name
    if source_manifest.get("vehicle", {}).get("candidateId") != candidate:
        fail("vehicle-source candidate identity does not match vehicle root")
    identity = source_manifest.get("identity", {})
    plan_key, source_sha = identity.get("bridgePlanKey"), identity.get("sourceSha256")
    if not re.fullmatch(r"[0-9a-f]{64}", str(plan_key)) or not re.fullmatch(r"[0-9a-f]{64}", str(source_sha)):
        fail("vehicle-source identity requires lowercase sha256 bridgePlanKey and sourceSha256")

    config = json.loads(config_path.read_text())
    if config.get("format") != 2 or not isinstance(config.get("parts"), dict):
        fail("configuration must be BeamNG .pc format 2 with a parts object")
    if "vars" in config and not isinstance(config["vars"], dict):
        fail("configuration vars must be an object when present")
    config_model = config.get("model") or config.get("mainPartName") or candidate
    if config_model != candidate:
        fail("configuration model/mainPartName does not match vehicle-source candidate")
    source_configs = source_manifest.get("sourceFiles", {}).get("configuration")
    expected_config = source_manifest.get("configuration", {}).get("file")
    if not isinstance(source_configs, list) or len(source_configs) != 1 or expected_config != config_path.name:
        fail("vehicle-source must fingerprint this exact selected configuration")
    config_receipt = source_configs[0]
    if config_receipt.get("root", "source") != "source" or config_receipt.get("path") != rel(config_path, source_root):
        fail("vehicle-source configuration path does not match selected .pc")
    config_sha, _config_size = sha256_file(config_path)
    if config_receipt.get("sha256") != config_sha or config_receipt.get("sizeBytes") != _config_size:
        fail("vehicle-source configuration sha256 does not match selected .pc")
    config_info: dict[str, Any] = {}
    config_info_path = vehicle_root / f"info_{config_path.stem}.json"
    if config_info_path.is_file():
        receipts = source_manifest.get("sourceFiles", {}).get("configurationInfo")
        if not isinstance(receipts, list) or len(receipts) != 1:
            fail("vehicle-source must fingerprint the consumed configuration info")
        info_sha, info_size = sha256_file(config_info_path)
        if receipts[0].get("root", "source") != "source" \
                or receipts[0].get("path") != rel(config_info_path, source_root) or receipts[0].get("sha256") != info_sha \
                or receipts[0].get("sizeBytes") != info_size:
            fail("configuration info receipt does not match selected source bytes")
        config_info = json.loads(config_info_path.read_text())
    explicit = [(str(k), str(v)) for k, v in config["parts"].items() if isinstance(v, str) and v]
    explicit.sort()
    selected_names = {v for _, v in explicit}

    dependency_roots = [Path(value).resolve() for value in args.common_root]
    root_map = {"source": source_root, **{f"dependency:{index}": root
                for index, root in enumerate(dependency_roots)}}
    common_closure = identity.get("commonDependency", {}).get("closureSha256") \
        if isinstance(identity.get("commonDependency"), dict) else None

    def source_label(path: Path) -> str:
        resolved = path.resolve()
        for origin, root in root_map.items():
            try:
                portable = resolved.relative_to(root).as_posix()
                return portable if origin == "source" else f"{origin}:{portable}@sha256:{common_closure}"
            except ValueError:
                continue
        fail(f"selected source escapes admitted roots: {path}")
        return "unreachable"
    ranked_roots = [(vehicle_root, 0)]
    local_common = source_root / "vehicles" / "common"
    if local_common.is_dir():
        ranked_roots.append((local_common, 1))
    ranked_roots.extend((root / "vehicles" / "common", 2) for root in dependency_roots
                        if (root / "vehicles" / "common").is_dir())
    roots = [root for root, _ in ranked_roots]
    definitions: dict[str, tuple[dict[str, Any], Path]] = {}
    parse_failures: list[str] = []
    lua_files: list[str] = []
    parsed_files = 0
    indexed_files = 0
    producer_parsed_files = 0
    maximum_parses_per_file = 0
    selected_slot_rows: list[dict[str, Any]] = []
    if args.part_index:
        index_path = Path(args.part_index).resolve()
        if (not index_path.is_file() or index_path.is_symlink()
                or index_path.stat().st_size > MAX_SELECTED_PART_INDEX_BYTES):
            fail("selected-part index must be a bounded regular non-symlink file")
        try:
            with index_path.open("r", encoding="utf-8") as handle:
                index = json.load(handle)
        except (UnicodeDecodeError, json.JSONDecodeError):
            fail("selected-part index is not canonical UTF-8 JSON")
        actual_digest, actual_size = sha256_file(index_path)
        canonical_digest, canonical_size = canonical_json_receipt(index)
        if (actual_digest, actual_size) != (canonical_digest, canonical_size):
            fail("selected-part index bytes are not canonical deterministic JSON")
        index_receipt = source_manifest.get("configuration", {}).get("selectedPartIndex")
        if index.get("schemaVersion") != SELECTED_PART_INDEX_SCHEMA or not isinstance(index_receipt, dict) \
                or index_receipt.get("schemaVersion") != SELECTED_PART_INDEX_SCHEMA \
                or index_receipt.get("sha256") != actual_digest or index_receipt.get("sizeBytes") != actual_size:
            fail("selected-part index schema or digest does not match vehicle-source receipt")
        if index.get("candidateId") != candidate or index.get("configurationSha256") != config_sha:
            fail("selected-part index identity does not match selected vehicle/configuration")
        if index.get("configurationParts") != config.get("parts") \
                or index.get("configurationMainPartName") != config.get("mainPartName") \
                or index.get("configurationModel") != config.get("model"):
            fail("selected-part index configuration body does not match selected .pc")
        index_identity = index.get("identity")
        if not isinstance(index_identity, dict) or index_identity.get("bridgePlanKey") != plan_key \
                or index_identity.get("sourceSha256") != source_sha \
                or index_identity.get("commonDependencyClosureSha256") != common_closure:
            fail("selected-part index is not bound to this Bridge plan/source/common closure")
        indexed_config = index.get("configuration")
        if not isinstance(indexed_config, dict) or indexed_config.get("root") != "source" \
                or indexed_config.get("path") != rel(config_path, source_root) \
                or indexed_config.get("sha256") != config_sha or indexed_config.get("sizeBytes") != _config_size:
            fail("selected-part index configuration receipt does not match selected .pc bytes")
        sources = index.get("sources")
        parts = index.get("parts")
        if not isinstance(sources, list) or not isinstance(parts, list) \
                or len(sources) > MAX_INDEX_SOURCES or len(parts) > MAX_INDEX_PARTS:
            fail("selected-part index requires sources and parts arrays")
        if index_receipt.get("sourceCount") != len(sources) or index_receipt.get("partCount") != len(parts):
            fail("selected-part index receipt counts do not match its closure")
        manifest_jbeams = source_manifest.get("sourceFiles", {}).get("jbeam")
        if not isinstance(manifest_jbeams, list):
            fail("vehicle-source must fingerprint the selected source JBeam closure")
        manifest_source_receipts = {(row.get("root", "source"), row.get("path")): row
                                    for row in manifest_jbeams if isinstance(row, dict)}
        if len(manifest_source_receipts) != len(manifest_jbeams):
            fail("vehicle-source contains duplicate or invalid JBeam receipts")
        verified_sources: dict[tuple[str, str], Path] = {}
        for row in sources:
            if not isinstance(row, dict) or row.get("root") not in root_map:
                fail("selected-part index source uses an unadmitted root")
            origin, portable = row["root"], portable_index_path(row.get("path"))
            key = (origin, portable)
            if key in verified_sources:
                fail("selected-part index repeats a source receipt")
            path = confined_file(root_map[origin], portable)
            digest, size = sha256_file(path)
            if digest != row.get("sha256") or size != row.get("sizeBytes"):
                fail("selected-part index source fingerprint changed")
            if origin == "source":
                manifest_row = manifest_source_receipts.get(key)
                if manifest_row is None or manifest_row.get("sha256") != digest or manifest_row.get("sizeBytes") != size:
                    fail("selected-part index source is not bound by the vehicle-source JBeam receipts")
            verified_sources[key] = path
        selected_source_keys = {key for key in verified_sources if key[0] == "source"}
        if set(manifest_source_receipts) != selected_source_keys:
            fail("vehicle-source JBeam receipts contain files outside the selected closure")
        selected_bodies = index.get("selectedBodies")
        if not isinstance(selected_bodies, list) or len(selected_bodies) != len(set(selected_bodies)):
            fail("selected-part index selectedBodies must be a unique ordered list")
        used_sources: set[tuple[str, str]] = set()
        for row in parts:
            if not isinstance(row, dict) or not isinstance(row.get("name"), str) or not isinstance(row.get("body"), dict):
                fail("selected-part index contains an invalid part row")
            source_key = (row.get("sourceRoot"), row.get("source"))
            source_path = verified_sources.get(source_key)
            if source_path is None or row["name"] in definitions:
                fail("selected-part index contains an unknown source or duplicate part")
            definitions[row["name"]] = (row["body"], source_path)
            used_sources.add(source_key)
        if selected_bodies != [row.get("name") for row in parts] or used_sources != set(verified_sources):
            fail("selected-part index parts, selected bodies, and source receipts do not form one exact closure")
        parse_counts = index.get("parseCounts", {})
        if parse_counts and (not isinstance(parse_counts, dict) or any(value != 1 for value in parse_counts.values())):
            fail("selected-part index does not prove one parse per consumed document")
        indexed_files = len(verified_sources)
        producer_parsed_files = len(parse_counts)
        maximum_parses_per_file = max(parse_counts.values(), default=0)
        selected_slot_rows = [row for row in index.get("slotClosure", []) if isinstance(row, dict)]
        selected = [(str(row.get("slotType") or "$selected"), row["name"], row["body"],
                     verified_sources[(row["sourceRoot"], row["source"])]) for row in parts]
        closure_rows = [{"slotType": "$main", "partName": str(index.get("mainPartName")),
                         "selection": "root", "resolution": "resolved"}]
        closure_rows.extend({"slotType": str(row.get("slotType")), "partName": str(row.get("selectedPart")),
                             "selection": str(row.get("selection")), "resolution": str(row.get("resolution"))}
                            for row in index.get("slotClosure", []) if isinstance(row, dict)
                            and isinstance(row.get("slotType"), str) and isinstance(row.get("selectedPart"), str)
                            and row.get("selectedPart") not in ("", "none"))
        missing = [(str(row.get("slotType")), str(row.get("partName")))
                   for row in index.get("missing", []) if isinstance(row, dict)]
        missing.extend((row["slotType"], row["partName"]) for row in closure_rows
                       if row["resolution"] == "missing-source")
    else:
        cache = JBeamDocumentCache(source_root, dependency_roots)
        catalog, parse_failures = build_part_catalog(
            roots, cache, [rank for _, rank in ranked_roots])
        graph = resolve_part_closure(catalog, dict(explicit), str(config.get("mainPartName") or candidate))
        selected_slot_rows = graph["slotClosure"]
        for row in graph["parts"]:
            definitions[row["name"]] = (catalog.body(row["name"]), row["_sourcePath"])
        selected = [(str(row.get("slotType") or "$selected"), row["name"],
                     definitions[row["name"]][0], row["_sourcePath"])
                    for row in graph["parts"]]
        closure_rows = [{"slotType": "$main", "partName": str(graph.get("mainPartName")),
                         "selection": "root", "resolution": "resolved"}]
        closure_rows.extend({"slotType": str(row.get("slotType")), "partName": str(row.get("selectedPart")),
                             "selection": str(row.get("selection")), "resolution": str(row.get("resolution"))}
                            for row in graph["slotClosure"] if row.get("selectedPart") not in (None, "", "none"))
        missing = [(str(row.get("slotType")), str(row.get("partName"))) for row in graph["missing"]]
        parsed_files = sum(cache.parse_counts.values())
        producer_parsed_files = len(cache.parse_counts)
        maximum_parses_per_file = max(cache.parse_counts.values(), default=0)
        for root in roots:
            lua_files.extend(rel(path, source_root) for path in bounded_asset_paths(
                [root], {".lua": LUA_SCAN_LIMIT}))

    closure_rows.sort(key=lambda row: (row["slotType"], row["partName"]))
    selected_names = {part_name for _, part_name, _, _ in selected}
    selected_bodies = [body for _, _, body, _ in selected]
    if not args.part_index:
        receipts = source_manifest.get("sourceFiles", {}).get("jbeam")
        if not isinstance(receipts, list):
            fail("vehicle-source must fingerprint every consumed JBeam file")
        receipt_by_path: dict[str, dict[str, Any]] = {}
        for row in receipts:
            portable = row.get("path") if isinstance(row, dict) else None
            if not isinstance(portable, str) or portable in receipt_by_path:
                fail("vehicle-source has an invalid or duplicate JBeam receipt")
            receipt_by_path[portable] = row
        for path in sorted({path.resolve() for _, _, _, path in selected}):
            portable = rel(path, source_root)
            row = receipt_by_path.get(portable)
            digest, size = sha256_file(path)
            if row is None or row.get("sha256") != digest or row.get("sizeBytes") != size:
                fail(f"consumed JBeam receipt does not match source bytes: {portable}")
    value_index = key_multimap((part_name, body) for _, part_name, body, _ in selected)
    node_masses: dict[str, float] = {}
    for body in selected_bodies:
        for row in decode_jbeam_table(body.get("nodes")):
            node_id, node_weight = row.get("id"), row.get("nodeWeight")
            if isinstance(node_id, str) and isinstance(node_weight, (int, float)) and node_weight > 0:
                node_masses[node_id] = float(node_weight)
    source_mass = round(sum(node_masses.values()), 4)

    citation_id = "beamng-jbeam-source"
    provenance: list[dict[str, Any]] = []
    def prov(target: str, source: str, disposition: str, detail: str) -> None:
        provenance.append({"target": target, "source": source, "disposition": disposition, "detail": detail})
    for slot_name, part_name, _, path in selected:
        prov(f"build.selections.{slot_name}", source_label(path), "source-literal", part_name)
    for slot_name, part_name in missing:
        prov(f"build.selections.{slot_name}", f"{config_path.name}#parts.{slot_name}", "missing-source",
             f"Selected part {part_name} is not present in the admitted JBeam closure.")

    # Engine values come from the chosen engine plus selected ECU/internals overlays.
    engine_parts = [(n, b, p) for _, n, b, p in selected if "engine" in n.lower()]
    engine_node = [b for _, b, _ in engine_parts]
    engine_configs = [body.get("mainEngine", {}) for body in engine_node if isinstance(body.get("mainEngine"), dict)]
    torque: list[list[float]] = []
    for body in engine_configs:
        values = body.get("torque")
        if isinstance(values, list):
            for row in values[1:] if values and isinstance(values[0], list) and values[0][:2] == ["rpm", "torque"] else values:
                if isinstance(row, list) and len(row) >= 2 and all(isinstance(x, (int, float)) for x in row[:2]):
                    torque.append([float(row[0]), float(row[1])])
    torque = sorted({(x[0], x[1]) for x in torque})
    torque_curve = [[int(r) if r.is_integer() else r, int(t) if t.is_integer() else t] for r, t in torque]
    if len(torque_curve) < 2:
        torque_curve = [[800, 100], [7000, 80]]
        prov("physics.engine.torqueCurve", "HELIX functional fallback", "defaulted", "No literal torque table in selected closure.")
    else:
        prov("physics.engine.torqueCurve", source_label(engine_parts[0][2]), "source-literal", "BeamNG torque table.")
    engine_filter = lambda part: "engine" in part.lower()
    idle, idle_key = number(value_index, ["idleRPM", "idleRpm"], 800, engine_filter)
    limiter, limiter_key = number(value_index, ["revLimiterRPM", "maxRPM", "limiterRpm"], 7000, engine_filter)
    inertia, _ = number(value_index, ["inertia"], .1, engine_filter)
    friction, _ = number(value_index, ["friction"], 11.5, engine_filter)
    dyn_friction, _ = number(value_index, ["dynamicFriction"], .024, engine_filter)
    coast, _ = number(value_index, ["engineBrakeTorque"], 38, engine_filter)
    for target, key in [("idleRpm", idle_key), ("limiterRpm", limiter_key)]:
        prov(f"physics.engine.{target}", f"selected JBeam#{key}", "source-literal" if key != "HELIX-default" else "defaulted", str(key))
    peak_rpm, peak_torque = max(torque_curve, key=lambda row: row[1])
    power_points = [(r * t / 9549.296596, r) for r, t in torque_curve]
    peak_power, peak_power_rpm = max(power_points)
    published_power = float(config_info["Power"]) if isinstance(config_info.get("Power"), (int, float)) else None
    published_torque = float(config_info["Torque"]) if isinstance(config_info.get("Torque"), (int, float)) else None
    if published_power is not None:
        prov("physics.engine.peakPowerKw", f"info_{config_path.stem}.json#Power", "source-literal",
             f"Selected configuration publishes {published_power:g} kW.")
    if published_torque is not None:
        prov("physics.engine.peakTorqueNm", f"info_{config_path.stem}.json#Torque", "source-literal",
             f"Selected configuration publishes {published_torque:g} N.m.")

    def range_midpoint(value: Any, fallback: float) -> float:
        values = [float(item) for item in re.findall(r"\d+(?:\.\d+)?", str(value))]
        return sum(values) / len(values) if values else fallback

    published_power_rpm = range_midpoint(config_info.get("PowerPeakRPM"), peak_power_rpm)
    published_torque_rpm = range_midpoint(config_info.get("TorquePeakRPM"), peak_rpm)

    power_rows = selected_powertrain_devices(selected, source_label)
    engine_device = next((r for r in power_rows if r.get("type") == "combustionEngine"), {})
    transmission_kind, transmission_source, transmission_detail = selected_transmission_kind(
        power_rows, config_info)
    transmission_kind_sourced = transmission_kind is not None
    if transmission_kind_sourced:
        prov("simulation.land.driveline.gearbox.kind", transmission_source, "source-literal", transmission_detail)
    else:
        transmission_kind = "manual"
        prov("simulation.land.driveline.gearbox.kind", transmission_source, "discovered-not-lowered",
             f"{transmission_detail} HELIX emits a manual fallback without claiming gearbox coverage.")
    ratios: list[float] = []
    reverse = -3.545
    component_ratios: dict[str, float] = {}
    for value in indexed_values(value_index, "gearRatios"):
        if isinstance(value, dict):
            component_ratios.update({str(key): float(ratio) for key, ratio in value.items()
                                     if isinstance(ratio, (int, float)) and re.fullmatch(r"gearRatio_(?:R|\d+)", str(key))})
        elif isinstance(value, list):
            nums = [float(x) for x in value if isinstance(x, (int, float))]
            if len(nums) >= 2:
                ratios = [x for x in nums if x > 0]
                reverse_candidates = [x for x in nums if x < 0]
                if reverse_candidates: reverse = reverse_candidates[0]
        else:
            continue
    if component_ratios:
        ratios = [component_ratios[key] for key in sorted(component_ratios,
                  key=lambda key: int(key.removeprefix("gearRatio_")) if key.removeprefix("gearRatio_").isdigit() else 10_000)
                  if key != "gearRatio_R" and component_ratios[key] > 0]
        if "gearRatio_R" in component_ratios:
            reverse = -abs(component_ratios["gearRatio_R"])
    ratios_sourced = bool(ratios)
    ratios_derived = False
    if transmission_kind == "cvt" and not ratios:
        cvt_bodies = [body for _, _, body, _ in selected if isinstance(body.get("gearbox"), dict)]
        cvt_min = next((float(body["gearbox"]["minGearRatio"]) for body in cvt_bodies
                        if isinstance(body["gearbox"].get("minGearRatio"), (int, float))), None)
        cvt_max = next((float(body["gearbox"]["maxGearRatio"]) for body in cvt_bodies
                        if isinstance(body["gearbox"].get("maxGearRatio"), (int, float))), None)
        if cvt_min is not None and cvt_max is not None and 0 < cvt_min <= cvt_max:
            ratios = [cvt_max, cvt_min]
            ratios_derived = True
    if not ratios:
        ratios = [3.636, 2.111, 1.488, 1.088, .825]
        prov("physics.gearbox.ratios", "HELIX known-safe manual prior", "defaulted", "No literal gearRatios table found.")
    elif ratios_derived:
        prov("physics.gearbox.ratios", transmission_source, "derived",
             "CVT maxGearRatio/minGearRatio retained as runtime range endpoints; continuous-ratio behavior is not yet lowered.")
    else:
        prov("physics.gearbox.ratios", "selected JBeam#components.gearRatios", "source-literal",
             "Selected ratio component dictionaries merged by numbered gear key.")
    reverse_value, reverse_key = ((reverse, "components.gearRatios") if "gearRatio_R" in component_ratios
                                  else number(value_index, ["reverseGearRatio", "reverseRatio"], reverse))
    reverse = -abs(reverse_value)
    final_drive, fd_key = number(value_index, ["gearRatio"], 4.11, lambda part: "finaldrive" in part.lower())
    shift_delay, shift_key = number(value_index, ["transmissionShiftDelay", "shiftDelay"], .25)

    source_ref = citation_id
    selected_variables, selected_variable_receipts = selected_variable_environment(
        selected, config, config_path, source_label)
    brakes, brake_semantics, brakes_functional = lower_selected_brakes(
        selected, selected_variables, selected_variable_receipts,
        source_label, citation_id, provenance)
    abs_runtime, abs_semantics, abs_adapted = lower_selected_abs(
        selected, config_path.name, config_sha,
        Path(args.abs_controller_receipt).resolve() if args.abs_controller_receipt else None,
        source_label, provenance)
    chassis_mass = (float(config_info["Weight"])
                    if isinstance(config_info.get("Weight"), (int, float)) else
                    source_mass if source_mass > 100 else 1365.0)
    weight_distribution_front = .58
    suspension, suspension_semantics = lower_selected_suspension(
        selected, selected_variables, selected_variable_receipts, source_label,
        chassis_mass, weight_distribution_front, provenance)
    differential_runtime, driveline_semantics, differentials_functional, drive_bias_front = lower_selected_driveline(
        power_rows, selected_variables, selected_variable_receipts, provenance)
    legacy_final_drive = driveline_semantics["legacyFinalDrive"]
    if legacy_final_drive["status"] != "unsupported":
        final_drive = float(legacy_final_drive["value"])
        fd_key = "selected-driveline-final-drive"
    tyre_by_axle, tyre_semantics, tyres_functional = lower_selected_tyres(
        selected, selected_variables, selected_variable_receipts, source_label, provenance)
    turbo_parts = [(name, body, path) for _, name, body, path in selected if isinstance(body.get("turbocharger"), dict)]
    wastegate_psi = None
    for _, name, body, _ in selected:
        if "ecu" not in name.lower():
            continue
        for row in decode_jbeam_table(body.get("variables")):
            if row.get("name") == "$wastegateTarget" and isinstance(row.get("default"), (int, float)):
                wastegate_psi = float(row["default"])
    induction = None
    if str(config_info.get("Induction Type", "")).lower() == "turbo" and turbo_parts and wastegate_psi:
        turbocharger = turbo_parts[0][1]["turbocharger"]
        pressure_rows = [row for row in turbocharger.get("pressurePSI", [])
                         if isinstance(row, list) and len(row) >= 2 and isinstance(row[1], (int, float))]
        max_pressure_psi = max((float(row[1]) for row in pressure_rows), default=wastegate_psi)
        engine_def = [row for row in turbocharger.get("engineDef", [])
                      if isinstance(row, list) and len(row) >= 2 and all(isinstance(value, (int, float)) for value in row[:2])]
        reference_rpm = float(max(engine_def, key=lambda row: row[1])[0]) if engine_def else 4000
        pressure_rate = float(turbocharger.get("pressureRatePSI", 50) or 50)
        wastegate_bar = round(wastegate_psi * 0.0689475729, 6)
        max_boost_bar = round(max(max_pressure_psi, wastegate_psi) * 0.0689475729, 6)
        induction = {"kind": "turbo", "maxBoostBar": sourced(max_boost_bar, "bar", source_ref),
                     "wastegateBar": sourced(wastegate_bar, "bar", source_ref),
                     "referenceRpm": sourced(reference_rpm, "rpm", source_ref),
                     "gamma": sourced(1.8, "ratio", note="HELIX turbo response fit for the selected BeamNG pressure/engine efficiency tables."),
                     "spoolUpTime": sourced(round(wastegate_psi / max(pressure_rate, 0.001), 4), "s", source_ref),
                     "spoolDownTime": sourced(round(wastegate_psi / max(pressure_rate, 0.001) * 1.4, 4), "s", note="Selected pressure rise time multiplied by HELIX decay prior 1.4."),
                     "blowOffThresholdBar": sourced(round(wastegate_bar * .35, 6), "bar", note="35% of selected wastegate pressure."),
                     "torqueCurveIncludesBoost": False}
        prov("physics.induction", source_label(turbo_parts[0][2]),
             "source-literal", f"Turbo selected with {wastegate_psi:g} psi wastegate target.")
    elif "turbo" in str(config_info.get("Induction Type", "")).lower():
        prov("physics.induction", f"info_{config_path.stem}.json#Induction Type", "discovered-not-lowered",
             "Selected configuration declares forced induction but exact turbo and ECU literals were incomplete.")

    # Geometry can be supplied from Blender's authoritative receipt.
    geometry: dict[str, Any] = {}
    if args.geometry:
        document = json.loads(Path(args.geometry).read_text())
        geometry = document.get("HELIX_vehicle", document)
    sockets = geometry.get("sockets") if isinstance(geometry.get("sockets"), dict) else {}
    selected_tyre_radius = sum(float(row["radius"]) for row in tyre_by_axle) / len(tyre_by_axle)
    wheel_radius = float(geometry.get("wheelRadius", selected_tyre_radius))
    bounds = geometry.get("bounds", {})
    extents = bounds.get("size") if isinstance(bounds, dict) else None
    if (not isinstance(extents, list) or len(extents) != 3) and isinstance(bounds, dict):
        lo, hi = bounds.get("min"), bounds.get("max")
        if isinstance(lo, list) and isinstance(hi, list) and len(lo) == len(hi) == 3:
            extents = [abs(float(hi[i]) - float(lo[i])) for i in range(3)]
    length, width, height = (float(extents[2]), float(extents[0]), float(extents[1])) if isinstance(extents, list) and len(extents) == 3 else (4.4, 1.8, 1.45)
    wheelbase = 2.62
    track_front = track_rear = 1.53
    if all(isinstance(sockets.get(key), list) and len(sockets[key]) == 3 for key in ("wheel_lf", "wheel_rf", "wheel_lr", "wheel_rr")):
        front_z = (float(sockets["wheel_lf"][2]) + float(sockets["wheel_rf"][2])) / 2
        rear_z = (float(sockets["wheel_lr"][2]) + float(sockets["wheel_rr"][2])) / 2
        wheelbase = abs(front_z - rear_z)
        track_front = abs(float(sockets["wheel_lf"][0]) - float(sockets["wheel_rf"][0]))
        track_rear = abs(float(sockets["wheel_lr"][0]) - float(sockets["wheel_rr"][0]))
    prov("physics.chassis.geometry", args.geometry or "HELIX compact-fixture geometry prior", "derived" if args.geometry else "defaulted",
         "Blender receipt geometry." if args.geometry else "Compact semantic fixture intentionally contains no render geometry.")

    mesh_parts: list[dict[str, Any]] = []
    part_nodes: dict[str, list[str]] = {}
    for _, part_name, body, _ in selected:
        meshes = [str(row.get("mesh")) for row in decode_jbeam_table(body.get("flexbodies")) if row.get("mesh")]
        if meshes:
            part_nodes[part_name] = sorted(set(meshes))
        for node in meshes:
            role = mesh_role(node)
            mesh_parts.append({"id": slug(node), "node": node, "role": role, "consumed": role in ("door", "bonnet", "boot", "lamp")})
    by_id = {row["id"]: row for row in mesh_parts}
    mesh_parts = [by_id[key] for key in sorted(by_id)]

    panels, panel_evidence = articulation_candidates(selected, selected_slot_rows)
    for evidence in panel_evidence:
        panel_id = evidence["panel"]["id"]
        prov(f"mesh.articulation.panels.{panel_id}", f"selected JBeam part {evidence['rootPart']}", "derived",
             f"Hinge nodes {', '.join(evidence['hingeNodeIds'])} and {len(evidence['descendantParts'])} "
             "slot descendants establish rigid visual custody; dynamics remain explicit HELIX priors.")

    lamps: list[dict[str, Any]] = []
    lamp_colors = {"headlight_low": 0xFFF4D6, "headlight_high": 0xFFFFFF, "tail": 0xFF1808,
                   "brake": 0xFF0000, "reverse": 0xFFFFFF, "indicator_left": 0xFF9B19,
                   "indicator_right": 0xFF9B19, "fog_front": 0xFFF4D6}

    lamp_sources: list[tuple[str, str, dict[str, Any]]] = []
    for slot in selected_slot_rows:
        variables = slot.get("variables")
        channel = variables.get("$electric") if isinstance(variables, dict) else None
        host = slot.get("hostPart")
        if isinstance(host, str) and isinstance(channel, str):
            lamp_sources.append((host, channel, variables))
    for _, part_name, body, _ in selected:
        for prop in decode_jbeam_table(body.get("props")):
            channel = prop.get("$electric") or prop.get("electric")
            if isinstance(channel, str):
                lamp_sources.append((part_name, channel, prop))

    for part_name, channel, variables in sorted(lamp_sources, key=lambda row: (row[0], row[1], str(row[2]))):
            nodes = part_nodes.get(part_name, [])
            functions = lamp_functions(part_name, channel)
            if not functions or not nodes:
                continue
            for light in functions:
                side = lamp_side(part_name, channel)
                semantics = LAMP_NODE_SEMANTICS[light]
                candidates = [value for value in nodes if any(token in value.lower() for token in semantics)
                              and (not side or side in value.lower())]
                if not candidates:
                    continue
                node = sorted(candidates)[0]
                beam = lamp_beam(light)
                row = {"id": slug(f"{part_name}-{light}-{channel}"), "light": light, "node": node,
                       "sourceChannel": channel, "colorHex": lamp_colors[light], "intensity": 1,
                       "presentation": "emissive+beam" if beam is not None else "emissive"}
                if beam is not None:
                    row["beam"] = beam
                lamps.append(row)
    lamps.sort(key=lambda row: (row["light"], row["id"]))
    light_evidence = bool(lamps)
    if lamps:
        prov("lights.lamps", "selected JBeam flexbody nodes + $electric channels", "source-literal",
             "Each HELIX lamp binding is backed by an actual selected node and source electrical channel.")

    sound: dict[str, Any] = {}
    exhaust: dict[str, Any] = {}
    for body in engine_node:
        if isinstance(body.get("soundConfig"), dict): sound.update(body["soundConfig"])
        if isinstance(body.get("exhaustSoundConfig"), dict): exhaust.update(body["exhaustSoundConfig"])
        if isinstance(body.get("soundConfigExhaust"), dict): exhaust.update(body["soundConfigExhaust"])
    engine_sample = sound.get("sampleName")
    exhaust_sample = exhaust.get("sampleName")
    if not exhaust_sample:
        candidate_sample = next((x for x in indexed_values(value_index, "sampleName")
                                 if isinstance(x, str) and "exhaust" in x.lower()), None)
        if candidate_sample: exhaust_sample = candidate_sample
    engine_override = None
    if args.engine_override:
        try:
            engine_override = json.loads(Path(args.engine_override).read_text())
        except (OSError, ValueError) as error:
            fail(f"beamngEngine input is not readable JSON: {error}")
        if not isinstance(engine_override, dict):
            fail("beamngEngine input must be a JSON object such as {\"cylinders\": 6}")
    try:
        cylinder_evidence = derive_cylinders(
            [(name, body) for _, name, body, _ in selected], sound, exhaust, engine_override)
    except ValueError as error:
        fail(str(error))
    cylinders = cylinder_evidence["count"]
    prov("engine.cylinders", cylinder_evidence["source"],
         "defaulted" if cylinder_evidence["state"] == "defaulted" else
         "source-literal" if cylinder_evidence["state"] == "declared" else "derived",
         cylinder_evidence["detail"])
    print(f"lower-beamng: engine cylinders={cylinders} [{cylinder_evidence['state']}] {cylinder_evidence['detail']}",
          file=sys.stderr)
    audio_layers = resolve_layers(source_root, engine_sample, exhaust_sample)
    audio_bank: dict[str, Any] | None = None
    audio_unavailable: str | None = None
    if any(layer["state"] == "shipped" for layer in audio_layers.values()):
        try:
            audio_bank = extract_engine_bank(source_root, audio_layers,
                                             Path(args.audio_dir) if args.audio_dir else Path(args.output).parent / "audio",
                                             locate_ffmpeg())
        except AudioUnavailable as exc:
            audio_unavailable = str(exc)
    engine_sample = engine_sample if isinstance(engine_sample, str) and audio_layers["engine"]["state"] != "absent" else None
    exhaust_sample = exhaust_sample if isinstance(exhaust_sample, str) and audio_layers["exhaust"]["state"] != "absent" else None

    def layer_reason(layer: str) -> str:
        state, name = audio_layers[layer]["state"], audio_layers[layer]["name"]
        if audio_unavailable and state == "shipped":
            return f"source blend {name} is unusable ({audio_unavailable}); platform fallback engine"
        if state == "stock":
            return stock_reason(name)
        return f"source declares no {layer} sound sample (sampleName {name!r}); platform fallback engine"

    bank_blends = audio_bank["blends"] if audio_bank else {}
    engine_blend = audio_bank["blendNames"]["engine"] if audio_bank else None
    exhaust_blend = audio_bank["blendNames"]["exhaust"] if audio_bank else None
    exhaust_shares_engine = False
    if audio_bank and engine_blend and audio_layers["exhaust"]["state"] == "absent":
        # BeamNG mods such as the 993 disable the exhaust layer (sampleName "0") because the single
        # recording already carries the exhaust; the same set serves both HELIX ladders.
        exhaust_blend, exhaust_shares_engine = engine_blend, True

    def ladder_note(blend_name: str) -> str:
        ladders = bank_blends[blend_name]["samples"]
        rungs = [rung[1] for rung in ladders[0]]
        return (f"{len(ladders[0])} rungs {min(rungs):g}-{max(rungs):g} rpm from the mod's own recording "
                f"(sfxBlend2D {blend_name}), {len(ladders)} load row(s).")

    audio_slots = []
    for slot_name in AUDIO_SLOTS:
        row: dict[str, Any] = {"slot": slot_name, "buffers": [], "consumed": False,
                               "reason": "No selected source event was mapped to this HELIX slot."}
        if slot_name in ("engineLadder", "exhaustLadder"):
            layer = "engine" if slot_name == "engineLadder" else "exhaust"
            blend_name = engine_blend if layer == "engine" else exhaust_blend
            sample = engine_sample if layer == "engine" else exhaust_sample
            if blend_name:
                note = ladder_note(blend_name)
                if layer == "exhaust" and exhaust_shares_engine:
                    declared = audio_layers["exhaust"]["name"]
                    note = (f"The source declares no separate exhaust sample (sampleName {declared!r}); the engine "
                            "recording is one combined set used on both ladders. " + note) if declared is not None else \
                           ("The source declares no separate exhaust sample; the engine recording is one combined "
                            "set used on both ladders. " + note)
                row = {"slot": slot_name, "buffers": [f"blend:{blend_name}"], "consumed": True, "note": note}
            else:
                row = {"slot": slot_name, "buffers": [sample] if sample and not audio_bank else [],
                       "consumed": False, "reason": layer_reason(layer)}
        audio_slots.append(row)

    if audio_bank:
        bank_source = source_label(Path(audio_layers["engine"]["blend"] if audio_layers["engine"]["state"] == "shipped"
                                        else audio_layers["exhaust"]["blend"]))
        for layer, info in audio_layers.items():
            if info["state"] == "shipped":
                prov(f"audio.bank.blends.{info['name']}", source_label(info["blend"]), "source-literal",
                     "rpm ladders copied from the mod's own sfxBlend2D file; rpm values are the source's.")
        for origin in audio_bank["sources"]:
            prov(f"audio.bank.assets.{origin['asset']}", source_label(source_root / origin["sourcePath"]),
                 "derived" if origin["transcoded"] else "source-literal",
                 "Recording shipped in the mod; transcoded to 16-bit PCM WAV." if origin["transcoded"]
                 else "Recording shipped in the mod, copied byte for byte.")
        prov("audio.sampleCylinderCount", bank_source,
             "defaulted" if cylinder_evidence["state"] == "defaulted" else "derived",
             "The recorded engine's cylinder count is taken to be the selected engine's: "
             + cylinder_evidence["detail"])
    elif audio_unavailable or engine_sample or exhaust_sample:
        prov("audio.bank", "selected soundConfig sampleName", "unsupported",
             audio_unavailable or "Source uses BeamNG stock FMOD events; no recording ships in the mod, so the "
             "platform fallback engine plays.")

    engine_spec = {"torqueCurve": {"points": torque_curve}, "idleRpm": idle, "limiterRpm": limiter,
                   "revLimiterType": "soft", "inertia": inertia, "friction": friction,
                   "dynamicFriction": dyn_friction, "engineBrakeTorque": coast,
                   "burnEfficiency": {"points": [[0, .12], [.05, .27], [.4, .5], [.7, .47], [1, .34]]},
                   "drivetrainEfficiency": .85, "boostTorqueCoef": 0}
    automatic_shift = transmission_kind in ("dct", "cvt", "automatic")
    gearbox_spec = {"kind": transmission_kind, "ratios": ratios, "reverseRatio": reverse, "shiftDelay": shift_delay,
                    "inertia": .08, "auto": {"enabled": automatic_shift,
                                               "upRpm": max(idle + 1, limiter - 200), "downRpm": 2800}}
    land = {"version": 1, "driveline": {"engine": engine_spec,
            "clutch": {"inertia": .1, "capacity": peak_torque * 1.6, "freePlay": .2, "launchStartRpm": 2000, "launchTargetRpm": 2500},
            "gearbox": gearbox_spec, **differential_runtime},
            **({"abs": abs_runtime} if abs_runtime is not None else {}),
            "tyreByAxle": tyre_by_axle}

    physics = {
        "chassis": {"mass": sourced(float(config_info["Weight"]), "kg", source_ref,
          "Selected configuration info curb mass." if isinstance(config_info.get("Weight"), (int, float)) else None)
          if isinstance(config_info.get("Weight"), (int, float)) else sourced(source_mass, "kg", source_ref if source_mass > 100 else None,
          "Sum of unique selected literal JBeam nodeWeight values; missing common selections remain visible in coverage." if source_mass > 100 else "Explicit fallback pending BeamNG node-mass accumulation."),
          "weightDistributionFront": sourced(weight_distribution_front, "ratio", note="Explicit sports-sedan prior."), "centreOfMassHeight": sourced(.52, "m", note="Explicit sports-sedan prior."),
          "wheelbase": sourced(wheelbase, "m", source_ref if sockets else None, "Measured from Blender wheel sockets." if sockets else "Geometry socket derivation unavailable in compact fixture."),
          "trackFront": sourced(track_front, "m", source_ref if sockets else None, "Measured from Blender wheel sockets." if sockets else "Geometry socket derivation unavailable in compact fixture."),
          "trackRear": sourced(track_rear, "m", source_ref if sockets else None, "Measured from Blender wheel sockets." if sockets else "Geometry socket derivation unavailable in compact fixture."), "length": sourced(length, "m", None if not args.geometry else source_ref),
          "width": sourced(width, "m", None if not args.geometry else source_ref), "height": sourced(height, "m", None if not args.geometry else source_ref),
          "wheelRadius": sourced(wheel_radius, "m", None if not args.geometry else source_ref), "tyreSize": sourced("235/40R18", "text", note="Derived from selected tyre part identity where a numeric tyre row is absent."),
          "inertiaMultiplier": sourced([1, 1, 1], "ratio", note="Solid-box tensor prior.")},
        "engine": {"torqueCurve": sourced(torque_curve, "rpm,N.m", source_ref if len(torque) >= 2 else None),
          "peakPowerKw": sourced(published_power, "kW", source_ref) if published_power is not None else sourced(round(peak_power, 4), "kW", note="maximum(rpm * torque / 9549.296596) from source torque table"),
          "peakPowerRpm": sourced(published_power_rpm, "rpm", source_ref) if published_power is not None else sourced(peak_power_rpm, "rpm", note="rpm at derived peak power"),
          "peakTorqueNm": sourced(published_torque, "N.m", source_ref) if published_torque is not None else sourced(peak_torque, "N.m", note="maximum source torque table value"),
          "peakTorqueRpm": sourced(published_torque_rpm, "rpm", source_ref) if published_torque is not None else sourced(peak_rpm, "rpm", note="rpm at maximum source torque"),
          "idleRpm": sourced(idle, "rpm", source_ref if idle_key != "HELIX-default" else None), "limiterRpm": sourced(limiter, "rpm", source_ref if limiter_key != "HELIX-default" else None),
          "drivetrainEfficiency": sourced(.85, "ratio", note="Explicit HELIX driveline runtime prior."), "coastTorque": sourced(coast, "N.m", source_ref),
          "cylinders": sourced(cylinders, "count", None if cylinder_evidence["state"] in ("defaulted", "operator") else source_ref,
                               cylinder_evidence["detail"]), "strokes": 4,
          "speedLimiterKph": sourced(None, "km/h", note="No selected literal speed governor.")},
        **({"induction": induction} if induction else {}),
        "gearbox": {"ratios": sourced(ratios, "ratio", source_ref if ratios_sourced else None), "reverseRatio": sourced(reverse, "ratio", source_ref if reverse_key != "HELIX-default" else None),
          "finalDrive": sourced(final_drive, "ratio", source_ref if fd_key != "HELIX-default" else None), "shiftTime": sourced(shift_delay, "s", source_ref if shift_key != "HELIX-default" else None),
          "autoUpRpm": sourced(max(idle + 1, limiter - 200), "rpm", note="HELIX automatic shift prior; ignored when the selected transmission is manual."), "autoDownRpm": sourced(2800, "rpm", note="HELIX automatic shift prior; ignored when the selected transmission is manual.")},
        "driveBiasFront": sourced(drive_bias_front, "ratio", source_ref if differentials_functional else None,
                                   "Derived from selected driven-axle topology and centre rear torque split."
                                   if differentials_functional else
                                   "Neutral fallback because selected driveline topology is unsupported."),
        "brakes": brakes,
        "aero": {"dragCoefficient": sourced(.32, "ratio", note="Explicit sports-sedan prior."), "frontalArea": sourced(2.2, "m2", note="width*height*shape factor prior."),
          "airDensity": sourced(1.225, "kg/m3", note="ISA sea-level standard."), "downforceCoefficient": sourced(0, "ratio", note="No selected literal aerodynamic coefficient.")},
        "grip": {"peak": sourced(1.1, "ratio", note="HELIX tyre-model prior."), "sliding": sourced(.85, "ratio", note="HELIX tyre-model prior."),
          "lateralMultiplier": sourced(1, "ratio", note="HELIX tyre-model prior."), "biasFront": sourced(.5, "ratio", note="Neutral prior."),
          "loadSensitivityExponent": sourced(.85, "ratio", note="HELIX tyre-model prior.")},
        "suspension": suspension,
        "steering": {"roadWheelLockDeg": sourced(34, "deg", note="Steering-wheel 510 degree source value needs rack ratio; road-wheel prior retained."),
          "rackTime": sourced(.8, "s", note="Derived from selected steering in/out rate."), "speedSensitivity": sourced([[0, 1], [50, .45]], "m/s,ratio", note="HELIX steering assist prior.")},
        "linearDamping": sourced(.02, "ratio", note="HELIX solver stability prior."), "angularDamping": sourced(.08, "ratio", note="HELIX solver stability prior.")}

    # Bridge materializes one canonical GLB today. Do not advertise planned
    # optimization targets as selectable artifacts until the optimizer has
    # actually sealed them into the package.
    renditions = [{"id": "source", "kind": "source", "triangleBudget": 500000, "textureMaxDimension": 4096}]
    tiers = {
      "minimal": {"renditionId":"source","interior":"hidden","materialLayers":"base","lightBeams":False,"physicalPanels":False,"detachableParts":False},
      "low": {"renditionId":"source","interior":"simplified","materialLayers":"base","lightBeams":False,"physicalPanels":False,"detachableParts":False},
      "medium": {"renditionId":"source","interior":"simplified","materialLayers":"dynamic","lightBeams":True,"physicalPanels":True,"detachableParts":False},
      "high": {"renditionId":"source","interior":"full","materialLayers":"full","lightBeams":True,"physicalPanels":True,"detachableParts":False},
      "ultra": {"renditionId":"source","interior":"full","materialLayers":"full","lightBeams":True,"physicalPanels":True,"detachableParts":False},
    }
    package_id = f"beamng-{slug(candidate)}-{slug(config_path.stem)}"
    package_uuid = stable_uuid(f"vehicle-package:{plan_key}:{source_sha}:{candidate}:{config_path.name}")
    top_speed_raw = config_info.get("Top Speed")
    top_speed_kph = float(top_speed_raw) * 3.6 if isinstance(top_speed_raw, (int, float)) and top_speed_raw < 120 else top_speed_raw
    braking_raw = config_info.get("60-0 mph")
    braking_m = float(braking_raw) * .3048 if isinstance(braking_raw, (int, float)) and braking_raw > 80 else braking_raw
    target_specs = {
      "zeroToSixtyMphS": (config_info.get("0-60 mph"), 7.0, "s"),
      "zeroToHundredKphS": (config_info.get("0-100 km/h"), 7.5, "s"),
      "quarterMileS": (config_info.get("Drag Times", {}).get("time_1_4") if isinstance(config_info.get("Drag Times"), dict) else None, 15.0, "s"),
      "topSpeedKph": (top_speed_kph, 220, "km/h"), "ungovernedTopSpeedKph": (top_speed_kph, 220, "km/h"),
      "lateralG": (None, 1.0, "g"), "brakingSixtyToZeroM": (braking_m, 36, "m"),
    }
    vehicle_package = {"schemaVersion": "helix.vehicle-package/2", "packageVersion": 2, "id": package_id,
      "displayName": f"{candidate} / {config_path.stem}", "years": "source-defined", "provenance": {"distributable": False,
      "note": "Source-local BeamNG lowering. Publication remains gated until imported assets and source policy are resolved."},
      "citations": [{"id": citation_id, "title": f"BeamNG source closure for {candidate}/{config_path.name}", "publisher": "BeamNG source import",
                       "kind": "measured-fixture", "note": f"bridgePlanKey={plan_key}; sourceSha256={source_sha}"}],
      "mesh": {"source": "fixture", "ref": f"{candidate}.glb", "classId": "car", "sockets": sockets, "wheelVisuals": "author-static",
               "parts": mesh_parts, "visual": {"format": 1, "renditions": renditions, "tiers": tiers},
               "articulation": {"format": 1, "panels": panels}},
      "physics": physics, "simulation": {"format": 1, "fixedStepHz": 60, "qualityInvariant": True, "land": land},
      "targets": {name: (sourced(float(raw), unit, source_ref) if isinstance(raw, (int, float))
                           else sourced(fallback, unit, note="Provisional functional acceptance target; no BeamNG literal supplied.")) | {"tolerance": .35}
                  for name, (raw, fallback, unit) in target_specs.items()},
      "audio": {"bankId": package_id, "sampleCylinderCount": cylinders, "strokes": 4,
                  **({"engineBlend": engine_blend} if engine_blend else {"engineBlend": engine_sample} if engine_sample and not audio_bank else {}),
                  **({"exhaustBlend": exhaust_blend} if exhaust_blend else {"exhaustBlend": exhaust_sample} if exhaust_sample and not audio_bank else {}),
                  **({"bank": {"blends": audio_bank["blends"], "assets": audio_bank["assets"]}} if audio_bank else {}),
                  "slots": audio_slots, "engineGainDb": float(sound.get("mainGain", 0) or 0), "exhaustGainDb": float(exhaust.get("mainGain", 0) or 0),
                  "minLoadMix": float(sound.get("minLoadMix", 0) or 0), "maxLoadMix": float(sound.get("maxLoadMix", 1) or 1), "muffling": float(sound.get("intakeMuffling", 0) or 0)},
      "lights": {"lamps": lamps, "indicatorHz": 1.5, "decelBrakeLightThreshold": 4},
      "vfx": [{"slot": name, "anchors": ["exhaust"] if name == "exhaustSmoke" else [], "consumed": False,
               "reason": "Source event retained; no portable BeamNG particle asset is lowered."}
              for name in ("exhaustSmoke", "tyreMarks", "tyreSmoke", "backfireFlame", "brakeGlow", "dust")]}

    addon_records = []
    add_on_selections = sorted({(row["slotType"], row["partName"]) for row in closure_rows if row["slotType"] != "$main"})
    for slot_name, part_name in add_on_selections:
        found = definitions.get(part_name)
        nodes = part_nodes.get(part_name, [])
        mapped_slot = canonical_addon_slot(slot_name, candidate)
        schema_compatible = mapped_slot is not None
        runtime_slot = mapped_slot or slot_name
        add_on = {"id": stable_uuid(f"addon:{plan_key}:{candidate}:{slot_name}:{part_name}"), "kind": "add_on", "version": "1",
                  "fits": {"slotType": runtime_slot, "requires": {"sockets": [], "paths": [], "pointers": [], "nodes": [], "skeleton": None}},
                  "ops": [{"v": "mount", "row": {"type": "articulator", "id": slug(part_name),
                           "sourcePart": part_name, "sourceSlotType": slot_name, "nodes": nodes}}]}
        executable_visual = bool(schema_compatible and found and nodes)
        addon_records.append({"slotType": runtime_slot, "sourceSlotType": slot_name, "partName": part_name, "source": source_label(found[1]) if found else f"{config_path.name}#parts.{slot_name}",
                            "schemaCompatible": schema_compatible, "runtimeCompatible": executable_visual,
                            "compatibilityScope": "visual" if executable_visual else "source-record-only", "package": add_on,
                            "provenance": {"disposition": "source-literal" if found else "missing-source",
                                           "note": "Stable source selection identity. runtimeCompatible means this record carries selected visual nodes in a known HELIX slot; unknown or base-build-only source parts remain explicit but are not claimed equip-ready."}})

    build = {"schemaVersion": "helix.vehicle-build-source/1", "id": stable_uuid(f"build:{plan_key}:{config_sha}"),
             "vehiclePackageId": package_uuid, "vehiclePackageSourceId": package_id,
             "configuration": {"file": config_path.name, "sha256": config_sha, "format": 2},
             "selections": [{"slotType": slot_name, "partName": part_name,
                              "addOnPackageId": stable_uuid(f"addon:{plan_key}:{candidate}:{slot_name}:{part_name}"),
                             "resolution": "resolved" if part_name in definitions else "missing-source"}
                             for slot_name, part_name in explicit],
             "resolvedClosure": closure_rows,
             "continuumLowering": {"status": "requires-publication-refs", "consumer": "createPrivateBuildDraft -> freezeBuildDraft",
                                    "note": "Publisher replaces source identities with immutable Continuum Package/CID refs; this compiler never invents them."}}

    controllers = sorted({str(row.get("fileName")) for _, _, body, _ in selected
                          for row in decode_jbeam_table(body.get("controller")) if row.get("fileName")})
    source_semantics = {
      "mass": {"uniqueNodes": len(node_masses), "selectedNodeMassKg": source_mass},
      "seats": sorted(name for name in selected_names if "seat" in name.lower()),
      "cameras": [{"partName": name, "section": section, "rows": decode_jbeam_table(body.get(section))}
                  for _, name, body, _ in selected for section in ("cameraChase", "cameraExternal", "camerasInternal")
                  if isinstance(body.get(section), list)],
      "brakes": {"selectedParts": sorted(name for name in selected_names if "brake" in name.lower()),
                  "sourceExpressions": sorted({str(row.get("brakeTorque", {}).get("raw"))
                                               for row in brake_semantics["axles"].values()
                                               if isinstance(row, dict) and isinstance(row.get("brakeTorque"), dict)
                                               and row["brakeTorque"].get("raw") is not None}),
                  **brake_semantics},
      "suspension": suspension_semantics,
      "driveline": driveline_semantics,
      "wheelsTyres": {"selectedParts": sorted(name for name in selected_names if any(token in name.lower() for token in ("wheel", "rim", "tire", "tyre"))),
                       **tyre_semantics},
      "electrics": sorted({str(value) for value in indexed_values(value_index, "electricsName") + indexed_values(value_index, "$electric")}),
      "audioEvents": sorted({str(value) for value in indexed_values(value_index, "sampleName") + indexed_values(value_index, "deformSound")}),
      "openableControllers": [name for name in controllers if name == "advancedCouplerControl"],
      "controllers": {"abs": abs_semantics},
    }
    abs_capability_source = [
        abs_semantics["activation"]["source"],
        f"{abs_semantics['sourceModule']['path']}@sha256:{abs_semantics['sourceModule']['sha256']}",
    ] if abs_adapted else [
        row.get("source", f"{row.get('partName', 'unknown')}#{row.get('field', 'unknown')}")
        for row in abs_semantics.get("activationCandidates", [])
    ] or ["selected JBeam ABS controller shape"]
    capabilities = [
      {"capability": "beamng.controller.abs", "disposition": "derived" if abs_adapted else "unsupported",
       "source": abs_capability_source,
       "note": ("One fingerprinted BeamNG wheel-core ABS shape is statically projected into HELIX AbsSpec; raw Lua is never executed."
                if abs_adapted else abs_semantics["reason"])},
      {"capability": "beamng.controller", "disposition": "unsupported", "source": controllers or ["selected JBeam controller tables"],
       "note": "Controller declarations outside explicitly versioned static adapters remain unsupported and auditable."},
      {"capability": "beamng.lua", "disposition": "unsupported", "source": sorted(lua_files) or ["source closure scan: no Lua file selected"],
       "note": "Raw BeamNG Lua is never executed or translated."},
      {"capability": "softbody", "disposition": "out-of-scope", "source": ["selected JBeam nodes/beams/triangles"],
       "note": "Rigid mass, sockets, tyres, and articulation are lowered; deformation is not."},
      {"capability": "fluids", "disposition": "out-of-scope", "source": ["selected JBeam energy and thermal declarations"],
       "note": "Fuel/oil/coolant simulation is intentionally outside this contract."},
      {"capability": "detailed-damage", "disposition": "out-of-scope", "source": ["selected JBeam break/deform groups"],
       "note": "Hinge break groups are retained only as future detachment eligibility; no production tier enables detachment."},
    ]
    prov("runtime.controllers", "selected JBeam controller tables", "unsupported",
         f"{len(controllers)} controller types retained in capability ledger; the ABS subset is governed by its separate static adapter receipt.")
    prov("runtime.softbody", "selected JBeam nodes/beams/triangles", "out-of-scope", "Not emitted into runtime contract.")
    prov("runtime.fluids", "selected JBeam energy/thermal sections", "out-of-scope", "Not emitted into runtime contract.")
    prov("mesh.visual.tiers", "HELIX engine fidelity contract", "defaulted", "Presentation-only policy; simulation and identity are invariant.")

    provenance.sort(key=lambda row: (row["target"], row["source"], row["disposition"], row["detail"]))
    literal_count = sum(row["disposition"] == "source-literal" for row in provenance)
    resolved_count = sum(part_name in definitions for _, part_name in explicit)
    turbo_declared = "turbo" in str(config_info.get("Induction Type", "")).lower()
    future_detachable_panels = sorted(evidence["panel"]["id"] for evidence in panel_evidence
                                      if evidence["hingeBreakGroups"])
    functional_domains = {
        "geometrySockets": bool(sockets),
        "engine": bool(engine_parts and len(torque) >= 2 and (not turbo_declared or induction is not None)),
        "gearbox": ratios_sourced and transmission_kind_sourced,
        "differentials": differentials_functional,
        "brakes": brakes_functional,
        "abs": abs_adapted and abs_semantics.get("parity") == "functional",
        "suspension": False,
        "wheelsTyres": tyres_functional,
        "seatsCameras": any(str(name).startswith("seat") for name in sockets),
        "lightsElectrics": light_evidence,
        "audio": bool(engine_sample or exhaust_sample),
        "rigidArticulation": bool(panels),
        "rigidDetachment": False,
    }
    output = {"schemaVersion": SCHEMA,
              "identity": {"bridgePlanKey": plan_key, "sourceSha256": source_sha, "candidateId": candidate,
                           "configurationSha256": config_sha, "vehiclePackageId": package_uuid},
              "vehiclePackage": vehicle_package,
              "addOnPackages": {"schemaVersion": "helix.vehicle-addon-packages/1", "records": addon_records},
              "build": build, "sourceSemantics": source_semantics, "capabilities": capabilities, "provenance": provenance,
              "coverage": {"explicitSelections": len(explicit), "resolvedSelections": resolved_count,
                           "missingExplicitSelections": len(explicit) - resolved_count,
                           "resolvedClosureParts": len(selected), "missingSelections": len(missing),
                           "resolvedSelectionPercent": round(100 * resolved_count / max(1, len(explicit)), 2),
                           "resolvedClosurePercent": round(100 * len(selected) / max(1, len(selected) + len(missing)), 2),
                           "sourceLiteralPercent": round(100 * literal_count / max(1, len(provenance)), 2),
                           "suspensionProvenance": {
                               disposition: sum(row["disposition"] == disposition
                                                and (row["target"].startswith("physics.suspension")
                                                     or row["target"].startswith("sourceSemantics.suspension"))
                                                for row in provenance)
                               for disposition in ("source-literal", "derived", "defaulted", "unsupported")
                           },
                           "functionalDomains": functional_domains,
                           "futureEligibility": {"rigidDetachment": {
                               "eligiblePanelIds": future_detachable_panels,
                               "productionEnabled": False,
                           }},
                           "jbeamParse": {"mode": "selected-part-index" if args.part_index else "fallback-cache",
                                          "parsedFiles": parsed_files, "indexedFiles": indexed_files,
                                          "producerParsedFiles": producer_parsed_files,
                                          "maximumParsesPerFile": maximum_parses_per_file},
                           "parseFailures": parse_failures}}
    out = Path(args.output)
    out.parent.mkdir(parents=True, exist_ok=True)
    out.write_text(json.dumps(output, indent=2, sort_keys=True, separators=(",", ": ")) + "\n")


if __name__ == "__main__":
    try:
        main()
    except Exception as exc:
        print(f"BeamNG functional lowering refused: {exc}", file=sys.stderr)
        raise SystemExit(2)
