"""Extract a BeamNG mod's own engine recordings into HELIX vehicle-audio bank rows.

BeamNG names an engine sound by ``soundConfig.sampleName`` (and ``soundConfigExhaust.sampleName``).
That name resolves to ``art/sound/blends/<sampleName>.sfxBlend2D.json``. The blend is the whole
mapping from recordings to rpm::

    { "eventName": "event:>Engine>default",
      "samples": [ [ ["art/sound/engine/PSH/1768.wav", 1768], ["...", 2238], ... ],     # load row 0
                   [ ["art/sound/engine/PSH/1768.wav", 1768], ... ] ] }                # load row 1

Each row is an rpm-ordered ladder; the HELIX bank blend keeps the same ``[[file, rpm], ...]`` shape.

A ``sampleName`` with no blend file inside the mod is a stock game blend: its sfxBlend2D lives in the
game's ``content/art_sound.zip`` and its FLAC ladder in ``content/audio.zip``. ``sim_audio_beamng``
extracts it from there when the BeamNG install is given; without it nothing is extracted and nothing
is fabricated, and the slot reason names the stock blend that is needed.

Only real bytes are ever used. A 16-bit PCM WAV is copied verbatim (a malformed header is rebuilt
around the untouched sample data and recorded as a transform). OGG, FLAC and WAVs that are not
16-bit PCM are transcoded with ``ffmpeg`` (``pcm_s16le``, channels preserved); the conversion is
refused with a clear message when ``ffmpeg`` is not installed.

The full-sound-set importer (``helix vehicle audio-import``) builds on this module: see
``sim_audio_import.py``.
"""
from __future__ import annotations

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

from beamng_jbeam import parse_jbeam_text
from sim_audio import read_wav_header, write_pcm16_wav

BLEND_SUFFIX = ".sfxBlend2D.json"
BLEND_DIRECTORY = ("art", "sound", "blends")
MAX_BLEND_BYTES = 1024 * 1024
MAX_SAMPLE_FILES = 400
MAX_SAMPLE_BYTES = 128 * 1024 * 1024
MAX_TOTAL_BYTES = 768 * 1024 * 1024
MAX_WALK_ENTRIES = 200_000
BANK_RATES = (44100, 48000)
DEFAULT_RATE = 44100
ASSET_ROLE = "vehicle.audio.bank.sample"
TRANSCODE_EXTENSIONS = {".ogg", ".flac", ".mp3", ".opus", ".aif", ".aiff"}
# BeamNG treats a sampleName it cannot resolve as "no sound for this layer"; modders use "0".
DISABLED_SAMPLE_NAMES = {"", "0", "none", "null", "false"}


class AudioExtractionError(ValueError):
    """The mod ships audio the importer must not silently drop or guess at (refuse the import)."""


class AudioUnavailable(AudioExtractionError):
    """The mod's own blend is unusable (missing files, malformed ladder, over a limit).

    The importer keeps the platform fallback engine and records this text as the slot reason.
    """


# ---------------------------------------------------------------------------------------------
# WAV inspection
# ---------------------------------------------------------------------------------------------

def inspect_wav(path: Path) -> dict[str, int] | None:
    """Return ``{format, channels, rate, bits}`` for a RIFF/WAVE file, or ``None`` if it is not one.

    ``format`` is the effective format tag: WAVE_FORMAT_EXTENSIBLE is resolved to its sub-format.
    """
    try:
        with path.open("rb") as handle:
            head = handle.read(12)
            if len(head) < 12 or head[:4] != b"RIFF" or head[8:12] != b"WAVE":
                return None
            while True:
                chunk = handle.read(8)
                if len(chunk) < 8:
                    return None
                tag, size = chunk[:4], struct.unpack("<I", chunk[4:])[0]
                if tag == b"fmt ":
                    body = handle.read(min(size, 40))
                    if len(body) < 16:
                        return None
                    fmt, channels, rate, _byte_rate, _align, bits = struct.unpack("<HHIIHH", body[:16])
                    if fmt == 0xFFFE and len(body) >= 26:
                        fmt = struct.unpack("<H", body[24:26])[0]
                    return {"format": fmt, "channels": channels, "rate": rate, "bits": bits}
                handle.seek(size + (size & 1), os.SEEK_CUR)
    except OSError:
        return None


def is_runtime_pcm(info: dict[str, int] | None) -> bool:
    return bool(info) and info["format"] == 1 and info["bits"] == 16 and info["channels"] in (1, 2)


# ---------------------------------------------------------------------------------------------
# Source resolution
# ---------------------------------------------------------------------------------------------

def _is_safe_sample_name(name: str) -> bool:
    return bool(re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.\- ]{0,200}", name))


def _ci_child(directory: Path, name: str) -> Path | None:
    """Case-insensitive child lookup (BeamNG runs on Windows, so mods routinely mismatch case)."""
    exact = directory / name
    if os.path.lexists(exact):
        return exact
    lowered = name.lower()
    try:
        for entry in os.scandir(directory):
            if entry.name.lower() == lowered:
                return Path(entry.path)
    except OSError:
        return None
    return None


def confine(source_root: Path, portable: str) -> Path | None:
    """Resolve a mod-relative path inside ``source_root`` without following symlinks."""
    if not isinstance(portable, str):
        return None
    portable = portable.replace("\\", "/").lstrip("/") if not re.match(r"^[A-Za-z]:", portable) else ""
    if not portable:
        return None
    current = source_root
    for piece in portable.split("/"):
        if piece in ("", ".", ".."):
            return None
        found = _ci_child(current, piece)
        if found is None or found.is_symlink():
            return None
        current = found
    try:
        current.resolve().relative_to(source_root.resolve())
    except ValueError:
        return None
    return current if current.is_file() else None


def find_blend(source_root: Path, sample_name: str) -> Path | None:
    """The ``<sampleName>.sfxBlend2D.json`` the mod ships, or ``None`` when it is a stock event."""
    if not _is_safe_sample_name(sample_name):
        return None
    wanted = (sample_name + BLEND_SUFFIX).lower()
    standard = confine(source_root, "/".join((*BLEND_DIRECTORY, sample_name + BLEND_SUFFIX)))
    if standard is not None:
        return standard
    seen = 0
    for directory, subdirectories, files in os.walk(source_root, followlinks=False):
        subdirectories[:] = [d for d in subdirectories if not os.path.islink(os.path.join(directory, d))]
        for name in files:
            seen += 1
            if seen > MAX_WALK_ENTRIES:
                return None
            if name.lower() == wanted and not os.path.islink(os.path.join(directory, name)):
                return Path(directory, name)
    return None


def parse_blend(path: Path) -> dict[str, Any]:
    """Parse a sfxBlend2D file into ``{eventName, ladders: [[[portable, rpm], ...], ...]}``.

    Rpm values come straight from the file. Each ladder is sorted by rpm; a ladder with fewer than
    two distinct rungs, a non-numeric rpm or a duplicate rpm is refused rather than repaired.
    """
    if path.stat().st_size > MAX_BLEND_BYTES:
        raise AudioUnavailable(f"sound blend {path.name} exceeds {MAX_BLEND_BYTES} bytes")
    try:
        body, _ = parse_jbeam_text(path.read_text(errors="ignore"))
    except (ValueError, json.JSONDecodeError) as error:
        raise AudioUnavailable(f"sound blend {path.name} is not valid JSON: {error}") from error
    rows = body.get("samples")
    if not isinstance(rows, list) or not rows:
        raise AudioUnavailable(f"sound blend {path.name} has no `samples` ladders")
    ladders: list[list[list[Any]]] = []
    for row_index, row in enumerate(rows):
        if not isinstance(row, list) or not row:
            raise AudioUnavailable(f"sound blend {path.name} ladder {row_index} is empty")
        ladder: list[list[Any]] = []
        for rung in row:
            if (not isinstance(rung, list) or len(rung) < 2 or not isinstance(rung[0], str) or not rung[0]
                    or isinstance(rung[1], bool) or not isinstance(rung[1], (int, float)) or rung[1] <= 0):
                raise AudioUnavailable(
                    f"sound blend {path.name} ladder {row_index} has a rung that is not [file, rpm]: {rung!r}")
            rpm = rung[1]
            ladder.append([rung[0], int(rpm) if float(rpm).is_integer() else float(rpm)])
        ladder.sort(key=lambda rung: rung[1])
        rpms = [rung[1] for rung in ladder]
        if len(set(rpms)) != len(rpms):
            raise AudioUnavailable(f"sound blend {path.name} ladder {row_index} repeats an rpm value")
        ladders.append(ladder)
    event = body.get("eventName")
    return {"eventName": event if isinstance(event, str) and event else "event:>Engine>default", "ladders": ladders}


# ---------------------------------------------------------------------------------------------
# Transcoding
# ---------------------------------------------------------------------------------------------

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")


def transcode_to_pcm16(ffmpeg: str, source: Path, target: Path, rate: int | None) -> None:
    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)]
    command.append(str(target))
    try:
        result = subprocess.run(command, capture_output=True, text=True, timeout=180)
    except subprocess.TimeoutExpired as error:
        raise AudioExtractionError(f"ffmpeg timed out transcoding {source.name}") from error
    if result.returncode != 0 or not target.is_file() or target.stat().st_size == 0:
        raise AudioExtractionError(f"ffmpeg could not transcode {source.name}: {result.stderr.strip()[:300]}")


def repair_wav_header(source: Path, target: Path) -> list[dict[str, Any]]:
    """Copy a 16-bit PCM WAV, rebuilding a malformed header around the untouched sample bytes.

    The mmbng 993 mod's PSH ladder declares 2 channels with the byteRate/blockAlign of mono; decoders that trust
    blockAlign read twice the frames at the wrong pitch. Returns the transforms applied (empty for a clean copy).
    """
    data = source.read_bytes()
    header = read_wav_header(data)
    if header is None or not header["problems"]:
        shutil.copyfile(source, target)
        return []
    start, end = header["data"]
    write_pcm16_wav(target, data[start:end], header["rate"], header["channels"])
    return [{"kind": "wav-header-repair", "detail": "; ".join(header["problems"]),
             "note": "header rebuilt from channels/bits/rate; sample bytes untouched"}]


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


def asset_file_name(source_path: str, taken: dict[str, str], source_digest: str) -> str:
    """A portable ``<stem>.wav`` name. Bare numbers (``1768.wav``) take their folder as a prefix and a
    name already used by different bytes gets the content hash appended, so names stay unique."""
    clean = lambda value: re.sub(r"[^A-Za-z0-9._-]+", "_", value).strip("._-")  # noqa: E731
    path = Path(source_path.replace("\\", "/"))
    stem = clean(path.stem) or "sample"
    if stem.isdigit() and clean(path.parent.name):
        stem = f"{clean(path.parent.name)}_{stem}"
    name = f"{stem}.wav"
    if taken.get(name, source_digest) != source_digest:
        name = f"{stem}-{source_digest[:8]}.wav"
    return name


# ---------------------------------------------------------------------------------------------
# Public entry point
# ---------------------------------------------------------------------------------------------

def stock_reason(event: str) -> str:
    return (f"source uses BeamNG stock FMOD event {event}; no recording ships in the mod "
            "— platform fallback engine")


def resolve_layers(source_root: Path, engine_name: str | None, exhaust_name: str | None) -> dict[str, Any]:
    """Classify the engine and exhaust layers as shipped-in-the-mod, stock-only, or absent."""
    layers: dict[str, Any] = {}
    for layer, name in (("engine", engine_name), ("exhaust", exhaust_name)):
        clean = name.strip() if isinstance(name, str) else ""
        if clean.lower() in DISABLED_SAMPLE_NAMES:
            layers[layer] = {"state": "absent", "name": clean or None}
            continue
        blend = find_blend(source_root, clean)
        layers[layer] = ({"state": "shipped", "name": clean, "blend": blend} if blend is not None
                         else {"state": "stock", "name": clean})
    return layers


def extract_engine_bank(source_root: Path, layers: dict[str, Any], audio_dir: Path,
                        ffmpeg: str | None = None) -> dict[str, Any]:
    """Write the WAVs for every shipped layer into ``audio_dir`` and return the bank description.

    Returns ``{"blends": {NAME: {eventName, samples}}, "assets": [row, ...], "sources": [...],
    "blendNames": {"engine": NAME | None, "exhaust": NAME | None}}``. Raises ``AudioExtractionError``
    when the mod ships audio that cannot be turned into a faithful PCM WAV.
    """
    source_root = source_root.resolve()
    shipped: dict[str, dict[str, Any]] = {}
    for layer, info in layers.items():
        if info["state"] != "shipped":
            continue
        parsed = parse_blend(info["blend"])
        shipped[info["name"]] = {"parsed": parsed, "blend": info["blend"]}

    # Gather every distinct recording the shipped blends name, in blend then ladder order.
    resolved: dict[str, Path] = {}
    for name, entry in shipped.items():
        missing: list[str] = []
        for ladder in entry["parsed"]["ladders"]:
            for portable, _rpm in ladder:
                if portable in resolved:
                    continue
                path = confine(source_root, portable)
                if path is None:
                    missing.append(portable)
                else:
                    resolved[portable] = path
        if missing:
            raise AudioUnavailable(
                f"sound blend {name} names {len(missing)} recording(s) the mod does not contain, "
                f"for example {missing[0]}")
    if len(resolved) > MAX_SAMPLE_FILES:
        raise AudioUnavailable(f"the mod's engine blends name {len(resolved)} recordings (limit {MAX_SAMPLE_FILES})")
    total = 0
    inspected: dict[str, dict[str, int] | None] = {}
    for portable, path in resolved.items():
        size = path.stat().st_size
        if size > MAX_SAMPLE_BYTES:
            raise AudioUnavailable(f"recording {portable} is {size} bytes (limit {MAX_SAMPLE_BYTES})")
        total += size
        inspected[portable] = inspect_wav(path)
    if total > MAX_TOTAL_BYTES:
        raise AudioUnavailable(f"the mod's engine recordings total {total} bytes (limit {MAX_TOTAL_BYTES})")

    # One bank sample rate: the most common rate among the recordings, else 44.1 kHz.
    rates = Counter(info["rate"] for info in inspected.values() if info)
    bank_rate = next((rate for rate, _ in sorted(rates.items(), key=lambda kv: (-kv[1], kv[0]))
                      if rate in BANK_RATES), DEFAULT_RATE)

    def needs_transcode(portable: str) -> tuple[bool, int | None]:
        info = inspected[portable]
        if info is None or not is_runtime_pcm(info):
            return True, bank_rate if (info is None or info["rate"] != bank_rate) else None
        return (info["rate"] != bank_rate), (bank_rate if info["rate"] != bank_rate else None)

    ffmpeg_needed = [p for p in resolved if needs_transcode(p)[0]]
    if ffmpeg_needed and ffmpeg is None:
        raise AudioExtractionError(
            f"{len(ffmpeg_needed)} engine recording(s) (for example {ffmpeg_needed[0]}) are not 16-bit PCM WAV "
            f"at {BANK_RATES[0]}/{BANK_RATES[1]} Hz and need ffmpeg to convert; install ffmpeg (or set "
            "HELIX_FFMPEG) and run the import again. The importer never ships OGG/FLAC or fabricates samples.")

    audio_dir.mkdir(parents=True, exist_ok=True)
    names_by_source: dict[str, str] = {}
    digest_by_name: dict[str, str] = {}
    rows: dict[str, dict[str, Any]] = {}
    sources: list[dict[str, Any]] = []
    with tempfile.TemporaryDirectory(prefix="beamng-audio-") as scratch:
        for portable, path in resolved.items():
            source_digest, _ = sha256_bytes(path)
            name = asset_file_name(portable, digest_by_name, source_digest)
            digest_by_name[name] = source_digest
            names_by_source[portable] = name
            target = audio_dir / name
            transcode, rate = needs_transcode(portable)
            transforms: list[dict[str, Any]] = []
            if transcode:
                staged = Path(scratch) / name
                transcode_to_pcm16(ffmpeg, path, staged, rate)  # type: ignore[arg-type]
                shutil.move(str(staged), target)
            else:
                transforms = repair_wav_header(path, target)
            checksum, size = sha256_bytes(target)
            rows[name] = {"name": name, "file": name, "path": f"audio/{name}", "role": ASSET_ROLE,
                          "mediaType": "audio/wav", "bytes": size, "checksumSha256": checksum,
                          "cid": f"cid:sha256:{checksum}"}
            sources.append({"asset": name, "sourcePath": portable, "sourceSha256": source_digest,
                            "transcoded": transcode, "transforms": transforms})

    blends: dict[str, dict[str, Any]] = {}
    for name, entry in shipped.items():
        blends[name] = {"eventName": entry["parsed"]["eventName"],
                        "samples": [[[names_by_source[portable], rpm] for portable, rpm in ladder]
                                    for ladder in entry["parsed"]["ladders"]]}
    return {"blends": blends, "assets": [rows[name] for name in sorted(rows)], "sources": sources,
            "sampleRate": bank_rate,
            "blendNames": {layer: (info["name"] if info["state"] == "shipped" else None)
                           for layer, info in layers.items()}}
