"""Shared pieces of the sim-audio importer: the HELIX slot vocabulary, sample-name -> slot rules, and WAV hygiene.

Every sound the importer emits is a real recording taken from a simulator's files. The only byte changes ever made:
  * a malformed WAV header is rewritten around the untouched sample data (``wav-header-repair``);
  * a non-PCM16 source (OGG, FLAC, 24-bit, float, FMOD-compressed) is decoded to 16-bit PCM (``decode``);
  * an FMOD auto-pitched engine sample is played back at the rpm its event places it, exactly as FMOD would
    (``fmod-autopitch-varispeed``, a sample-rate change, see ``varispeed``).
Each one is recorded in the provenance ``transforms`` list. Nothing is generated, filtered, mixed or synthesised.
"""
from __future__ import annotations

import hashlib
import os
import re
import shutil
import struct
import subprocess
import tempfile
from pathlib import Path
from typing import Any

# The HELIX vehicle audio slots (humanoid-character/src/core/vehicle/package/format.ts VehicleAudioSlot).
SLOTS = (
    "engineLadder", "exhaustLadder", "idle", "startup", "shutdown", "shiftUp", "shiftDown", "clutch",
    "transmissionWhine", "turboSpool", "blowOff", "intake", "revLimiter", "backfire", "suspension",
    "impactLight", "impactMedium", "impactHeavy", "tyreRollSlow",
    "tyreRollFast", "indicatorTick", "handbrake", "reverseBeep", "horn", "doorOpen",
    "doorClose",
)
# Retired: the engine plays no tyre squeal, scrub, wheelspin, skid or brake squeal. Never extracted or emitted; a sound
# whose name says so is dropped, not filed under another slot.
RETIRED_SLOTS = ("tyreSqueal", "tyreScrub", "tyreSpin", "skid", "brakeSqueal")
# Buffer names the runtime plays a slot's sample under (engine-core addonAudio PACKAGE_SLOT_TO_RUNTIME_SOUND,
# VehicleAudio VEHICLE_SOUNDS / VEHICLE_TRANSMISSION_SLOTS / VEHICLE_INDUCTION_SLOTS).
SLOT_BUFFER = {
    "startup": "vehicle.ignition", "shutdown": "vehicle.shutdown", "shiftUp": "vehicle.shift.up",
    "shiftDown": "vehicle.shift.down", "clutch": "vehicle.clutch", "transmissionWhine": "vehicle.transmission.whine",
    "turboSpool": "vehicle.turbo.whine", "blowOff": "vehicle.turbo.blowoff", "intake": "vehicle.intake",
    "revLimiter": "vehicle.rev-limiter", "backfire": "vehicle.backfire", "suspension": "vehicle.suspension",
    "impactLight": "vehicle.impact.light", "impactMedium": "vehicle.impact.medium",
    "impactHeavy": "vehicle.impact.heavy",
    "tyreRollSlow": "vehicle.tyre.roll.slow", "tyreRollFast": "vehicle.tyre.roll.fast",
    "indicatorTick": "vehicle.indicator.tick",
    "handbrake": "vehicle.handbrake", "reverseBeep": "vehicle.reverse-beep", "horn": "vehicle.horn",
    "doorOpen": "vehicle.door.open", "doorClose": "vehicle.door.close", "idle": "vehicle.idle",
}
# Slots a recording can be bound to but that today's portable runtime does not play from a package.
NOT_CONSUMED = {
    "transmissionWhine": ("the runtime plays a recorded gear whine only with a declared native pitch "
                          "(gearWhineNativeHz), which a vehicle package cannot carry yet"),
    "intake": "the portable runtime has no intake layer",
    "idle": "idle plays from the engine ladder's lowest rung; there is no separate idle one-shot",
}

# Sample/file name -> slot. Ordered: the first rule that matches wins. Used for FMOD subsong names (Assetto Corsa:
# horn, door_open, gearupEXT, blowoff_2, limiter, backfireEXT_3, skid_ext_mono, tyre_rolling, Ferruccio_trans ...)
# and for files a mod ships under art/sound/**. Engine ladder samples are classified separately.
NAME_RULES: tuple[tuple[str, str], ...] = (
    (r"door.?open", "doorOpen"),
    (r"door.?clos", "doorClose"),
    (r"horn", "horn"),
    (r"(rev.?)?limiter", "revLimiter"),
    (r"blow.?off|\bbov\b|flutter|dump.?valve", "blowOff"),
    (r"turbo|spool|whistle", "turboSpool"),
    (r"backfire|afterfire|after.?fire|\bpop", "backfire"),
    (r"gear.?up|shift.?up|upshift", "shiftUp"),
    (r"gear.?(dn|down)|shift.?(dn|down)|downshift", "shiftDown"),
    (r"miss.?gear|grind", ""),
    (r"trans(mission)?|gear.?whine|\bwhine", "transmissionWhine"),
    (r"skid|squeal.*tyre|tyre.*squeal", ""),  # retired: the engine has no tyre squeal
    (r"tyre.?roll|tire.?roll|rolling", "tyreRollSlow"),
    (r"handbrake|hand.?brake|ratchet", "handbrake"),
    (r"brake", ""),  # retired: the engine has no brake squeal
    (r"shut.?(off|down)|engine.?stop|ignition.?off", "shutdown"),
    (r"starter|ignition|crank|start.?up", "startup"),
    (r"clutch", "clutch"),
    (r"indicator|blinker|turn.?signal|ind.?loop|relay", "indicatorTick"),
    (r"reverse.?beep|backup.?beep|beep", "reverseBeep"),
    (r"intake|induction", "intake"),
    (r"suspension|spring|bump", "suspension"),
)


def slot_for_name(name: str) -> str | None:
    text = name.lower().replace("-", "_")
    for pattern, slot in NAME_RULES:
        if re.search(pattern, text):
            return slot or None
    return None


def exterior_rank(name: str) -> int:
    """Lower is better: exterior takes, then unlabelled, then interior (Kunos: EXT/ext/ex vs int/in)."""
    text = name.lower()
    if re.search(r"(^|[_ .-])(ext|ex|exterior|outside)([_ .-]|$)|ext(_|$)|ext\d|[a-z]ext\b", text) or text.endswith("ext"):
        return 0
    if re.search(r"(^|[_ .-])(int|in|interior|inside|cabin)([_ .-]|$)", text):
        return 2
    return 1


def sha256_file(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as handle:
        for chunk in iter(lambda: handle.read(1024 * 1024), b""):
            digest.update(chunk)
    return digest.hexdigest()


def locate_ffmpeg() -> str | None:
    explicit = os.environ.get("HELIX_FFMPEG")
    if explicit:
        return explicit if os.access(explicit, os.X_OK) else None
    return shutil.which("ffmpeg")


# ---------------------------------------------------------------------------------------------
# WAV hygiene
# ---------------------------------------------------------------------------------------------

def read_wav_header(data: bytes) -> dict[str, Any] | None:
    """Parse the RIFF chunk list. Returns fmt fields, the data chunk span and what is inconsistent, or None."""
    if len(data) < 12 or data[:4] != b"RIFF" or data[8:12] != b"WAVE":
        return None
    offset = 12
    fmt: dict[str, int] | None = None
    data_span: tuple[int, int] | None = None
    problems: list[str] = []
    while offset + 8 <= len(data):
        cid = data[offset:offset + 4]
        size = struct.unpack_from("<I", data, offset + 4)[0]
        body = offset + 8
        if cid == b"fmt " and size >= 16:
            tag, channels, rate, byte_rate, align, bits = struct.unpack_from("<HHIIHH", data, body)
            if tag == 0xFFFE and size >= 26:
                tag = struct.unpack_from("<H", data, body + 24)[0]
            fmt = {"format": tag, "channels": channels, "rate": rate, "byteRate": byte_rate, "blockAlign": align,
                   "bits": bits}
        elif cid == b"data":
            end = body + size
            if end > len(data):
                problems.append(f"data chunk declares {size} bytes but only {len(data) - body} follow")
                end = len(data)
            data_span = (body, end)
            break
        offset = body + size + (size & 1)
    if fmt is None or data_span is None:
        return None
    riff = struct.unpack_from("<I", data, 4)[0]
    if riff + 8 != len(data):
        problems.append(f"RIFF size {riff + 8} != file size {len(data)}")
    if fmt["format"] == 1 and fmt["channels"] and fmt["bits"]:
        align = fmt["channels"] * fmt["bits"] // 8
        if fmt["blockAlign"] != align:
            problems.append(f"blockAlign {fmt['blockAlign']} != channels*bits/8 = {align}")
        if fmt["byteRate"] != fmt["rate"] * align:
            problems.append(f"byteRate {fmt['byteRate']} != rate*blockAlign = {fmt['rate'] * align}")
        if (data_span[1] - data_span[0]) % align:
            problems.append("data length is not a whole number of frames")
    return {**fmt, "data": data_span, "problems": problems}


def write_pcm16_wav(target: Path, pcm: bytes, rate: int, channels: int) -> None:
    align = channels * 2
    pcm = pcm[:len(pcm) - len(pcm) % align]
    header = b"RIFF" + struct.pack("<I", 36 + len(pcm)) + b"WAVE" + b"fmt " + struct.pack(
        "<IHHIIHH", 16, 1, channels, rate, rate * align, align, 16) + b"data" + struct.pack("<I", len(pcm))
    target.write_bytes(header + pcm)


def normalize_wav(source: Path, target: Path, ffmpeg: str | None = None, rate: int | None = None) -> list[dict[str, Any]]:
    """Write ``source`` to ``target`` as a canonical 16-bit PCM WAV; return the transforms applied (may be empty).

    * already canonical PCM16 at the wanted rate: copied byte for byte;
    * PCM16 with a malformed header (the mmbng 993 mod ships byteRate/blockAlign for mono on stereo files): the
      header is rebuilt from channels/bits/rate around the exact sample bytes;
    * anything else (OGG, FLAC, MP3, 8/24/32-bit, float) or a rate change: decoded with ffmpeg to pcm_s16le, channels
      kept. Refused with an install message when ffmpeg is missing.
    """
    data = source.read_bytes()
    header = read_wav_header(data)
    transforms: list[dict[str, Any]] = []
    if header and header["format"] == 1 and header["bits"] == 16 and header["channels"] in (1, 2) \
            and (rate is None or header["rate"] == rate):
        if not header["problems"]:
            if target != source:
                shutil.copyfile(source, target)
            return transforms
        start, end = header["data"]
        write_pcm16_wav(target, data[start:end], header["rate"], header["channels"])
        transforms.append({"kind": "wav-header-repair", "detail": "; ".join(header["problems"]),
                           "note": "header rebuilt from channels/bits/rate; sample bytes untouched"})
        return transforms
    ffmpeg = ffmpeg or locate_ffmpeg()
    if not ffmpeg:
        raise ValueError(f"{source.name} is not 16-bit PCM WAV and ffmpeg is needed to decode it; install ffmpeg "
                         "(or set HELIX_FFMPEG) and run the import again")
    command = [ffmpeg, "-nostdin", "-v", "error", "-y", "-i", str(source), "-map", "0:a:0", "-c:a", "pcm_s16le",
               "-fflags", "+bitexact", "-flags:a", "+bitexact"]
    if rate:
        command += ["-ar", str(rate)]
    with tempfile.TemporaryDirectory(prefix="helix-wav-") as scratch:
        staged = Path(scratch) / "out.wav"
        result = subprocess.run(command + [str(staged)], capture_output=True, text=True, timeout=300)
        if result.returncode != 0 or not staged.is_file():
            raise ValueError(f"ffmpeg could not decode {source.name}: {result.stderr.strip()[:300]}")
        shutil.move(str(staged), target)
    what = "WAV" if header else (data[:4].decode("latin-1", errors="replace") or "audio")
    transforms.append({"kind": "decode", "detail": f"{what} -> 16-bit PCM WAV" + (f" at {rate} Hz" if rate else ""),
                       "tool": "ffmpeg"})
    return transforms


def varispeed(source: Path, target: Path, ratio: float, ffmpeg: str | None = None) -> dict[str, Any]:
    """Play ``source`` at ``ratio`` times its speed (pitch and tempo together, as FMOD auto-pitch does), same rate."""
    ffmpeg = ffmpeg or locate_ffmpeg()
    if not ffmpeg:
        raise ValueError("re-pitching an FMOD auto-pitched sample to the rpm its event plays it at needs ffmpeg; "
                         "install ffmpeg (or set HELIX_FFMPEG), or pass --ac-native-rungs to keep only rungs the "
                         "bank places at their recorded pitch")
    header = read_wav_header(source.read_bytes())
    if not header:
        raise ValueError(f"{source.name} is not a WAV")
    rate = header["rate"]
    with tempfile.TemporaryDirectory(prefix="helix-vari-") as scratch:
        staged = Path(scratch) / "out.wav"
        result = subprocess.run([ffmpeg, "-nostdin", "-v", "error", "-y", "-i", str(source), "-af",
                                 f"asetrate={rate * ratio:.6f},aresample={rate}:resampler=soxr" if _has_soxr(ffmpeg)
                                 else f"asetrate={rate * ratio:.6f},aresample={rate}",
                                 "-c:a", "pcm_s16le", "-fflags", "+bitexact", "-flags:a", "+bitexact", str(staged)],
                                capture_output=True, text=True, timeout=300)
        if result.returncode != 0 or not staged.is_file():
            raise ValueError(f"ffmpeg could not re-pitch {source.name}: {result.stderr.strip()[:300]}")
        shutil.move(str(staged), target)
    return {"kind": "fmod-autopitch-varispeed", "ratio": round(ratio, 6), "tool": "ffmpeg asetrate+aresample"}


_SOXR: dict[str, bool] = {}


def _has_soxr(ffmpeg: str) -> bool:
    if ffmpeg not in _SOXR:
        try:
            out = subprocess.run([ffmpeg, "-hide_banner", "-buildconf"], capture_output=True, text=True, timeout=30).stdout
            _SOXR[ffmpeg] = "libsoxr" in out
        except (OSError, subprocess.TimeoutExpired):
            _SOXR[ffmpeg] = False
    return _SOXR[ffmpeg]


def staged_name(stem: str, digest: str) -> str:
    clean = re.sub(r"[^A-Za-z0-9._-]+", "_", stem).strip("._-") or "sample"
    return f"{clean[:80]}-{digest[:8]}.wav"
