"""A BeamNG vehicle mod's whole sound set -> HELIX engine ladders and slots.

What a mod can name, and where it comes from:

  engine ladders   ``soundConfig.sampleName`` / ``soundConfigExhaust.sampleName`` -> ``art/sound/blends/<name>.sfxBlend2D.json``
                   in the mod (its own recordings), else the game's stock blend in ``content/art_sound.zip`` with its
                   FLAC ladder in ``content/audio.zip`` (``--beamng-root``)
  one-shots        engine fields (``starterSample``, ``shutOffSampleEngine``, ``instant/sustained/shiftAfterFireSound``),
                   ``turbocharger`` (``whineLoopEvent``, ``bovSoundFileName``), gearbox (``gearWhineInputEvent``),
                   ``beepLoopName``, ``soundscape`` rows (``horn``, ``indLoop1``, ``handbrakeEngaging`` ...)
                   -> a file the mod ships (``vehicles/<id>/sounds/x.ogg``), or a stock FMOD event (``event:>A>B>C``)
                   resolved in the game's FMOD banks when ``--beamng-root`` is given
  loose files      ``art/sound/**`` and ``vehicles/**/sounds/**`` recordings no field names, classified by file name

Only bytes the mod or the game ships are used. A slot nothing provides stays empty with the reason (for a stock event
that cannot be resolved: exactly which event is needed).
"""
from __future__ import annotations

import hashlib
import math
import re
import shutil
import zipfile
from pathlib import Path
from typing import Any

import beamng_audio
from beamng_engine import derive_cylinders
from beamng_jbeam import (JBeamDocumentCache, bounded_asset_paths, build_part_catalog, decode_jbeam_table,
                          parse_jbeam_text, preselect_configuration, resolve_part_closure)
from sim_audio import exterior_rank, normalize_wav, sha256_file, slot_for_name, staged_name

AUDIO_EXTENSIONS = {".wav", ".ogg", ".flac", ".mp3"}
MAX_ZIP_MEMBERS = 60_000
MAX_ZIP_BYTES = 6 * 1024 * 1024 * 1024
KEEP_IN_ZIP = re.compile(r"\.(jbeam|pc|json|wav|ogg|flac|mp3)$", re.I)

# Engine-device / powertrain fields -> (slot, preference: lower wins between fields filling one slot).
FIELD_SLOTS: dict[str, tuple[str, int]] = {
    "starterSample": ("startup", 0), "starterSampleExhaust": ("startup", 1),
    "shutOffSampleEngine": ("shutdown", 0), "shutOffSampleExhaust": ("shutdown", 1),
    "instantAfterFireSound": ("backfire", 0), "sustainedAfterFireSound": ("backfire", 1),
    "shiftAfterFireSound": ("backfire", 2),
    "bovSoundFileName": ("blowOff", 0),
    "gearWhineInputEvent": ("transmissionWhine", 0), "gearWhineOutputEvent": ("transmissionWhine", 1),
    "beepLoopName": ("reverseBeep", 0),
}
# ``whineLoopEvent`` means the turbo whine inside a ``turbocharger`` section; a supercharger whine has no HELIX slot.
SECTION_FIELDS = {("turbocharger", "whineLoopEvent"): ("turboSpool", 0)}
UNMAPPED_FIELDS = {"hissLoopEvent": "turbo hiss (the runtime synthesises hiss; no slot carries a recording)",
                   "pumpLoopEvent": "no HELIX slot", "whineLoopEvent": "supercharger whine: no HELIX slot"}
# Coupler/lever/beam fields whose slot depends on the event they name.
EVENT_FIELDS: dict[str, tuple[tuple[str, str, int], ...]] = {
    "detachSoundEvent": ((r">Latches>Door>|/Latches/Door/", "doorOpen", 0),),
    "attachSoundEvent": ((r">Latches>Door>|/Latches/Door/", "doorClose", 0),),
    "shiftSoundEventSequentialGearUp": ((r".", "shiftUp", 0),),
    "shiftSoundEventSequentialGearDown": ((r".", "shiftDown", 0),),
    "shiftSoundEventHPatternGearIn": ((r".", "shiftUp", 1),),
    "shiftSoundEventHPatternGearOut": ((r".", "shiftDown", 1),),
    "shiftSoundEventSingleAxisLever": ((r".", "shiftUp", 2),),
    "soundFile": ((r">Suspension>|/Suspension/|spring|suspension", "suspension", 0),),
}
# What BeamNG plays when no selected part names a sound (the game's Lua defaults), per slot:
# (event, prefer sample regex, avoid sample regex, evidence). Used only with --beamng-root.
BASE_GAME_DEFAULTS: dict[str, tuple[str, str | None, str | None, str]] = {
    "startup": ("event:/Engine/Starter/Old_V2", r"starter_start|_start\d*$", r"loop",
                "lua/vehicle/powertrain/combustionEngine.lua: starterSample or event:>Engine>Starter>Old_V2"),
    "backfire": ("event:/Vehicle/Afterfire/01_Single_EQ1", None, None,
                 "lua/vehicle/powertrain/combustionEngineThermals.lua: instantAfterFireSound default"),
    "transmissionWhine": ("event:/Vehicle/Transmission/helical_01/twine_in", None, None,
                          "lua/vehicle/powertrain/manualGearbox.lua: gearWhineInputEvent default"),
    "shiftUp": ("event:/Vehicle/Interior/Gearshift/manual_modern_01_in", None, None,
                "lua/vehicle/controller/propAnimation/hPattern.lua: shiftSoundEventHPatternGearIn default"),
    "shiftDown": ("event:/Vehicle/Interior/Gearshift/manual_modern_01_out", None, None,
                  "lua/vehicle/controller/propAnimation/hPattern.lua: shiftSoundEventHPatternGearOut default"),
    "tyreRollSlow": ("event:/Surfaces/roll_rigid_v2", r"tarm_roll_03a?_m_slow|tarm_roll.*slow", r"wet|heavy|ice|treadbig|barrel",
                     "lua/vehicle/sounds.lua: rigidRoll = event:>Surfaces>roll_rigid_v2 (asphalt, slow)"),
    "tyreRollFast": ("event:/Surfaces/roll_rigid_v2", r"tarm_roll_03a?_m_fast|tarm_roll.*fast", r"wet|heavy|ice|treadbig|barrel",
                     "lua/vehicle/sounds.lua: rigidRoll = event:>Surfaces>roll_rigid_v2 (asphalt, fast)"),
    "impactLight": ("event:/Destruction/Vehicle/vehicle_part_impact", r"_sml", None,
                    "lua/vehicle/sounds.lua: impactGenericEvent = event:>Destruction>Vehicle>vehicle_part_impact (small)"),
    "impactMedium": ("event:/Destruction/Vehicle/vehicle_part_impact", r"_med", None,
                     "lua/vehicle/sounds.lua: impactGenericEvent (medium)"),
    "impactHeavy": ("event:/Destruction/Vehicle/vehicle_part_impact", r"_lrg", None,
                    "lua/vehicle/sounds.lua: impactGenericEvent (large)"),
    "suspension": ("event:/Vehicle/Suspension/car_modn_med_01/spring_compress_01", None, None,
                   "no Lua default; BeamNG's modern passenger-car spring set (vehicles/common beamSounds)"),
    "doorOpen": ("event:/Vehicle/Latches/Door/modern_03_open", None, None,
                 "vehicles/common door couplers: detachSoundEvent event:>Vehicle>Latches>Door>modern_03_open"),
    "doorClose": ("event:/Vehicle/Latches/Door/modern_03_close", r"high", None,
                  "vehicles/common door couplers: attachSoundEvent event:>Vehicle>Latches>Door>modern_03_close"),
    "handbrake": ("event:/Vehicle/Interior/Handbrake_Ratchet/Ratchet_01_Ratchet", None, None,
                  "vehicles/common soundscape handbrake ratchet"),
    "indicatorTick": ("event:/Vehicle/Interior/Indicator/AU3_Click", None, None,
                      "vehicles/common soundscape.jbeam soundscape_indicator1: indLoop1 event:>Vehicle>Interior>Indicator>AU3_Click"),
    "turboSpool": ("event:/Vehicle/Forced_Induction/Turbo_01/turbo_spin", None, None,
                   "turbocharger whineLoopEvent default set (Turbo_01)"),
    "blowOff": ("event:/Vehicle/Forced_Induction/Turbo_01/turbo_bov", None, None,
                "turbocharger bovSoundFileName default set (Turbo_01)"),
}
TURBO_ONLY = {"turboSpool", "blowOff"}
GEARBOX_KINDS = {"manualgearbox": "manual", "automaticgearbox": "automatic", "dctgearbox": "dct",
                 "cvtgearbox": "cvt", "sequentialgearbox": "sequential"}


FMOD_PITCH_SEMITONES = 24.0


def automation_ratio(curve: list[tuple[float, float]], x: float) -> float:
    """Playback ratio FMOD applies at parameter value ``x``: the curve's normalised pitch (-1..1 = -24..+24 st)."""
    points = sorted(curve)
    if x <= points[0][0]:
        y = points[0][1]
    elif x >= points[-1][0]:
        y = points[-1][1]
    else:
        y = next(y0 + (y1 - y0) * (x - x0) / (x1 - x0) for (x0, y0), (x1, y1) in zip(points, points[1:]) if x0 <= x <= x1)
    return 2.0 ** (y * FMOD_PITCH_SEMITONES / 12.0)


def event_ladder(stock: Any, event: str, rpms: list[float], staging: Path, name: str, layer: int = 0) -> tuple[dict[str, Any] | None, str | None]:
    """An rpm ladder from a stock FMOD event that plays one loop re-pitched by its RPM parameter (BeamNG's electric
    motors: ``ElectricMotor_02`` -> ``event:/Engine/Bands/Real/electric_eng_02``, a blend with no rung samples).

    Each rung is the event's own recording played at the rate the event's pitch automation gives it at that rpm
    (``fmod-pitch-automation-varispeed``), so the HELIX ladder sounds as BeamNG plays the event; the runtime
    re-pitches proportionally between rungs. ``layer`` picks one of an event's simultaneous loops (in name order).
    """
    from sim_audio import read_wav_header, sha256_file, staged_name, varispeed
    guid = stock.lower.get(event.lower())
    info = stock.events.get(guid) if guid else None
    if info is None:
        return None, f"BeamNG stock event {event} is not in the game's banks"
    if not info.pitch_curve:
        return None, f"BeamNG stock event {event} carries no RPM pitch automation to build a ladder from"
    takes = sorted(stock.samples(event), key=lambda bs: bs[1].name.lower())
    if layer >= len(takes):
        return None, None
    emitted = stock.extract(event, "engineLadder", f"^{re.escape(takes[layer][1].name)}$")
    if emitted is None:
        return None, f"BeamNG stock event {event} resolves to no recording"
    source = Path(emitted["wav"])
    rows: list[dict[str, Any]] = []
    for rpm in rpms:
        ratio = automation_ratio(info.pitch_curve, rpm)
        target = staging / f"evrung-{layer}-{int(rpm)}.wav"
        transform = varispeed(source, target, ratio)
        transform.update({"kind": "fmod-pitch-automation-varispeed", "rpm": rpm, "parameter": info.pitch_parameter or "RPM",
                          "curve": [list(p) for p in info.pitch_curve], "semitoneRange": FMOD_PITCH_SEMITONES})
        final = staging / staged_name(f"{takes[layer][1].name}_{int(rpm)}rpm", sha256_file(target))
        if not final.exists():
            target.replace(final)
        provenance = dict(emitted["provenance"])
        provenance["transforms"] = [*provenance.get("transforms", []), transform]
        provenance["rungRpm"] = rpm
        rows.append({"wav": str(final), "rpm": int(round(rpm)), "provenance": provenance})
    others = [t[1].name for i, t in enumerate(takes) if i != layer]
    ladder = {"name": name, "eventName": event, "rows": [rows, rows], "motor": True,
              "provenance": {**{k: v for k, v in emitted["provenance"].items() if k not in ("transforms",)},
                             "pitchAutomation": {"parameter": info.pitch_parameter or "RPM", "curve": [list(p) for p in info.pitch_curve],
                                                 "semitoneRange": FMOD_PITCH_SEMITONES}},
              "note": (f"motor ladder from {event} ('{takes[layer][1].name}'): {len(rows)} rungs {int(rpms[0])}-{int(rpms[-1])} rpm, "
                       f"each the recording at the rate the event's {info.pitch_parameter or 'RPM'} pitch automation plays it"
                       + (f"; the event's other loop(s) {others} play on the other layer" if others else ""))}
    return ladder, None


# The HELIX audio block's gain / load-mix / muffling fields, read the way lower-beamng.py reads them for a whole car.
MIX_FIELDS = (("engineGainDb", "sound", "mainGain"), ("exhaustGainDb", "exhaust", "mainGain"),
              ("minLoadMix", "sound", "minLoadMix"), ("maxLoadMix", "sound", "maxLoadMix"), ("muffling", "sound", "intakeMuffling"))


def mix_from_sound_config(sound: dict[str, Any], exhaust: dict[str, Any]) -> dict[str, Any]:
    """``{field: {"value", "from"}}`` for each mix field the selected parts' soundConfig / soundConfigExhaust state."""
    out: dict[str, Any] = {}
    for field, which, key in MIX_FIELDS:
        value = (sound if which == "sound" else exhaust).get(key)
        if isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(float(value)):
            out[field] = {"value": float(value), "from": f"{'soundConfig' if which == 'sound' else 'soundConfigExhaust'}.{key}"}
    return out


def motor_rungs(max_rpm: float, step: float = 2000.0) -> list[float]:
    top = max(2000.0, float(max_rpm))
    rungs = [1000.0, *[float(r) for r in range(2000, int(top), int(step))], top]
    return sorted(set(rungs))


def extract_exact(stock: Any, event: str, slot: str | None, sample: str | None) -> dict[str, Any]:
    """One stock event's take: the named ``sample`` exactly, else the slot's default choice."""
    try:
        if sample:
            names = [s.name for _, s in stock.samples(event)]
            if sample not in names:
                return {"reason": f"BeamNG stock event {event} has no take {sample!r} (it has {', '.join(names[:12])})"}
            emitted = stock.extract(event, slot, f"^{re.escape(sample)}$", None, None)
        else:
            emitted = stock.extract(event, slot)
    except Exception as error:  # noqa: BLE001
        return {"reason": f"BeamNG stock event {event}: {error}"}
    if emitted is None:
        return {"reason": f"BeamNG stock event {event} resolves to no recording"}
    emitted["provenance"]["pickedBy"] = "--map"
    return emitted


def base_game_slots(stock: Any, wanted: list[str], traits: dict[str, Any], taken: set[str],
                    events: dict[str, str] | None = None) -> tuple[dict[str, Any], dict[str, str]]:
    """Fill ``wanted`` slots with what BeamNG plays by default. ``taken`` = sample names already used (no repeats).

    ``events`` names a specific stock event per slot (a --map pick: a same-family starter, another door set ...).
    """
    slots: dict[str, Any] = {}
    reasons: dict[str, str] = {}
    for slot, value in (events or {}).items():
        event = stock_event_to_fmod(value)
        try:
            emitted = stock.extract(event, slot, None, None, taken)
        except Exception as error:  # noqa: BLE001
            reasons[slot] = f"BeamNG stock event {event}: {error}"
            continue
        if emitted is None:
            reasons[slot] = f"BeamNG stock event {event} resolves to no recording"
            continue
        emitted["provenance"]["pickedBy"] = "--map"
        taken.add(emitted["provenance"]["sample"])
        slots[slot] = emitted
    for slot in wanted:
        if slot in slots:
            continue
        entry = BASE_GAME_DEFAULTS.get(slot)
        if entry is None:
            continue
        if slot in TURBO_ONLY and traits.get("induction") != "turbo":
            continue
        event, prefer, avoid, evidence = entry
        try:
            emitted = stock.extract(event, slot, prefer, avoid, taken)
        except Exception as error:  # noqa: BLE001
            reasons[slot] = f"BeamNG base-game default {event}: {error}"
            continue
        if emitted is None:
            reasons[slot] = f"BeamNG base-game default {event} resolves to no recording"
            continue
        emitted["provenance"]["baseGameDefault"] = evidence
        taken.add(emitted["provenance"]["sample"])
        slots[slot] = emitted
    return slots, reasons


SOUNDSCAPE_SLOTS: dict[str, tuple[str, int]] = {
    "horn": ("horn", 0), "indloop1": ("indicatorTick", 0), "indicatorstart": ("indicatorTick", 1),
    "handbrakeengaging": ("handbrake", 0), "handbrakedisengaged": ("handbrake", 1),
}


def stock_event_to_fmod(value: str) -> str:
    """``event:>Engine>Starter>v8flat_1986_eng`` -> ``event:/Engine/Starter/v8flat_1986_eng``."""
    return "event:/" + value[len("event:>"):].replace(">", "/") if value.startswith("event:>") else value


def safe_extract(archive: Path, target: Path, keep: re.Pattern[str] = KEEP_IN_ZIP) -> None:
    with zipfile.ZipFile(archive) as handle:
        members = handle.infolist()
        if len(members) > MAX_ZIP_MEMBERS:
            raise ValueError(f"{archive.name} has {len(members)} entries (limit {MAX_ZIP_MEMBERS})")
        total = 0
        root = target.resolve()
        for member in members:
            name = member.filename.replace("\\", "/")
            if member.is_dir() or not keep.search(name):
                continue
            destination = (target / name).resolve()
            if root not in destination.parents:
                raise ValueError(f"{archive.name} entry escapes the extraction root: {member.filename}")
            total += member.file_size
            if total > MAX_ZIP_BYTES:
                raise ValueError(f"{archive.name} expands past {MAX_ZIP_BYTES} bytes")
            destination.parent.mkdir(parents=True, exist_ok=True)
            with handle.open(member) as source, destination.open("wb") as out:
                shutil.copyfileobj(source, out)


def _values(node: Any, key: str, depth: int = 0) -> list[Any]:
    if depth > 8:
        return []
    if isinstance(node, dict):
        return [v for k, v in node.items() if k == key] + [x for v in node.values() for x in _values(v, key, depth + 1)]
    if isinstance(node, list):
        return [x for v in node for x in _values(v, key, depth + 1)]
    return []


def mod_root(folder: Path) -> Path:
    """The folder holding ``vehicles/`` — zips often wrap the mod in a folder or two (``unpacked/66487-.../``)."""
    if (folder / "vehicles").is_dir():
        return folder
    frontier = [folder]
    for _ in range(3):
        nxt = []
        for directory in frontier:
            for child in sorted(p for p in directory.iterdir() if p.is_dir() and not p.is_symlink()):
                if (child / "vehicles").is_dir():
                    return child
                nxt.append(child)
        frontier = nxt[:200]
    return folder


class BeamngInventory:
    def __init__(self, source: Path, staging: Path, options: dict[str, Any]):
        self.options = options
        self.staging = staging
        self.archive = source if source.is_file() and source.suffix.lower() == ".zip" else None
        if self.archive:
            self.root = staging / "mod"
            safe_extract(self.archive, self.root)
            self.root = mod_root(self.root)
        else:
            self.root = mod_root(source)
        self.source_sha = sha256_file(self.archive) if self.archive else None
        self.mod_name = options.get("modName") or (self.archive.stem if self.archive else source.name)
        self.beamng_root = Path(options["beamngRoot"]) if options.get("beamngRoot") else None
        self.warnings: list[str] = []
        self.notes: list[str] = []
        self._stock = None
        self._stock_error: str | None = None
        self.max_motor_rpm = 0.0

    # -- vehicle + configuration ----------------------------------------------------------------------------------
    def vehicle_root(self) -> Path:
        vehicles = self.root / "vehicles"
        if not vehicles.is_dir():
            raise ValueError(f"{self.root} has no vehicles/ folder: not a BeamNG vehicle mod")
        wanted = self.options.get("vehicle")
        candidates = sorted(p for p in vehicles.iterdir() if p.is_dir() and p.name != "common"
                            and any(p.glob("*.jbeam")))
        if wanted:
            match = next((p for p in candidates if p.name.lower() == wanted.lower()), None)
            if not match:
                raise ValueError(f"--vehicle {wanted}: the mod has {', '.join(p.name for p in candidates) or 'no vehicles'}")
            return match
        if len(candidates) != 1:
            raise ValueError(f"the mod has {len(candidates)} vehicles ({', '.join(p.name for p in candidates)}); pass --vehicle")
        return candidates[0]

    def common_roots(self) -> list[Path]:
        roots = []
        if self.beamng_root:
            common_zip = self.beamng_root / "content" / "vehicles" / "common.zip"
            if common_zip.is_file():
                target = self.staging / "bng-common"
                if not (target / "vehicles" / "common").is_dir():
                    safe_extract(common_zip, target, re.compile(r"\.jbeam$", re.I))
                roots.append(target)
        return roots

    def selected_parts(self) -> tuple[list[tuple[str, dict[str, Any], str]], dict[str, Any]]:
        vehicle = self.vehicle_root()
        config_arg = self.options.get("config")
        if config_arg:
            config = Path(config_arg)
            if not config.is_absolute():
                config = vehicle / config_arg
            if not config.is_file():
                hits = [p for p in vehicle.glob("*.pc") if p.name.lower() == Path(config_arg).name.lower()]
                if not hits:
                    raise ValueError(f"--config {config_arg}: not found in {vehicle} ({', '.join(p.name for p in sorted(vehicle.glob('*.pc')))})")
                config = hits[0]
        else:
            config = preselect_configuration(vehicle, [vehicle.name])
            if config is None:
                info = vehicle / "info.json"
                default = None
                if info.is_file():
                    try:
                        body, _ = parse_jbeam_text(info.read_text(errors="ignore"))
                        default = body.get("default_pc") or body.get("defaultPC")
                    except ValueError:
                        default = None
                pcs = sorted(vehicle.glob("*.pc"))
                config = next((p for p in pcs if default and p.stem == default), pcs[0] if pcs else None)
            if config is None:
                raise ValueError(f"{vehicle} has no .pc configuration; pass --config")
        dependency = self.common_roots()
        cache = JBeamDocumentCache(self.root, dependency)
        ranked = [(vehicle, 0), (self.root / "vehicles" / "common", 1),
                  *((root / "vehicles" / "common", 2) for root in dependency)]
        admitted = [(root, rank) for root, rank in ranked if root.is_dir()]
        catalog, failures = build_part_catalog([r for r, _ in admitted], cache, [k for _, k in admitted])
        if failures:
            self.warnings.extend(f"jbeam parse: {f}" for f in failures[:5])
        configuration, _ = parse_jbeam_text(config.read_text(errors="ignore"))
        parts = configuration.get("parts") if isinstance(configuration.get("parts"), dict) else {}
        main = configuration.get("mainPartName") or configuration.get("model") or vehicle.name
        closure = resolve_part_closure(catalog, parts, main)
        selected = [(p["name"], catalog.body(p["name"]), p["source"]) for p in closure["parts"]]
        meta = {"vehicle": vehicle.name, "config": config.name, "parts": len(selected),
                "missing": [m["partName"] for m in closure["missing"]][:20]}
        return selected, meta

    # -- references -------------------------------------------------------------------------------------------------
    def references(self, parts: list[tuple[str, dict[str, Any], str]]) -> list[dict[str, Any]]:
        refs: list[dict[str, Any]] = []

        def visit(node: Any, part: str, section: str, depth: int) -> None:
            if depth > 8:
                return
            if isinstance(node, list):
                for item in node:
                    if isinstance(item, (dict, list)):
                        visit(item, part, section, depth + 1)
                return
            if isinstance(node, dict):
                for key, value in node.items():
                    if isinstance(value, str) and value and key in EVENT_FIELDS:
                        rule = next((r for r in EVENT_FIELDS[key] if re.search(r[0], value, re.I)), None)
                        refs.append({"field": key, "section": section, "part": part, "value": value,
                                     "slot": rule[1] if rule else None, "rank": rule[2] if rule else 9,
                                     **({} if rule else {"why": "no HELIX slot (bonnet/boot/other latch)"})})
                        continue
                    if isinstance(value, str) and value:
                        slot = SECTION_FIELDS.get((section, key)) or FIELD_SLOTS.get(key)
                        if slot:
                            refs.append({"field": key, "section": section, "part": part, "value": value,
                                         "slot": slot[0], "rank": slot[1]})
                        elif key in UNMAPPED_FIELDS and (value.startswith("event:>") or "." in value):
                            refs.append({"field": key, "section": section, "part": part, "value": value,
                                         "slot": None, "why": UNMAPPED_FIELDS[key]})
                    elif key == "soundscape" and isinstance(value, list):
                        for row in value:
                            if isinstance(row, list) and len(row) >= 2 and isinstance(row[0], str) and isinstance(row[1], str):
                                if row[0] in ("name", "src") or row[1] in ("src", "event"):
                                    continue
                                slot = SOUNDSCAPE_SLOTS.get(row[0].lower())
                                refs.append({"field": f"soundscape.{row[0]}", "section": "soundscape", "part": part,
                                             "value": row[1], "slot": slot[0] if slot else None,
                                             "rank": slot[1] if slot else 9,
                                             **({} if slot else {"why": "no HELIX slot"})})
                    elif isinstance(value, (dict, list)):
                        visit(value, part, key if isinstance(value, dict) else section, depth + 1)

        for name, body, _source in parts:
            visit(body, name, "", 0)
        return refs

    # -- sources ----------------------------------------------------------------------------------------------------
    def provenance(self, kind: str, source_file: str, sha: str, event: str | None, transforms: list[dict[str, Any]],
                   extractor: str, **extra: Any) -> dict[str, Any]:
        row: dict[str, Any] = {"kind": self.options.get("kind") if kind == "sim-mod" and self.options.get("kind") else kind,
                               "sim": "beamng", "mod": self.mod_name if kind == "sim-mod" else "BeamNG.drive",
                               "sourceFile": source_file, "sourceSha256": sha, "extractor": extractor}
        if kind == "sim-mod" and self.options.get("modUrl"):
            row["modUrl"] = self.options["modUrl"]
        if event:
            row["event"] = event
        if transforms:
            row["transforms"] = transforms
        row.update(extra)
        return row

    def mod_file(self, value: str) -> Path | None:
        return beamng_audio.confine(self.root.resolve(), value)

    def stock_resolver(self) -> Any:
        if self._stock is None and self._stock_error is None:
            if not self.beamng_root:
                self._stock_error = "no --beamng-root (or HELIX_BEAMNG_ROOT) was given"
            else:
                try:
                    import beamng_stock_events
                    self._stock = beamng_stock_events.StockEvents(
                        self.beamng_root, self.staging / "bng-stock", self.options.get("vgmstream"),
                        Path(self.options["cacheDir"]) if self.options.get("cacheDir") else None)
                except Exception as error:  # noqa: BLE001 - reported as the slot reason
                    self._stock_error = str(error)
        return self._stock

    def emit_file(self, path: Path, event: str | None, kind: str, portable: str, sha: str | None = None,
                  extractor: str = "helix sim_audio_beamng", **extra: Any) -> dict[str, Any]:
        out = self.staging / f"tmp-{hashlib.sha256(str(path).encode()).hexdigest()[:16]}.wav"
        transforms = normalize_wav(path, out)
        digest = sha256_file(out)
        final = self.staging / staged_name(path.stem, digest)
        if not final.exists():
            shutil.copyfile(out, final)
        return {"wav": str(final), "provenance": self.provenance(kind, portable, sha or sha256_file(path), event,
                                                                 transforms, extractor, **extra)}

    def resolve_value(self, value: str, slot: str | None = None) -> tuple[dict[str, Any] | None, str | None]:
        """A field value -> (emitted sample, None) or (None, reason it stays empty)."""
        if value.startswith("event:>") or value.startswith("event:/"):
            event = stock_event_to_fmod(value)
            stock = self.stock_resolver()
            if stock is None:
                return None, (f"needs BeamNG stock FMOD event {event} ({value}); {self._stock_error} — pass "
                              "--beamng-root <BeamNG.drive install> to extract it from content/art_sound.zip")
            try:
                emitted = stock.extract(event, slot)
            except Exception as error:  # noqa: BLE001
                return None, f"BeamNG stock FMOD event {event}: {error}"
            if emitted is None:
                return None, f"BeamNG stock FMOD event {event} is not in the game's vehicle banks"
            return emitted, None
        path = self.mod_file(value)
        if path is None or path.suffix.lower() not in AUDIO_EXTENSIONS:
            path = self.find_named_recording(value)
        if path is not None and path.suffix.lower() in AUDIO_EXTENSIONS:
            portable = path.resolve().relative_to(self.root.resolve()).as_posix()
            return self.emit_file(path, None, "sim-mod", portable), None
        return None, f"names {value!r}, which is neither a file the mod ships nor an FMOD event"

    def find_named_recording(self, value: str) -> Path | None:
        """An extension-less name (``F40_LM_Start``, ``bovf40``): the recording the mod ships under that stem."""
        name = value.replace("\\", "/").rstrip("/").rsplit("/", 1)[-1]
        stem = Path(name).stem if Path(name).suffix.lower() in AUDIO_EXTENSIONS else name
        if not stem:
            return None
        if not hasattr(self, "_recordings"):
            limits = {ext: (5000, 4 * 1024 * 1024 * 1024, 512 * 1024 * 1024) for ext in AUDIO_EXTENSIONS}
            try:
                self._recordings = bounded_asset_paths([self.root], limits)
            except ValueError:
                self._recordings = []
        hits = [p for p in self._recordings if p.stem.lower() == stem.lower()]
        hits.sort(key=lambda p: (["/vehicles/" not in p.as_posix(), p.suffix.lower() != ".wav", len(p.as_posix())]))
        return hits[0] if hits else None

    def resolve_request(self, req: dict[str, Any], refs: list[dict[str, Any]]) -> dict[str, Any]:
        """A --map pick on a BeamNG mod: a jbeam field / value the selected parts name, a recording the mod ships
        (path or stem), or a stock event (with an exact `sample` among its takes)."""
        slot = req.get("slot")
        sample = req.get("sample") or req.get("field")
        event = req.get("event")
        if event and not str(event).startswith("event:"):
            # The car-lane form {"event": "starterSample", "sample": "<file>"}: event names the jbeam field.
            sample = sample or event
            event = None
        if event:
            stock = self.stock_resolver()
            if stock is None:
                return {"reason": f"needs BeamNG stock FMOD event {stock_event_to_fmod(event)}; {self._stock_error}"}
            return extract_exact(stock, stock_event_to_fmod(event), slot, req.get("sample"))
        if sample:
            for ref in refs:
                value = str(ref["value"])
                if sample in (ref["field"], value) or Path(value.replace("\\", "/")).stem.lower() == Path(str(sample)).stem.lower():
                    emitted, reason = self.resolve_value(value, slot)
                    if emitted:
                        emitted["provenance"].setdefault("jbeam", f"{ref['part']}.{ref['field']}")
                        return emitted
                    return {"reason": f"{ref['part']}.{ref['field']} {reason}"}
            path = self.mod_file(str(sample))
            if path is None or path.suffix.lower() not in AUDIO_EXTENSIONS:
                path = self.find_named_recording(str(sample))
            if path is not None:
                portable = path.resolve().relative_to(self.root.resolve()).as_posix()
                emitted = self.emit_file(path, None, "sim-mod", portable)
                emitted["provenance"]["pickedBy"] = "--map"
                return emitted
            return {"reason": f"the mod ships no recording {sample!r} and its selected parts name none"}
        return {"reason": "the request names no sample, field or event"}

    def event_only_blend(self, root: Path, name: str) -> str | None:
        """The FMOD event a stock blend names when it has no rung samples (BeamNG's electric motors), else None."""
        blend = beamng_audio.find_blend(root, name)
        if blend is None:
            return None
        try:
            body, _ = parse_jbeam_text(blend.read_text(errors="ignore"))
        except ValueError:
            return None
        samples = body.get("samples")
        event = body.get("eventName")
        return event if isinstance(event, str) and event.startswith("event:") and not samples else None

    def motor_ladders(self, event: str, notes: list[str]) -> tuple[dict[str, Any] | None, str | None]:
        stock = self.stock_resolver()
        if stock is None:
            return None, f"needs BeamNG stock FMOD event {event}; {self._stock_error}"
        max_rpm = float(self.options.get("maxRpm") or self.max_motor_rpm or 0) or None
        if max_rpm is None:
            guid = stock.lower.get(event.lower())
            curve = stock.events[guid].pitch_curve if guid in stock.events else []
            max_rpm = max((x for x, _ in curve), default=8000.0)
            notes.append(f"engine: no maxRPM in the selected parts; rungs span the event's pitch automation (to {max_rpm:g} rpm)")
        rpms = [float(r) for r in self.options.get("ladderRpms") or motor_rungs(max_rpm)]
        engine, reason = event_ladder(stock, event, rpms, self.staging, re.sub(r"[^A-Za-z0-9]+", "_", event.rsplit("/", 1)[-1]).upper())
        if engine is None:
            return None, reason
        exhaust, _ = event_ladder(stock, event, rpms, self.staging, engine["name"] + "_L2", layer=1)
        return {"engine": engine, "exhaust": exhaust}, None

    def shipped_blends(self) -> list[str]:
        blends = self.root / "art" / "sound" / "blends"
        if not blends.is_dir():
            return []
        return sorted(p.name[:-len(beamng_audio.BLEND_SUFFIX)] for p in blends.iterdir()
                      if p.name.lower().endswith(beamng_audio.BLEND_SUFFIX.lower()))

    # -- ladders ----------------------------------------------------------------------------------------------------
    def stock_blend_root(self, name: str) -> Path | None:
        if not self.beamng_root:
            return None
        content = self.beamng_root / "content"
        target = self.staging / "bng-blends"
        blend_member = f"art/sound/blends/{name}.sfxBlend2D.json".lower()
        found = None
        for archive in (content / "art_sound.zip", content / "audio.zip"):
            if not archive.is_file():
                continue
            with zipfile.ZipFile(archive) as handle:
                for member in handle.infolist():
                    if member.filename.replace("\\", "/").lower() == blend_member:
                        found = member.filename
                        safe_extract(archive, target, re.compile(re.escape(member.filename) + "$"))
                        break
            if found:
                break
        if not found:
            return None
        try:
            blend = beamng_audio.parse_blend(target / found)
        except beamng_audio.AudioUnavailable:
            return target  # an event-only blend (an EV motor): the caller reads its eventName
        wanted = {p.replace("\\", "/").lower() for ladder in blend["ladders"] for p, _ in ladder}
        for archive in (content / "audio.zip", content / "art_sound.zip"):
            if not archive.is_file():
                continue
            with zipfile.ZipFile(archive) as handle:
                names = [m.filename for m in handle.infolist() if m.filename.replace("\\", "/").lower() in wanted]
            if names:
                pattern = re.compile("^(" + "|".join(re.escape(n) for n in names) + ")$")
                safe_extract(archive, target, pattern)
        return target

    def ladders(self, engine_name: str | None, exhaust_name: str | None) -> tuple[dict[str, Any], list[str]]:
        notes: list[str] = []
        out: dict[str, Any] = {"engine": None, "exhaust": None}
        # --map ladder.blend / ladder.exhaustBlend: a blend the mod ships that no selected part names (an Automation
        # export whose jbeam still names a stale sampleName, an alternative engine set).
        if self.options.get("engineBlend"):
            notes.append(f"engine: blend {self.options['engineBlend']!r} chosen by --map (the selected parts name {engine_name!r})")
            engine_name = self.options["engineBlend"]
        if self.options.get("exhaustBlend"):
            notes.append(f"exhaust: blend {self.options['exhaustBlend']!r} chosen by --map (the selected parts name {exhaust_name!r})")
            exhaust_name = self.options["exhaustBlend"]
        if self.options.get("engineEvent"):
            event = stock_event_to_fmod(str(self.options["engineEvent"]))
            built, reason = self.motor_ladders(event, notes)
            if built:
                return built, notes
            notes.append(f"engine: {reason}")
            return out, notes
        layers = beamng_audio.resolve_layers(self.root, engine_name, exhaust_name)
        roots: dict[str, tuple[Path, str]] = {}
        for layer, info in layers.items():
            if info["state"] == "shipped":
                roots[layer] = (self.root, "sim-mod")
            elif info["state"] == "stock":
                stock_root = self.stock_blend_root(info["name"])
                event_only = self.event_only_blend(stock_root, info["name"]) if stock_root is not None else None
                if event_only and layer == "engine":
                    built, reason = self.motor_ladders(stock_event_to_fmod(event_only), notes)
                    if built:
                        notes.append(f"engine: the stock blend {info['name']} names only the FMOD event {event_only}; "
                                     "its ladder is built from that event")
                        return built, notes
                    notes.append(f"engine: {reason}")
                    continue
                if stock_root is not None:
                    layers[layer] = {"state": "shipped", "name": info["name"],
                                     "blend": beamng_audio.find_blend(stock_root, info["name"])}
                    roots[layer] = (stock_root, "sim-official")
                else:
                    notes.append(f"{layer}: {beamng_audio.stock_reason(info['name']).replace(' — platform fallback engine', '')}"
                                 + ("" if self.beamng_root else "; pass --beamng-root to extract the stock blend"))
            elif not (layer == "exhaust" and layers["engine"]["state"] != "absent"):
                notes.append(f"{layer}: the selected engine declares no {layer} sample (sampleName {info['name']!r})")
        for layer, (root, kind) in roots.items():
            single = {layer: layers[layer], **{other: {"state": "absent", "name": None}
                                               for other in ("engine", "exhaust") if other != layer}}
            bank_dir = self.staging / f"bank-{layer}"
            try:
                bank = beamng_audio.extract_engine_bank(root, single, bank_dir, beamng_audio.locate_ffmpeg())
            except beamng_audio.AudioUnavailable as error:
                notes.append(f"{layer}: blend {layers[layer]['name']} unusable: {error}")
                continue
            name = layers[layer]["name"]
            blend = bank["blends"][name]
            by_asset = {s["asset"]: s for s in bank["sources"]}
            blend_file = layers[layer]["blend"]
            rel_blend = blend_file.resolve().relative_to(root.resolve()).as_posix()
            rows = []
            for ladder in blend["samples"]:
                row = []
                for asset, rpm in ladder:
                    origin = by_asset[asset]
                    staged_path = bank_dir / asset
                    transforms = [{"kind": "decode", "detail": "-> 16-bit PCM WAV", "tool": "ffmpeg"}] if origin["transcoded"] else []
                    transforms += origin.get("transforms", [])
                    row.append({"wav": str(staged_path), "rpm": rpm,
                                "provenance": self.provenance(kind, origin["sourcePath"] if kind == "sim-mod" else f"content/audio.zip:{origin['sourcePath']}",
                                                              origin["sourceSha256"], blend["eventName"], transforms,
                                                              "helix beamng_audio", blend=rel_blend)})
                rows.append(row)
            if len(rows) == 1:
                rows.append(rows[0])
                notes.append(f"{layer}: blend {name} has one load row; it serves both")
            rungs = [r["rpm"] for r in rows[0]]
            out[layer] = {"name": name, "eventName": blend["eventName"], "rows": rows[:2],
                          "sampleRate": bank["sampleRate"],
                          "provenance": self.provenance(kind, rel_blend if kind == "sim-mod" else f"content/art_sound.zip:{rel_blend}",
                                                        sha256_file(blend_file), blend["eventName"], [], "helix beamng_audio"),
                          "note": (f"{len(rows[0])} rungs {min(rungs):g}-{max(rungs):g} rpm from "
                                   f"{'the mod' if kind == 'sim-mod' else 'the BeamNG stock'} blend {name}, "
                                   f"row 0 = off-throttle, row 1 = on-throttle")}
        if not out["engine"]:
            shipped = self.shipped_blends()
            if shipped:
                notes.append(f"the mod ships blend(s) {', '.join(shipped)} that the selected engine does not name; "
                             'pick one with --map {"ladder": {"blend": "<name>"}}')
        if out["engine"] and not out["exhaust"] and layers["exhaust"]["state"] == "absent":
            declared = layers["exhaust"]["name"]
            notes.append(("exhaust: the mod disables the exhaust layer (sampleName "
                          f"{declared!r})" if declared else "exhaust: the selected parts declare no exhaust sample")
                         + "; its engine recording is one combined engine+exhaust set")
        return out, notes

    # -- loose recordings -------------------------------------------------------------------------------------------
    def loose_files(self, used: set[str]) -> dict[str, list[Path]]:
        found: dict[str, list[Path]] = {}
        roots = [self.root / "art" / "sound", *self.root.glob("vehicles/*/sounds"), *self.root.glob("vehicles/*/sound")]
        limits = {ext: (2000, 2 * 1024 * 1024 * 1024, 256 * 1024 * 1024) for ext in AUDIO_EXTENSIONS}
        paths = bounded_asset_paths([r for r in roots if r.is_dir()], limits) if any(r.is_dir() for r in roots) else []
        for path in paths:
            rel = path.resolve().relative_to(self.root.resolve()).as_posix()
            if rel.lower() in used or "/engine/" in rel.lower():
                continue
            slot = slot_for_name(path.stem)
            if slot:
                found.setdefault(slot, []).append(path)
        for slot in found:
            found[slot].sort(key=lambda p: (exterior_rank(p.stem), p.name.lower()))
        return found

    # -- what the car physically has --------------------------------------------------------------------------------
    @staticmethod
    def traits(parts: list[tuple[str, dict[str, Any], str]]) -> dict[str, Any]:
        induction = None
        gearbox = None
        electric = False
        for _, body, _ in parts:
            if isinstance(body.get("turbocharger"), dict):
                induction = "turbo"
            elif isinstance(body.get("supercharger"), dict) and induction is None:
                induction = "supercharger"
            for row in body.get("powertrain", []) if isinstance(body.get("powertrain"), list) else []:
                if isinstance(row, list) and row and isinstance(row[0], str):
                    kind = row[0].lower()
                    if kind in GEARBOX_KINDS:
                        gearbox = GEARBOX_KINDS[kind]
                    if "electricmotor" in kind:
                        electric = True
        return {"induction": induction, "gearbox": gearbox, "electric": electric}

    # -- everything -------------------------------------------------------------------------------------------------
    def inventory(self) -> dict[str, Any]:
        parts, meta = self.selected_parts()
        traits = self.traits(parts)
        refs = self.references(parts)
        sound: dict[str, Any] = {}
        exhaust: dict[str, Any] = {}
        for _, body, _ in parts:
            if isinstance(body.get("soundConfig"), dict):
                sound.update(body["soundConfig"])
            for key in ("soundConfigExhaust", "exhaustSoundConfig"):
                if isinstance(body.get(key), dict):
                    exhaust.update(body[key])
        try:
            cylinders = derive_cylinders([(n, b) for n, b, _ in parts], sound, exhaust,
                                         {"cylinders": self.options["cylinders"]} if self.options.get("cylinders") else None)
        except ValueError as error:
            cylinders = {"count": None, "detail": str(error)}
        self.max_motor_rpm = max((float(v) for _, body, _ in parts for v in _values(body, "maxRPM")
                                  if isinstance(v, (int, float)) and not isinstance(v, bool)), default=0.0)
        ladders, ladder_notes = (({"engine": None, "exhaust": None}, ["--no-ladder"]) if self.options.get("noLadder")
                                 else self.ladders(sound.get("sampleName"), exhaust.get("sampleName")))
        slots: dict[str, Any] = {}
        reasons: dict[str, str] = {}
        unmapped: list[dict[str, Any]] = []
        used: set[str] = set()
        picks: dict[str, str] = self.options.get("pick") or {}
        by_slot: dict[str, list[dict[str, Any]]] = {}
        for ref in refs:
            if ref.get("slot"):
                by_slot.setdefault(ref["slot"], []).append(ref)
            else:
                unmapped.append({"field": ref["field"], "part": ref["part"], "value": ref["value"], "why": ref.get("why")})
        for slot, candidates in by_slot.items():
            candidates.sort(key=lambda r: r["rank"])
            if slot in picks:
                candidates = [r for r in candidates if picks[slot] in (r["field"], r["value"])] or candidates
            errors = []
            for ref in candidates:
                emitted, reason = self.resolve_value(ref["value"], slot)
                if emitted:
                    emitted["provenance"].setdefault("jbeam", f"{ref['part']}.{ref['field']}")
                    emitted["alternatives"] = [*emitted.get("alternatives", []),
                                               *[r["value"] for r in candidates if r is not ref]][:16]
                    slots[slot] = emitted
                    if not ref["value"].startswith("event:"):
                        used.add(ref["value"].replace("\\", "/").lstrip("/").lower())
                    break
                errors.append(f"{ref['part']}.{ref['field']} {reason}")
            if slot not in slots:
                reasons[slot] = "; ".join(errors)
        loose = self.loose_files(used)
        for slot, paths in loose.items():
            if slot in slots:
                continue
            chosen = paths[0]
            if slot in picks:
                chosen = next((p for p in paths if p.name == picks[slot] or p.stem == picks[slot]), chosen)
            portable = chosen.resolve().relative_to(self.root.resolve()).as_posix()
            emitted = self.emit_file(chosen, None, "sim-mod", portable)
            emitted["provenance"]["matchedBy"] = "file name"
            emitted["alternatives"] = [p.name for p in paths if p != chosen][:8]
            slots[slot] = emitted
            reasons.pop(slot, None)
        if self.beamng_root and not self.options.get("noBaseGame"):
            stock = self.stock_resolver()
            wanted = [slot for slot in BASE_GAME_DEFAULTS if slot not in slots]
            if stock is not None and wanted:
                taken = {v["provenance"].get("sample") for v in slots.values() if v["provenance"].get("sample")}
                filled, failed = base_game_slots(stock, wanted, traits, taken)
                slots.update(filled)
                for slot in filled:
                    reasons.pop(slot, None)
                for slot, reason in failed.items():
                    reasons.setdefault(slot, reason)
        requested: dict[str, Any] = {}
        for req in self.options.get("requests") or []:
            if any(req.get(key) for key in ("sample", "field", "event", "file")):
                requested[str(req["id"])] = self.resolve_request(req, refs)
            else:
                # A slot routed to this mod with no pick: what the mod itself provides for it.
                slot = req.get("slot")
                requested[str(req["id"])] = slots.get(slot) or {"reason": reasons.get(slot) or
                                                                 f"the mod's selected parts name no {slot} sound and it ships no recording named for it"}
        return {
            "requested": requested,
            "sim": "beamng",
            "traits": traits,
            "source": {"path": str(self.archive or self.root), "name": self.mod_name, "sha256": self.source_sha,
                       **meta, "engineSample": sound.get("sampleName"), "exhaustSample": exhaust.get("sampleName")},
            "ladders": ladders,
            "ladderNotes": ladder_notes,
            "slots": slots,
            "reasons": reasons,
            "absentReason": "the mod's selected parts name no {slot} sound and it ships no recording named for it",
            "unmapped": unmapped,
            "warnings": self.warnings,
            "cylinders": cylinders,
            "mix": mix_from_sound_config(sound, exhaust),
            "stockEvents": self._stock.report() if self._stock is not None else
                           ({"error": self._stock_error} if self._stock_error else None),
        }
