"""Tiny, generated stand-ins for simulator sound files (no binaries are committed).

  build_fsb5(samples)                 an FSB5 block of PCM16 samples with names
  build_ac_bank(path, ...)            an Assetto Corsa style FMOD Studio 1.x bank (FMT 0x50): an engine_ext event whose
                                      instruments sit on an rpm sheet with auto-pitch references and volume fades, and a
                                      horn / door timeline event; plus the GUIDs.txt the game ships
  build_beamng_root(root)             a BeamNG.drive install with content/art_sound.zip (a 2.x strings bank, a metadata
                                      bank and an assets bank for two stock events) and content/vehicles/common.zip
  build_beamng_mod(root)              a BeamNG vehicle mod: jbeam (engine naming a stock starter, a soundscape horn slot),
                                      a .pc, its own sfxBlend2D ladder (one WAV with the mmbng-993 malformed header) and a
                                      loose door recording

Used by test_sim_audio.py and by the jest specs (``python3 sim_audio_fixtures.py <kind> <dir>``).
"""
from __future__ import annotations

import json
import math
import struct
import sys
import uuid
import zipfile
from pathlib import Path


def tone(freq: float, seconds: float = 0.5, rate: int = 44100, amp: float = 0.4, channels: int = 1) -> bytes:
    frames = int(seconds * rate)
    out = bytearray()
    for i in range(frames):
        v = 0.0
        for h in range(1, 9):
            v += math.sin(2 * math.pi * freq * h * i / rate) / h
        s = int(max(-1.0, min(1.0, v * amp * 0.5)) * 32767)
        out += struct.pack("<h", s) * channels
    return bytes(out)


def wav(pcm: bytes, rate: int = 44100, channels: int = 1, *, malformed: bool = False) -> bytes:
    align = channels * 2
    # malformed: the mmbng 993 mod's header (2 channels declared, byteRate/blockAlign of mono)
    block = 2 if malformed else align
    return (b"RIFF" + struct.pack("<I", 36 + len(pcm)) + b"WAVE" + b"fmt " +
            struct.pack("<IHHIIHH", 16, 1, channels, rate, rate * block, block, 16) + b"data" + struct.pack("<I", len(pcm)) + pcm)


def chunk(cid: bytes, body: bytes) -> bytes:
    return cid + struct.pack("<I", len(body)) + body + (b"\0" if len(body) & 1 else b"")


def listing(form: bytes, *children: bytes) -> bytes:
    return chunk(b"LIST", form + b"".join(children))


def guid() -> bytes:
    return uuid.uuid4().bytes_le


def build_fsb5(samples: list[tuple[str, bytes, int, int]]) -> bytes:
    """samples: (name, pcm16 bytes, rate, channels)."""
    freq_index = {8000: 1, 11000: 2, 11025: 3, 16000: 4, 22050: 5, 24000: 6, 32000: 7, 44100: 8, 48000: 9}
    headers = b""
    data = b""
    for name, pcm, rate, channels in samples:
        offset = len(data)
        frames = len(pcm) // (2 * channels)
        packed = (freq_index[rate] << 1) | ((1 if channels == 2 else 0) << 5) | ((offset // 16) << 6) | (frames << 34)
        headers += struct.pack("<Q", packed)
        data += pcm + b"\0" * ((16 - len(pcm) % 16) % 16)
    names_blob = b""
    offsets = []
    base = 4 * len(samples)
    for name, *_ in samples:
        offsets.append(base + len(names_blob))
        names_blob += name.encode() + b"\0"
    names = struct.pack(f"<{len(samples)}I", *offsets) + names_blob
    names += b"\0" * ((16 - len(names) % 16) % 16)
    header = b"FSB5" + struct.pack("<6I", 1, len(samples), len(headers), len(names), len(data), 2)
    header += b"\0" * (0x3C - len(header))
    return header + headers + names + data


def fev(fmt: int, proj_children: list[bytes], snd: bytes | None = None) -> bytes:
    body = b"FEV " + chunk(b"FMT ", struct.pack("<II", fmt, 0x46)) + listing(b"PROJ", *proj_children)
    if snd is not None:
        body += chunk(b"SND ", b"\0" * 8 + snd)
    return chunk(b"RIFF", body)


# ------------------------------------------------------------------------------------------------
# Assetto Corsa (FMOD Studio 1.x, FMT 0x50)
# ------------------------------------------------------------------------------------------------

def _inst_v1(parent: bytes | None, autopitch: float) -> bytes:
    inst = bytearray(123)
    struct.pack_into("<f", inst, 16, 0.0)
    if parent:
        inst[53:69] = parent
        struct.pack_into("<f", inst, 69, autopitch)
    return bytes(inst)


def _curve(owner: bytes, points: list[tuple[float, float]]) -> bytes:
    body = guid() + owner + b"\x05\x00\x10\x00"
    for x, y in points:
        body += struct.pack("<ffff", x, y, 0.0, 0.0)
    return body


def build_ac_bank(directory: Path, car: str = "test_car") -> dict:
    """An AC car folder: <dir>/content/cars/<car>/sfx/<car>.bank + <dir>/content/sfx/GUIDs.txt. Returns GUID facts."""
    rate = 44100
    # Engine samples: on-throttle idle (1150), low (2300 native), mid (4600 reference, placed at 5700 by its plateau).
    samples = [("TST_ex_on_idle", tone(1150 / 15), rate, 1), ("TST_ex_on_low", tone(2300 / 15), rate, 1),
               ("TST_ex_on_mid", tone(4600 / 15), rate, 1), ("TST_ex_off_low", tone(2300 / 15), rate, 1),
               ("TST_ex_off_mid", tone(4600 / 15), rate, 1), ("horn", tone(420, 0.4), rate, 1),
               ("door_open", tone(900, 0.2), rate, 1), ("door_close", tone(700, 0.2), rate, 1)]
    fsb = build_fsb5(samples)
    ev_engine, ev_horn, ev_door = guid(), guid(), guid()
    sheet_rpm, param_rpm, tl_horn, tl_door = guid(), guid(), guid(), guid()
    wav_ids = [guid() for _ in samples]
    inst_ids = [guid() for _ in samples]
    wav_records = [listing(b"WAVS", *[chunk(b"WAV ", w + struct.pack("<HHHIHHH", 0x0C, 0, 0, i, 0, 0, 0)[:14])
                                      for i, w in enumerate(wav_ids)])]
    # engine instruments: (index, autopitch, fades as [(x0,y0),(x1,y1)] lists)
    engine = [(0, 1150.0, [[(1600, 1.0), (2000, 0.0)]]),
              (1, 2300.0, [[(1600, 0.0), (2000, 1.0)], [(3500, 1.0), (4000, 0.0)]]),
              (2, 4600.0, [[(4500, 0.0), (5000, 1.0)], [(5600, 1.0), (5800, 0.0)]]),
              (3, 2300.0, [[(3500, 1.0), (4000, 0.0)]]),
              (4, 4600.0, [[(3500, 0.0), (4000, 1.0)]])]
    waits = []
    ctrls = []
    curves = []
    for index, autopitch, fades in engine:
        waits.append(listing(b"WAIT", chunk(b"WAIB", inst_ids[index] + wav_ids[index]),
                             chunk(b"INST", _inst_v1(sheet_rpm, autopitch))))
        for fade in fades:
            ctrl = guid()
            curve = _curve(ctrl, fade)
            ctrls.append(chunk(b"CTRL", ctrl + inst_ids[index] + sheet_rpm + curve[:16] + struct.pack("<I", 4)))
            curves.append(chunk(b"CURV", curve))
    for index in (5, 6, 7):
        waits.append(listing(b"WAIT", chunk(b"WAIB", inst_ids[index] + wav_ids[index]), chunk(b"INST", _inst_v1(None, 0))))
    proj = [
        listing(b"EVTS", *[listing(b"EVNT", chunk(b"EVTB", e + b"\0" * 40)) for e in (ev_engine, ev_horn, ev_door)]),
        listing(b"TLNS", listing(b"TMLN", chunk(b"TLNB", tl_horn + ev_horn + b"\0" * 4 + inst_ids[5])),
                listing(b"TMLN", chunk(b"TLNB", tl_door + ev_door + b"\0" * 4 + inst_ids[6] + inst_ids[7]))),
        listing(b"PMLS", listing(b"PMLO", chunk(b"PMLB", sheet_rpm + param_rpm + ev_engine + b"\0" * 8))),
        listing(b"PRMS", listing(b"PARM", chunk(b"PRMB", param_rpm + b"\0" * 5 + b"\x04\x00" + b"rpms" + struct.pack("<ff", 0, 9000)))),
        listing(b"CTRS", *ctrls), listing(b"CRVS", *curves), listing(b"WAIS", *waits), *wav_records,
    ]
    car_dir = directory / "content" / "cars" / car
    (car_dir / "sfx").mkdir(parents=True, exist_ok=True)
    (car_dir / "ui").mkdir(exist_ok=True)
    (car_dir / "sfx" / f"{car}.bank").write_bytes(fev(0x50, proj, fsb))
    sfx = directory / "content" / "sfx"
    sfx.mkdir(parents=True, exist_ok=True)
    text = lambda g: "{" + str(uuid.UUID(bytes_le=g)) + "}"  # noqa: E731
    (sfx / "GUIDs.txt").write_text("\n".join([
        f"{text(ev_engine)} event:/cars/{car}/engine_ext",
        f"{text(ev_horn)} event:/cars/{car}/horn",
        f"{text(ev_door)} event:/cars/{car}/door",
    ]) + "\n")
    return {"car_dir": str(car_dir), "bank": str(car_dir / "sfx" / f"{car}.bank")}


# ------------------------------------------------------------------------------------------------
# BeamNG (FMOD Studio 2.x, FMT 0x92)
# ------------------------------------------------------------------------------------------------

def build_strings_bank(paths: dict[str, bytes]) -> bytes:
    """A 2.x strings bank: a flat radix tree (root -> one leaf node per path)."""
    items = sorted(paths.items())
    pool = b""
    nodes = [struct.pack("<I", 0x00FFFFFF) + struct.pack("<I", 1 | (len(items) << 24))]
    ends = []
    for index, (path, _) in enumerate(items):
        offset = len(pool)
        pool += path.encode() + b"\0"
        nodes.append(struct.pack("<I", offset | (ord(path[0]) << 24)) + struct.pack("<I", index))
        ends.append(index + 1)
    parents = [0xFFFFFF] + [0] * len(items)
    u24 = lambda v: struct.pack("<I", v)[:3]  # noqa: E731
    stdt = struct.pack("<I", 1)
    stdt += struct.pack("<HH", (len(nodes) << 1) | 1, 8) + b"".join(nodes)
    stdt += struct.pack("<HH", (len(items) << 1) | 1, 16) + b"".join(g for _, g in items)
    stdt += struct.pack("<H", len(pool)) + pool
    stdt += struct.pack("<H", len(ends)) + b"".join(u24(e) for e in ends)
    stdt += struct.pack("<H", len(parents)) + b"".join(u24(p) for p in parents)
    return fev(0x92, [chunk(b"STDT", stdt)])


def build_beamng_root(root: Path) -> dict:
    """content/art_sound.zip with two stock events (a starter and a horn) and content/vehicles/common.zip."""
    rate = 44100
    events = {"event:/Engine/Starter/test_eng": [("starter_start_test", tone(180, 0.6))],
              "event:/Vehicle/Electrics/Horns/TEST_HORN": [("horn_start_test", tone(400, 0.1)),
                                                           ("horn_loop_test", tone(400, 0.6))]}
    paths = {path: guid() for path in events}
    meta = []
    wavs = []
    fsb_samples = []
    for path, takes in events.items():
        timeline = guid()
        meta.append(listing(b"EVNT", chunk(b"EVTB", paths[path] + b"\0" * 16 + timeline + b"\0" * 32)))
        meta.append(listing(b"TMLN", chunk(b"TLNB", timeline + paths[path] + b"\0" * 44)))
        for name, pcm in takes:
            inst, wave = guid(), guid()
            inst_body = bytearray(130)
            inst_body[0:16] = timeline
            meta.append(listing(b"WAIT", chunk(b"WAIB", inst + wave), chunk(b"INST", bytes(inst_body))))
            wavs.append(chunk(b"WAV ", wave + struct.pack("<HHH", 0x0C, 0, 0) + struct.pack("<I", len(fsb_samples)) + b"\0" * 4))
            fsb_samples.append((name, pcm, rate, 1))
    # An EV motor event: one loop on the timeline, re-pitched by RPM through a pitch automation on its master bus.
    motor_path = "event:/Engine/Bands/Real/test_motor"
    paths[motor_path] = guid()
    timeline, master, sheet, param, ctrl = guid(), guid(), guid(), guid(), guid()
    meta.append(listing(b"EVNT", chunk(b"EVTB", paths[motor_path] + b"\0" * 16 + timeline + b"\0" * 16 + master + b"\0" * 17 + sheet)))
    meta.append(listing(b"TMLN", chunk(b"TLNB", timeline + paths[motor_path] + b"\0" * 44)))
    meta.append(listing(b"PMLO", chunk(b"PMLB", sheet + param + b"\0" * 6)))
    meta.append(listing(b"PARM", chunk(b"PRMB", param + b"\0" * 8 + b"\x03\x00" + b"RPM" + struct.pack("<ff", 0.0, 50000.0) + b"\0" * 8)))
    meta.append(chunk(b"CTRL", ctrl + master + ctrl + struct.pack("<I", 1)))
    meta.append(chunk(b"CURV", guid() + ctrl + b"\x05\x00\x10\x00" + struct.pack("<ffff", 0.0, -1.0, 0, 0) + struct.pack("<ffff", 20000.0, 1.0, 0, 0)))
    inst, wave = guid(), guid()
    inst_body = bytearray(130)
    inst_body[0:16] = timeline
    meta.append(listing(b"WAIT", chunk(b"WAIB", inst + wave), chunk(b"INST", bytes(inst_body))))
    wavs.append(chunk(b"WAV ", wave + struct.pack("<HHH", 0x0C, 0, 0) + struct.pack("<I", len(fsb_samples)) + b"\0" * 4))
    fsb_samples.append(("motor_whine_test", tone(900, 1.0), rate, 1))
    vehicle_bank = fev(0x92, meta)
    assets_bank = fev(0x92, [listing(b"WAVS", *wavs)], build_fsb5(fsb_samples))
    strings = build_strings_bank(paths)
    content = root / "content"
    (content / "vehicles").mkdir(parents=True, exist_ok=True)
    with zipfile.ZipFile(content / "art_sound.zip", "w") as z:
        z.writestr("art/sound/fmod/desktop/main_preload.strings.bank", strings)
        z.writestr("art/sound/fmod/desktop/vehicle.bank", vehicle_bank)
        z.writestr("art/sound/fmod/desktop/vehicle.assets.bank", assets_bank)
        z.writestr("art/sound/blends/TestMotor.sfxBlend2D.json",
                   json.dumps({"header": {"version": 1}, "eventName": "event:>Engine>Bands>Real>test_motor", "samples": []}))
    soundscape = {"soundscape_horn_1": {"information": {"name": "Test horn"}, "slotType": "soundscape_horn",
                                        "soundscape": [["name", "src"], ["horn", "event:>Vehicle>Electrics>Horns>TEST_HORN"]]}}
    with zipfile.ZipFile(content / "vehicles" / "common.zip", "w") as z:
        z.writestr("vehicles/common/sounds/soundscape.jbeam", json.dumps(soundscape))
    return {"root": str(root)}


def build_beamng_mod(root: Path) -> dict:
    vehicle = root / "vehicles" / "testcar"
    vehicle.mkdir(parents=True, exist_ok=True)
    jbeam = {
        "testcar": {"information": {"name": "Test Car"}, "slotType": "main",
                    "slots": [["type", "default", "description"], ["testcar_engine", "testcar_engine", "Engine"],
                              ["soundscape_horn", "soundscape_horn_1", "Horn"]]},
        "testcar_engine": {"information": {"name": "2.0L I4 Engine"}, "slotType": "testcar_engine",
                           "mainEngine": {"torque": [["rpm", "torque"], [0, 0], [6000, 300]],
                                          "soundConfig": "soundConfig", "soundConfigExhaust": "soundConfigExhaust",
                                          "starterSample": "event:>Engine>Starter>test_eng"},
                           "soundConfig": {"sampleName": "TST"}, "soundConfigExhaust": {"sampleName": "0"}},
    }
    (vehicle / "testcar.jbeam").write_text(json.dumps(jbeam))
    (vehicle / "testcar.pc").write_text(json.dumps({"format": 2, "model": "testcar", "parts": {}}))
    blends = root / "art" / "sound" / "blends"
    engine = root / "art" / "sound" / "engine" / "TST"
    blends.mkdir(parents=True, exist_ok=True)
    engine.mkdir(parents=True, exist_ok=True)
    ladder = [["art/sound/engine/TST/1000.wav", 1000], ["art/sound/engine/TST/3000.wav", 3000]]
    (blends / "TST.sfxBlend2D.json").write_text(json.dumps({"eventName": "event:>Engine>default", "samples": [ladder, ladder]}))
    (engine / "1000.wav").write_bytes(wav(tone(1000 / 30, 0.5, channels=2), channels=2, malformed=True))
    (engine / "3000.wav").write_bytes(wav(tone(3000 / 30, 0.5), channels=1))
    # A second set the mod ships but no part names (an Automation export's leftover): reachable with --map ladder.blend.
    alt = root / "art" / "sound" / "engine" / "ALT"
    alt.mkdir(parents=True, exist_ok=True)
    (alt / "2000.wav").write_bytes(wav(tone(2000 / 30, 0.5)))
    (alt / "5000.wav").write_bytes(wav(tone(5000 / 30, 0.5)))
    alt_ladder = [["art/sound/engine/ALT/2000.wav", 2000], ["art/sound/engine/ALT/5000.wav", 5000]]
    (blends / "ALT.sfxBlend2D.json").write_text(json.dumps({"eventName": "event:>Engine>default", "samples": [alt_ladder, alt_ladder]}))
    sounds = vehicle / "sounds"
    sounds.mkdir(exist_ok=True)
    (sounds / "door_open.wav").write_bytes(wav(tone(800, 0.2)))
    return {"root": str(root)}


if __name__ == "__main__":
    kind, target = sys.argv[1], Path(sys.argv[2])
    target.mkdir(parents=True, exist_ok=True)
    result = {"ac": build_ac_bank, "beamng-root": build_beamng_root, "beamng-mod": build_beamng_mod}[kind](target)
    print(json.dumps(result))
