"""Read the event metadata of an FMOD Studio bank: which samples an event plays, and where on its parameter.

An FMOD Studio ``.bank`` is a RIFF ``FEV `` file. Its ``PROJ`` list holds one chunk list per object kind, each record
starting with the object's 16-byte GUID and referring to other objects by GUID:

  EVTS/EVNT/EVTB   an event                         [0:16] event GUID
  TLNS/TMLN/TLNB   an event's timeline              [0:16] timeline, [16:32] event, then the instrument GUIDs on it
  PMLS/PMLO/PMLB   a parameter sheet of an event    [0:16] sheet, [16:32] parameter, [32:48] event
  PRMS/PARM/PRMB   a parameter                      [0:16] parameter, then its name and range
  WAIS/WAIT/WAIB   a single-sample instrument       [0:16] instrument, [16:32] waveform
  WAIS/WAIT/INST   that instrument's placement      parent sheet GUID, auto-pitch reference value
  MUIS/MUIT/MUIB   a multi-instrument (random set)  [0:16] instrument; PLST lists member instrument GUIDs
  CTRS/CTRL        an automation                    [16:32] target (instrument), [32:48] sheet, [48:64] curve
  CRVS/CURV        its curve                        [16:32] automation, then (x, y, shape, flags) points
  WAVS/WAV         a waveform resource              [0:16] waveform, FSB5 subsound index

Event paths are not in the metadata: Assetto Corsa lists ``{guid} event:/cars/<car>/<event>`` lines in
``content/sfx/GUIDs.txt``; a ``.strings.bank`` carries them for other projects.

Only the layouts this importer has been measured against are decoded (``SUPPORTED_FORMATS``). Any other version is
refused with the version number, never guessed at.
"""
from __future__ import annotations

import re
import struct
import uuid
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any

# FMT chunk version -> per-record offsets. 0x50 = FMOD Studio 1.x as shipped by Assetto Corsa (2014-2019 cars).
SUPPORTED_FORMATS: dict[int, dict[str, int]] = {
    0x50: {"inst_parent": 53, "inst_autopitch": 69, "inst_volume": 16, "wav_index": 22,
           "ctrl_target": 16, "ctrl_sheet": 32, "ctrl_curve": 48, "ctrl_property": 64, "curve_points": 36},
}
VOLUME_PROPERTY = 4
# FMOD Studio 2.x as shipped by BeamNG.drive 0.3x (FMT 0x92): an instrument names its parent timeline / parameter
# sheet in INST[0:16]; an event lists its timeline and sheets; waveforms live in the *.assets.bank WAVS lists.
SUPPORTED_V2_FORMATS = {0x92}
INST_V2_BUS = 86


class FmodMetadataError(ValueError):
    """The bank's event metadata is in a layout this importer has not been measured against."""


def guid_from_text(text: str) -> bytes:
    """``{1b366f4a-d7f4-4670-b61e-a9daf78d3a3b}`` -> the 16 bytes FMOD stores (Windows GUID byte order)."""
    return uuid.UUID(text.strip().strip("{}")).bytes_le


def guid_text(raw: bytes) -> str:
    return "{" + str(uuid.UUID(bytes_le=bytes(raw))) + "}"


@dataclass
class Records:
    data: bytes
    fmt: int
    by_type: dict[str, list[tuple[int, int]]] = field(default_factory=dict)
    order: list[tuple[str, int, int]] = field(default_factory=list)

    def bodies(self, kind: str) -> list[bytes]:
        return [self.data[b:b + s] for b, s in self.by_type.get(kind, [])]


def walk_records(data: bytes) -> Records:
    if data[:4] != b"RIFF" or data[8:12] != b"FEV ":
        raise FmodMetadataError("not an FMOD Studio bank (no RIFF FEV header)")
    fmt = -1
    records = Records(data, fmt)

    def walk(offset: int, end: int, depth: int) -> None:
        while offset + 8 <= end and depth < 12:
            cid = data[offset:offset + 4]
            size = struct.unpack_from("<I", data, offset + 4)[0]
            body = offset + 8
            if cid in (b"RIFF", b"LIST"):
                walk(body + 4, min(end, body + size), depth + 1)
            elif cid != b"SND ":
                kind = cid.decode("latin-1")
                records.by_type.setdefault(kind, []).append((body, size))
                records.order.append((kind, body, size))
            offset = body + size + (size & 1)

    walk(0, len(data), 0)
    fmt_rows = records.by_type.get("FMT ")
    if fmt_rows:
        b, _ = fmt_rows[0]
        records.fmt = struct.unpack_from("<I", data, b)[0]
    return records


@dataclass
class Instrument:
    guid: bytes
    waveform: bytes | None
    subsound: int | None = None
    sheet: bytes | None = None          # parameter sheet it sits on (None: on the timeline)
    autopitch: float | None = None      # parameter value at which the sample plays at its recorded pitch
    volume_db: float = 0.0
    fades: list[list[tuple[float, float]]] = field(default_factory=list)  # volume automation curves, (x, gain)
    members: list[bytes] = field(default_factory=list)  # for a multi-instrument: member instrument GUIDs

    def audible(self) -> tuple[float, float]:
        """Parameter range where the volume automation is above zero (open-ended where there is no fade)."""
        lo, hi = float("-inf"), float("inf")
        for curve in self.fades:
            if len(curve) < 2:
                continue
            (x0, y0), (x1, y1) = curve[0], curve[-1]
            if y0 < y1:   # fade in
                lo = max(lo, x0)
            elif y0 > y1:  # fade out
                hi = min(hi, x1)
        return lo, hi

    def plateau(self) -> tuple[float, float]:
        """Parameter range where every volume automation is at full gain."""
        lo, hi = float("-inf"), float("inf")
        for curve in self.fades:
            if len(curve) < 2:
                continue
            (x0, y0), (x1, y1) = curve[0], curve[-1]
            if y0 < y1:
                lo = max(lo, x1)
            elif y0 > y1:
                hi = min(hi, x0)
        return lo, hi


@dataclass
class Sheet:
    guid: bytes
    parameter: bytes
    event: bytes
    parameter_name: str | None = None
    parameter_range: tuple[float, float] | None = None


@dataclass
class EventInfo:
    guid: bytes
    path: str | None
    sheets: list[Sheet] = field(default_factory=list)
    instruments: list[Instrument] = field(default_factory=list)  # every single-sample instrument it can play
    nested: list[bytes] = field(default_factory=list)  # events this event plays (event instruments)
    # Pitch automation of the event's own buses: [(parameter value, normalised pitch -1..1)] and the parameter.
    pitch_curve: list[tuple[float, float]] = field(default_factory=list)
    pitch_parameter: str | None = None
    parameter_ranges: dict[str, tuple[float, float]] = field(default_factory=dict)


@dataclass
class BankMetadata:
    fmt: int
    events: list[EventInfo]
    waveforms: dict[bytes, int]

    def event(self, path: str) -> EventInfo | None:
        lowered = path.lower()
        return next((e for e in self.events if e.path and e.path.lower() == lowered), None)


def _parameter_name(body: bytes) -> tuple[str | None, tuple[float, float] | None]:
    match = re.search(rb"[A-Za-z_][A-Za-z0-9_ .\-]{1,63}", body[16:])
    if not match:
        return None, None
    name = match.group(0).decode("latin-1")
    after = 16 + match.end()
    rng = None
    if after + 8 <= len(body):
        lo, hi = struct.unpack_from("<ff", body, after)
        if lo == lo and hi == hi and abs(lo) < 1e7 and abs(hi) < 1e7 and hi > lo:
            rng = (lo, hi)
    return name, rng


def read_metadata(path: str | Path, event_paths: dict[bytes, str] | None = None) -> BankMetadata:
    data = Path(path).read_bytes()
    records = walk_records(data)
    if records.fmt in SUPPORTED_V2_FORMATS:
        return _read_metadata_v2(data, records, event_paths)
    layout = SUPPORTED_FORMATS.get(records.fmt)
    if layout is None:
        raise FmodMetadataError(
            f"FMOD Studio bank format 0x{records.fmt:x} is not one this importer has been measured against "
            f"(supported: {', '.join(f'0x{v:x}' for v in [*SUPPORTED_FORMATS, *SUPPORTED_V2_FORMATS])})")

    waveforms: dict[bytes, int] = {}
    for body in records.bodies("WAV "):
        if len(body) >= layout["wav_index"] + 4:
            waveforms[body[:16]] = struct.unpack_from("<I", body, layout["wav_index"])[0]

    parameters: dict[bytes, tuple[str | None, tuple[float, float] | None]] = {}
    for body in records.bodies("PRMB"):
        parameters[body[:16]] = _parameter_name(body)

    sheets: dict[bytes, Sheet] = {}
    for body in records.bodies("PMLB"):
        if len(body) >= 48:
            name, rng = parameters.get(body[16:32], (None, None))
            sheets[body[:16]] = Sheet(body[:16], body[16:32], body[32:48], name, rng)

    instruments: dict[bytes, Instrument] = {}
    order = records.order
    for position, (kind, b, s) in enumerate(order):
        if kind != "WAIB" or s < 32:
            continue
        guid, waveform = data[b:b + 16], data[b + 16:b + 32]
        instrument = Instrument(guid, waveform, waveforms.get(waveform))
        follow = order[position + 1] if position + 1 < len(order) else None
        if follow and follow[0] == "INST":
            ib, isz = follow[1], follow[2]
            inst = data[ib:ib + isz]
            if len(inst) >= layout["inst_autopitch"] + 4:
                parent = inst[layout["inst_parent"]:layout["inst_parent"] + 16]
                if parent in sheets:
                    instrument.sheet = parent
                    value = struct.unpack_from("<f", inst, layout["inst_autopitch"])[0]
                    instrument.autopitch = value if value > 0 and value == value else None
                instrument.volume_db = struct.unpack_from("<f", inst, layout["inst_volume"])[0]
        instruments[guid] = instrument

    multis: dict[bytes, list[bytes]] = {}
    for position, (kind, b, s) in enumerate(order):
        if kind != "MUIB":
            continue
        guid = data[b:b + 16]
        members: list[bytes] = []
        for later in order[position + 1:position + 4]:
            if later[0] == "PLST":
                plst = data[later[1]:later[1] + later[2]]
                for at in range(0, len(plst) - 15):
                    candidate = plst[at:at + 16]
                    if candidate in instruments and candidate not in members:
                        members.append(candidate)
                break
        multis[guid] = members

    curves: dict[bytes, list[tuple[float, float]]] = {}
    for body in records.bodies("CURV"):
        owner = body[16:32]
        points: list[tuple[float, float]] = []
        for at in range(layout["curve_points"], len(body) - 7, 16):
            x, y = struct.unpack_from("<ff", body, at)
            if x != x or y != y:
                break
            points.append((x, y))
        if points:
            curves[owner] = points
    for body in records.bodies("CTRL"):
        if len(body) < layout["ctrl_property"] + 4:
            continue
        target = body[layout["ctrl_target"]:layout["ctrl_target"] + 16]
        prop = struct.unpack_from("<I", body, layout["ctrl_property"])[0]
        curve = curves.get(body[:16])
        if target in instruments and prop == VOLUME_PROPERTY and curve:
            instruments[target].fades.append(curve)

    events: dict[bytes, EventInfo] = {}
    for body in records.bodies("EVTB"):
        guid = body[:16]
        events[guid] = EventInfo(guid, (event_paths or {}).get(guid))
    for sheet in sheets.values():
        if sheet.event in events:
            events[sheet.event].sheets.append(sheet)
    for instrument in instruments.values():
        if instrument.sheet is not None and sheets[instrument.sheet].event in events:
            events[sheets[instrument.sheet].event].instruments.append(instrument)
    def adopt(event: EventInfo, body: bytes, start: int, sheet: bytes | None) -> None:
        # A timeline or sheet lists the instruments placed on it by GUID (trigger instruments on a sheet carry no
        # parent of their own; continuous ones do, and are adopted above).
        for at in range(start, len(body) - 15):
            candidate = body[at:at + 16]
            members = [candidate] if candidate in instruments else multis.get(candidate, [])
            for member in members:
                instrument = instruments[member]
                if sheet is not None and instrument.sheet is None:
                    instrument.sheet = sheet
                if instrument not in event.instruments:
                    event.instruments.append(instrument)

    for body in records.bodies("TLNB"):
        if len(body) >= 32 and body[16:32] in events:
            adopt(events[body[16:32]], body, 32, None)
    for body in records.bodies("PMLB"):
        if len(body) >= 48 and body[32:48] in events:
            adopt(events[body[32:48]], body, 48, body[:16])
    return BankMetadata(records.fmt, list(events.values()), waveforms)


def read_guids_txt(path: str | Path, prefer: str | None = None) -> dict[bytes, str]:
    """Assetto Corsa's ``content/sfx/GUIDs.txt``: ``{guid} event:/cars/<car>/<name>`` per line.

    Kunos variants (``ferrari_f40_s3``) reuse the base car's event GUIDs, so one GUID can carry several paths; the
    path under ``/cars/<prefer>/`` wins, then the first listed.
    """
    candidates: dict[bytes, list[str]] = {}
    for line in Path(path).read_text(errors="ignore").splitlines():
        match = re.match(r"\s*(\{[0-9a-fA-F-]{36}\})\s+(\S.*?)\s*$", line)
        if match:
            try:
                candidates.setdefault(guid_from_text(match.group(1)), []).append(match.group(2))
            except ValueError:
                continue
    wanted = f"/cars/{prefer.lower()}/" if prefer else None
    return {guid: next((p for p in paths if wanted and wanted in p.lower()), paths[0])
            for guid, paths in candidates.items()}


def summarize(meta: BankMetadata, names: dict[int, str]) -> list[dict[str, Any]]:
    rows = []
    for event in meta.events:
        rows.append({
            "event": event.path or guid_text(event.guid),
            "parameters": sorted({s.parameter_name or guid_text(s.parameter) for s in event.sheets}),
            "instruments": [{
                "sample": names.get(i.subsound, None) if i.subsound is not None else None,
                "subsound": i.subsound,
                "autopitch": i.autopitch,
                "audible": list(i.audible()) if i.fades else None,
                "plateau": list(i.plateau()) if i.fades else None,
            } for i in event.instruments],
        })
    return rows


# ---------------------------------------------------------------------------------------------
# FMOD Studio 2 strings banks (``*.strings.bank``): path <-> GUID
# ---------------------------------------------------------------------------------------------

def _u24(data: bytes, at: int) -> int:
    return data[at] | (data[at + 1] << 8) | (data[at + 2] << 16)


def _packed_count(value: int) -> int:
    """Array lengths in the 2.x string table are written as ``count << 1 | 1``."""
    return value >> 1 if value & 1 else value


def read_strings_bank(path: str | Path) -> dict[str, bytes]:
    """``event:/Engine/Starter/v8flat_1986_eng`` -> GUID bytes, for every path a 2.x strings bank holds.

    STDT layout (measured on BeamNG 0.3x ``main_preload.strings.bank``, FMT 0x92):
      u32 version
      u16 count<<1|1, u16 8   then count radix-tree nodes: [u24 label offset][u8 first char][u24 first child or
                              string id][u8 child count]; a node without a label (0xffffff) terminates the path above it
      u16 count<<1|1, u16 16  then count GUIDs (sorted)
      u16 L                   then the L-byte label pool (NUL-terminated edge labels)
      u16 count               then count u24: GUID i -> the node that ends its path
      u16 count               then count u24: node -> parent node
    """
    data = Path(path).read_bytes()
    records = walk_records(data)
    rows = records.by_type.get("STDT")
    if not rows or rows[0][1] < 16:
        raise FmodMetadataError(f"{Path(path).name} has no string table (STDT)")
    start, size = rows[0]
    b = data[start:start + size]
    at = 4
    nodes_count = _packed_count(struct.unpack_from("<H", b, at)[0])
    node_size = struct.unpack_from("<H", b, at + 2)[0]
    at += 4
    if node_size != 8:
        raise FmodMetadataError(f"string table node size {node_size} (expected 8)")
    nodes = [(_u24(b, at + 8 * k), b[at + 8 * k + 3], _u24(b, at + 8 * k + 4), b[at + 8 * k + 7]) for k in range(nodes_count)]
    at += 8 * nodes_count
    guid_count = _packed_count(struct.unpack_from("<H", b, at)[0])
    guid_size = struct.unpack_from("<H", b, at + 2)[0]
    at += 4
    if guid_size != 16:
        raise FmodMetadataError(f"string table GUID size {guid_size} (expected 16)")
    guids = [b[at + 16 * k:at + 16 * k + 16] for k in range(guid_count)]
    at += 16 * guid_count
    pool_size = struct.unpack_from("<H", b, at)[0]
    at += 2
    pool = b[at:at + pool_size]
    at += pool_size
    map_count = struct.unpack_from("<H", b, at)[0]
    at += 2
    ends = [_u24(b, at + 3 * k) for k in range(map_count)]
    at += 3 * map_count
    parent_count = struct.unpack_from("<H", b, at)[0]
    at += 2
    parents = [_u24(b, at + 3 * k) for k in range(parent_count)]
    if map_count != guid_count or parent_count != nodes_count:
        raise FmodMetadataError("string table sections disagree (an FMOD version this importer has not measured)")

    def label(index: int) -> str:
        offset = nodes[index][0]
        if offset == 0xFFFFFF:
            return ""
        end = pool.find(b"\0", offset)
        return pool[offset:end if end >= 0 else len(pool)].decode("utf-8", errors="replace")

    out: dict[str, bytes] = {}
    for guid, node in zip(guids, ends):
        parts: list[str] = []
        steps = 0
        while node != 0xFFFFFF and node < nodes_count and steps < 512:
            parts.append(label(node))
            node = parents[node]
            steps += 1
        out["".join(reversed(parts))] = guid
    return out


def read_waveform_index(path: str | Path) -> dict[bytes, tuple[int, int]]:
    """A 2.x ``*.assets.bank`` / ``*.streams.bank``: waveform GUID -> (FSB5 block, index in block)."""
    data = Path(path).read_bytes()
    records = walk_records(data)
    out: dict[bytes, tuple[int, int]] = {}
    for body in records.bodies("WAV "):
        if len(body) >= 26:
            out[body[:16]] = (struct.unpack_from("<H", body, 18)[0], struct.unpack_from("<I", body, 22)[0])
    return out


def _read_metadata_v2(data: bytes, records: Records, event_paths: dict[bytes, str] | None) -> BankMetadata:
    order = records.order
    events: dict[bytes, EventInfo] = {}
    owner: dict[bytes, bytes] = {}  # timeline / sheet GUID -> event GUID
    known_kinds = {"TLNB", "PMLB", "GBSB"}
    containers: dict[bytes, str] = {}
    for kind, b, s in order:
        if kind in known_kinds and s >= 16:
            containers[data[b:b + 16]] = kind
    for body in records.bodies("EVTB"):
        guid = body[:16]
        events[guid] = EventInfo(guid, (event_paths or {}).get(guid))
        for at in range(16, len(body) - 15):
            candidate = body[at:at + 16]
            if candidate in containers:
                owner.setdefault(candidate, guid)
    instruments: dict[bytes, Instrument] = {}
    multis: dict[bytes, tuple[bytes, list[bytes]]] = {}
    nested: list[tuple[bytes, bytes]] = []
    for position, (kind, b, s) in enumerate(order):
        if kind not in ("WAIB", "MUIB", "EVIB", "SPIB") or s < 16:
            continue
        guid = data[b:b + 16]
        inst = plst = None
        for later in order[position + 1:position + 5]:
            if later[0] == "INST" and inst is None:
                inst = data[later[1]:later[1] + later[2]]
            elif later[0] == "PLST" and plst is None:
                plst = data[later[1]:later[1] + later[2]]
            elif later[0] in ("WAIB", "MUIB", "EVIB", "SPIB"):
                break
        parent = inst[:16] if inst is not None and len(inst) >= 16 else b""
        if parent not in owner and inst is not None and len(inst) >= INST_V2_BUS + 16:
            # Instruments on a parameter sheet carry no parent; they route into the event's own group bus.
            bus = inst[INST_V2_BUS:INST_V2_BUS + 16]
            if bus in owner:
                parent = bus
        if kind == "WAIB" and s >= 32:
            instruments[guid] = Instrument(guid, data[b + 16:b + 32], sheet=parent or None)
        elif kind in ("MUIB", "SPIB"):
            members: list[bytes] = []
            if plst:
                for at in range(0, len(plst) - 15):
                    members.append(plst[at:at + 16])
            multis[guid] = (parent, members)
        elif kind == "EVIB":
            body = data[b:b + s]
            target = next((body[at:at + 16] for at in range(16, len(body) - 15) if body[at:at + 16] in events), None)
            if target is not None:
                nested.append((parent, target))
    for instrument in instruments.values():
        event = owner.get(instrument.sheet or b"")
        if event in events:
            events[event].instruments.append(instrument)
    for guid, (parent, members) in multis.items():
        event = owner.get(parent)
        if event not in events:
            continue
        for member in members:
            if member in instruments and instruments[member] not in events[event].instruments:
                events[event].instruments.append(instruments[member])
    for parent, target in nested:
        event = owner.get(parent)
        if event in events and target not in events[event].nested:
            events[event].nested.append(target)
    # Event-level pitch automation (an EV motor event: one loop, re-pitched by RPM on the event's master bus). FMOD 2
    # stores the CTRL as [0:16] id, [16:32] target, [32:48] curve owner, u32 property at 48 (1 = pitch); its CURV
    # points are (x, y, shape, flags) with y the normalised pitch, -1..1 = -24..+24 semitones.
    parameters: dict[bytes, tuple[str | None, tuple[float, float] | None]] = {b[:16]: _parameter_name(b) for b in records.bodies("PRMB")}
    curves: dict[bytes, list[tuple[float, float]]] = {}
    for body in records.bodies("CURV"):
        points = []
        for at in range(36, len(body) - 7, 16):
            x, y = struct.unpack_from("<ff", body, at)
            if x != x or y != y:
                break
            points.append((x, y))
        curves[body[16:32]] = points
    bus_owner: dict[bytes, bytes] = {}
    for body in records.bodies("EVTB"):
        for at in range(16, len(body) - 15):
            candidate = body[at:at + 16]
            if candidate not in containers:
                bus_owner.setdefault(candidate, body[:16])
    for body in records.bodies("CTRL"):
        if len(body) < 52 or struct.unpack_from("<I", body, 48)[0] != 1:
            continue
        event = bus_owner.get(body[16:32])
        curve = curves.get(body[:16]) or curves.get(body[32:48])
        if event in events and curve and not events[event].pitch_curve:
            events[event].pitch_curve = curve
    for event in events.values():
        for body in records.bodies("PMLB"):
            if owner.get(body[:16]) != event.guid:
                continue
            for at in range(16, len(body) - 15):
                hit = parameters.get(body[at:at + 16])
                if hit and hit[0] and hit[1]:
                    event.parameter_ranges[hit[0]] = hit[1]
        if event.pitch_curve:
            span = max(x for x, _ in event.pitch_curve)
            fits = [n for n, (lo, hi) in event.parameter_ranges.items() if lo <= 0 and hi >= span and n.lower() in ("rpm", "rpms")]
            event.pitch_parameter = fits[0] if fits else None
    return BankMetadata(records.fmt, list(events.values()), {})
