"""Assetto Corsa / ACC car sound banks -> HELIX engine ladders and slots.

A Kunos car ships ``content/cars/<car>/sfx/<car>.bank`` (FMOD Studio 1.x: event metadata and the FSB5 samples in one
file) and the game lists every event path in ``content/sfx/GUIDs.txt``. The events a car carries are fixed by the
game: ``engine_ext`` / ``engine_int`` (rpm x throttle parameter sheets), ``gear_ext``/``gear_int``, ``turbo``,
``backfire_ext``/``backfire_int``, ``limiter``, ``horn``, ``door``, ``skid_ext``/``skid_int``, ``wheel``,
``transmission``, ``gear_grind``, ``bodywork``, ``wind``, ``tractioncontrol_*``.

The engine ladder comes from the ``rpms`` sheet of the engine event. Each sample sits on that sheet with an
auto-pitch reference (the rpm it was recorded at) and volume fades that make it the dominant voice over a plateau.
Kunos records several takes at one reference rpm (the F40's exterior on-throttle set is four 4,600 rpm takes) and
spreads them over the rev range by auto-pitch, so a HELIX rung (one recording per rpm, the runtime re-pitches between
rungs) is built per instrument as:

  * reference rpm inside the plateau -> the rung is the recording itself at its reference rpm (no change);
  * otherwise -> the rung is the recording as FMOD plays it at the plateau's anchor rpm (``varispeed`` by
    anchor / reference, recorded as a transform), unless ``native_only`` keeps only the unchanged rungs.

Rows follow the engine: row 0 = off-throttle (``_off_`` samples), row 1 = on-throttle (``_on_``); a sample without
either (``idle``, ``max``) joins the row of the instruments on its mixer bus, else both rows when it is an idle take.
"""
from __future__ import annotations

import re
import shutil
from pathlib import Path
from typing import Any

import fmod_studio
import fsb5
from sim_audio import exterior_rank, normalize_wav, sha256_file, slot_for_name, staged_name, varispeed

# Event leaf -> the HELIX slots its samples may fill (name rules pick between them). Empty = deliberately unmapped.
EVENT_SLOTS: dict[str, tuple[str, ...]] = {
    "backfire": ("backfire",), "door": ("doorOpen", "doorClose"), "gear": ("shiftUp", "shiftDown"),
    "horn": ("horn",), "limiter": ("revLimiter",), "skid": (), "transmission": ("transmissionWhine",),
    "turbo": ("turboSpool", "blowOff"), "wheel": ("tyreRollSlow",),
    "gear_grind": (), "bodywork": (), "wind": (), "tractioncontrol": (),
}
ENGINE_EVENTS = ("engine_ext", "engine_int")


def _event_leaf(path: str | None) -> tuple[str, str]:
    """``event:/cars/ferrari_f40/backfire_ext`` -> (``backfire``, ``ext``)."""
    leaf = (path or "").rsplit("/", 1)[-1].lower()
    match = re.match(r"(.+?)_(ext|int)$", leaf)
    return (match.group(1), match.group(2)) if match else (leaf, "")


def _natural(name: str) -> list[Any]:
    return [int(t) if t.isdigit() else t.lower() for t in re.split(r"(\d+)", name)]


def _row_of(name: str) -> str | None:
    text = name.lower()
    if re.search(r"(^|_)on(_|$)", text):
        return "on"
    if re.search(r"(^|_)off(_|$)", text):
        return "off"
    return None


def car_bank(source: Path) -> tuple[Path, Path | None, str]:
    """Resolve an AC car dir / sfx dir / bare .bank to (bank, GUIDs.txt or None, car id)."""
    if source.is_file() and source.suffix.lower() == ".bank":
        bank = source
        car = bank.stem
    else:
        sfx = source / "sfx" if (source / "sfx").is_dir() else source
        banks = sorted(p for p in sfx.glob("*.bank") if not p.name.endswith(".strings.bank"))
        if not banks:
            raise ValueError(f"{source} has no sfx/<car>.bank (an Assetto Corsa car this install owns ships one; a "
                             "car with only a ui/ folder is a DLC that is not installed)")
        car = source.parent.name if source.name.lower() == "sfx" else source.name
        bank = next((b for b in banks if b.stem.lower() == car.lower()), banks[0])
    guids = None
    for parent in [bank.parent, *bank.parents]:
        for candidate in (parent / "GUIDs.txt", parent / "sfx" / "GUIDs.txt", parent / "content" / "sfx" / "GUIDs.txt"):
            if candidate.is_file():
                guids = candidate
                break
        if guids:
            break
    return bank, guids, car


class AcInventory:
    def __init__(self, source: Path, staging: Path, options: dict[str, Any]):
        self.source = source
        self.staging = staging
        self.options = options
        self.bank_path, self.guids_path, self.car = car_bank(source)
        self.bank = fsb5.read_bank(self.bank_path)
        self.names = {s.index: s for s in self.bank.samples}
        self.warnings: list[str] = []
        self.meta: fmod_studio.BankMetadata | None = None
        try:
            paths = fmod_studio.read_guids_txt(self.guids_path, self.car) if self.guids_path else None
            self.meta = fmod_studio.read_metadata(self.bank_path, paths)
        except fmod_studio.FmodMetadataError as error:
            self.warnings.append(f"event metadata unreadable ({error}); slots are mapped by sample name only and no "
                                 "engine ladder is built (pass rung rpms with --map ladder.rpm)")
        self.decoded: dict[int, tuple[Path, str]] = {}
        self.decoder = None

    # -- provenance ---------------------------------------------------------------------------------------------
    def provenance(self, sample: fsb5.FsbSample, event: str | None, transforms: list[dict[str, Any]],
                   decoder: str) -> dict[str, Any]:
        root = self.source if self.source.is_dir() else self.bank_path.parent
        try:
            rel = self.bank_path.resolve().relative_to(root.resolve().parent).as_posix()
        except ValueError:
            rel = self.bank_path.name
        row: dict[str, Any] = {
            "kind": "sim-official", "sim": "assetto-corsa", "mod": self.car,
            "sourceFile": rel, "sourceSha256": self.bank.sha256,
            "sample": sample.name, "subsong": sample.index,
            "extractor": f"helix sim_audio_ac + {decoder}",
        }
        if self.options.get("modUrl"):
            row["modUrl"] = self.options["modUrl"]
        if self.options.get("kind"):
            row["kind"] = self.options["kind"]
        if event:
            row["event"] = event
        if transforms:
            row["transforms"] = transforms
        return row

    def decode(self, sample: fsb5.FsbSample) -> tuple[Path, list[dict[str, Any]], str]:
        if sample.index not in self.decoded:
            raw = self.staging / f"raw-{sample.index}.wav"
            decoder = fsb5.decode_sample(self.bank, sample, raw, self.options.get("vgmstream"))
            self.decoded[sample.index] = (raw, decoder)
        raw, decoder = self.decoded[sample.index]
        out = self.staging / f"norm-{sample.index}.wav"
        transforms = normalize_wav(raw, out)
        return out, transforms, decoder

    def emit(self, sample: fsb5.FsbSample, event: str | None, ratio: float = 1.0) -> dict[str, Any]:
        path, transforms, decoder = self.decode(sample)
        transforms = [*transforms, {"kind": "decode", "detail": f"FMOD {sample.codec} subsong -> 16-bit PCM WAV"}] \
            if sample.codec != "pcm16" else transforms
        if abs(ratio - 1) > 1e-4:
            pitched = self.staging / f"vari-{sample.index}-{ratio:.5f}.wav"
            transforms = [*transforms, varispeed(path, pitched, ratio)]
            path = pitched
        digest = sha256_file(path)
        final = self.staging / staged_name(sample.name if abs(ratio - 1) <= 1e-4 else f"{sample.name}_x{ratio:.3f}", digest)
        if not final.exists():
            shutil.copyfile(path, final)
        return {"wav": str(final), "provenance": self.provenance(sample, event, transforms, decoder)}

    # -- engine ladder ------------------------------------------------------------------------------------------
    def ladder(self) -> tuple[dict[str, Any] | None, list[str]]:
        notes: list[str] = []
        if self.meta is None:
            return None, ["no readable event metadata: rung rpms cannot be read from the bank"]
        prefer = self.options.get("prefer", "exterior")
        order = ENGINE_EVENTS if prefer != "interior" else tuple(reversed(ENGINE_EVENTS))
        event = None
        for leaf in order:
            event = next((e for e in self.meta.events if e.path and e.path.lower().endswith("/" + leaf)), None)
            if event and any(i.autopitch for i in event.instruments):
                break
            event = None
        if event is None and not any(e.path for e in self.meta.events):
            # No GUIDs.txt beside the bank: the engine events are the ones with auto-pitched rpm instruments; their
            # sample names say which is the exterior set (Kunos: F40_ex_* / F40_in_*).
            engines = [e for e in self.meta.events if sum(1 for i in e.instruments if i.autopitch) >= 2]
            def side(e: fmod_studio.EventInfo) -> float:
                ranks = [exterior_rank(self.names[i.subsound].name) for i in e.instruments if i.subsound is not None]
                return sum(ranks) / max(1, len(ranks))
            engines.sort(key=side, reverse=prefer == "interior")
            event = engines[0] if engines else None
            if event is not None:
                notes.append("no GUIDs.txt beside the bank: the engine event was chosen by its sample names "
                             f"({'interior' if side(event) > 1 else 'exterior'} set)")
        if event is None:
            return None, ["the bank has no engine_ext / engine_int event with auto-pitched rpm samples"]
        rpm_sheet = next((s for s in event.sheets if (s.parameter_name or "").lower() in ("rpms", "rpm")), None)
        instruments = [i for i in event.instruments if i.autopitch and i.subsound is not None
                       and (rpm_sheet is None or i.sheet == rpm_sheet.guid)]
        overrides: dict[str, float] = {str(k): float(v) for k, v in (self.options.get("rpm") or {}).items()}
        native_only = bool(self.options.get("nativeOnly"))
        # Row membership: name, else the mixer bus shared with named instruments (not exposed here: fall back to
        # "both" for idle takes, "on" otherwise, and say so).
        rows: dict[str, list[dict[str, Any]]] = {"off": [], "on": []}
        for instrument in instruments:
            sample = self.names[instrument.subsound]
            row = _row_of(sample.name)
            targets = [row] if row else (["off", "on"] if "idle" in sample.name.lower() else ["on"])
            if not row and "idle" not in sample.name.lower():
                notes.append(f"{sample.name}: no _on_/_off_ in its name; placed on the on-throttle row")
            ref = float(instrument.autopitch)
            lo, hi = instrument.plateau() if instrument.fades else (float("-inf"), float("inf"))
            if sample.name in overrides:
                rung, how = overrides[sample.name], "--map ladder.rpm override"
            elif lo <= ref <= hi:
                rung, how = ref, "recorded at its auto-pitch reference, inside its plateau"
            else:
                rung = (lo + hi) / 2 if lo > float("-inf") and hi < float("inf") else (lo if lo > float("-inf") else hi)
                how = f"plateau {lo:g}-{hi:g} rpm; auto-pitch reference {ref:g} rpm"
            for target in targets:
                rows[target].append({"instrument": instrument, "sample": sample, "ref": ref, "rung": float(rung),
                                     "how": how, "native": abs(rung - ref) < 0.5, "named": row is not None})
        built: dict[str, list[dict[str, Any]]] = {}
        for row_name, entries in rows.items():
            entries.sort(key=lambda e: (e["rung"], not e["native"], not e["named"]))
            kept: list[dict[str, Any]] = []
            for entry in entries:
                if native_only and not entry["native"]:
                    notes.append(f"{entry['sample'].name}: skipped ({row_name} row), FMOD plays it at {entry['rung']:g} "
                                 f"rpm but it was recorded at {entry['ref']:g} (--ac-native-rungs)")
                    continue
                clash = next((k for k in kept if abs(k["rung"] - entry["rung"]) < 1), None)
                same = next((k for k in kept if k["sample"].index == entry["sample"].index
                             and abs(k["rung"] - entry["rung"]) < 1), None)
                if clash or same:
                    if not same:
                        notes.append(f"{entry['sample'].name}: dropped from the {row_name} row, {clash['sample'].name} "
                                     f"already holds {entry['rung']:g} rpm")
                    continue
                kept.append(entry)
            built[row_name] = kept
        if len(built["on"]) < 2 and len(built["off"]) < 2:
            return None, notes + ["fewer than two rpm rungs could be placed"]
        if len(built["off"]) < 2:
            built["off"] = built["on"]
            notes.append("no off-throttle set: the on-throttle rungs serve both load rows")
        if len(built["on"]) < 2:
            built["on"] = built["off"]
            notes.append("no on-throttle set: the off-throttle rungs serve both load rows")
        out_rows: list[list[dict[str, Any]]] = []
        for row_name in ("off", "on"):
            out: list[dict[str, Any]] = []
            for entry in built[row_name]:
                ratio = entry["rung"] / entry["ref"]
                emitted = self.emit(entry["sample"], event.path, ratio)
                emitted["provenance"].update({"autopitchReferenceRpm": entry["ref"], "rungRpm": entry["rung"],
                                              "placement": entry["how"]})
                emitted["rpm"] = int(round(entry["rung"]))
                out.append(emitted)
            out_rows.append(out)
        side = ("exterior" if event.path.lower().endswith("_ext") else "interior") if event.path else (
            "exterior" if sum(exterior_rank(e["sample"].name) for e in built["on"] + built["off"]) <= len(built["on"] + built["off"]) else "interior")
        blend = re.sub(r"[^A-Za-z0-9]+", "_", f"{self.car}_{side}").upper()
        return {"name": blend, "eventName": event.path, "rows": out_rows, "side": side,
                "provenance": {"kind": self.options.get("kind") or "sim-official", "sim": "assetto-corsa",
                               "mod": self.car, "sourceFile": self.bank_path.name, "sourceSha256": self.bank.sha256,
                               "event": event.path, "extractor": "helix sim_audio_ac",
                               **({"modUrl": self.options["modUrl"]} if self.options.get("modUrl") else {})},
                "note": (f"{side} engine set from {event.path}: row 0 = {len(out_rows[0])} off-throttle rungs "
                         f"{out_rows[0][0]['rpm']}-{out_rows[0][-1]['rpm']} rpm, row 1 = {len(out_rows[1])} on-throttle "
                         f"rungs {out_rows[1][0]['rpm']}-{out_rows[1][-1]['rpm']} rpm")}, notes

    # -- one-shot slots -----------------------------------------------------------------------------------------
    def slot_candidates(self) -> dict[str, list[tuple[fsb5.FsbSample, str | None, int]]]:
        """slot -> [(sample, event path, rank)], best first (exterior, then natural name order)."""
        found: dict[str, list[tuple[fsb5.FsbSample, str | None, int]]] = {}
        if self.meta is not None and any(e.path for e in self.meta.events):
            for event in self.meta.events:
                leaf, side = _event_leaf(event.path)
                if leaf in ("engine",):
                    continue
                allowed = EVENT_SLOTS.get(leaf)
                if allowed is None or not allowed:
                    continue
                for instrument in event.instruments:
                    if instrument.subsound is None:
                        continue
                    sample = self.names[instrument.subsound]
                    slot = slot_for_name(sample.name)
                    if slot not in allowed:
                        slot = allowed[0] if len(allowed) == 1 else None
                    if not slot:
                        continue
                    rank = 0 if side == "ext" else 2 if side == "int" else exterior_rank(sample.name)
                    found.setdefault(slot, []).append((sample, event.path, rank))
        else:
            for sample in self.bank.samples:
                slot = slot_for_name(sample.name)
                if slot:
                    found.setdefault(slot, []).append((sample, None, exterior_rank(sample.name)))
        for slot in found:
            unique: dict[int, tuple[fsb5.FsbSample, str | None, int]] = {}
            for entry in found[slot]:
                unique.setdefault(entry[0].index, entry)
            found[slot] = sorted(unique.values(), key=lambda e: (e[2], _natural(e[0].name)))
        return found

    def resolve_request(self, req: dict[str, Any]) -> dict[str, Any]:
        """A --map pick: a subsound by name (optionally inside one event), else the slot's default pick."""
        sample_name = req.get("sample")
        event_name = req.get("event")
        pool: list[tuple[fsb5.FsbSample, str | None]] = []
        if self.meta is not None and event_name:
            wanted = event_name.lower()
            for event in self.meta.events:
                path = (event.path or "").lower()
                if path == wanted or path.endswith("/" + wanted.rsplit("/", 1)[-1]):
                    pool += [(self.names[i.subsound], event.path) for i in event.instruments if i.subsound is not None]
            if not pool:
                return {"reason": f"{self.bank_path.name} has no event {event_name!r}"}
        else:
            pool = [(s, None) for s in self.bank.samples]
        if sample_name:
            hit = next(((s, e) for s, e in pool if s.name == sample_name), None) or next(
                ((s, e) for s, e in pool if s.name.lower() == str(sample_name).lower()), None)
            if hit is None:
                return {"reason": f"{self.bank_path.name} has no sample {sample_name!r}"
                                  + (f" in {event_name}" if event_name else "")}
            sample, event = hit
            if event is None and self.meta is not None:
                event = next((e.path for e in self.meta.events for i in e.instruments if i.subsound == sample.index), None)
            return self.emit(sample, event)
        if event_name:
            sample, event = sorted(pool, key=lambda p: (exterior_rank(p[0].name), _natural(p[0].name)))[0]
            return self.emit(sample, event)
        slot = req.get("slot")
        candidates = self.slot_candidates().get(slot or "", [])
        if not candidates:
            return {"reason": f"the Assetto Corsa car's FMOD bank has no {slot} sound"}
        sample, event, _ = candidates[0]
        emitted = self.emit(sample, event)
        emitted["alternatives"] = [c[0].name for c in candidates[1:]][:16]
        return emitted

    def unmapped(self) -> list[dict[str, Any]]:
        rows = []
        if self.meta is None:
            return rows
        for event in self.meta.events:
            leaf, _ = _event_leaf(event.path)
            if leaf == "engine" or EVENT_SLOTS.get(leaf):
                continue
            samples = sorted({self.names[i.subsound].name for i in event.instruments if i.subsound is not None})
            if samples:
                rows.append({"event": event.path, "samples": samples,
                             "why": "no HELIX slot for this sound" if leaf in EVENT_SLOTS else "unknown event"})
        return rows

    def inventory(self) -> dict[str, Any]:
        ladder, ladder_notes = (None, ["--no-ladder"]) if self.options.get("noLadder") else self.ladder()
        picks: dict[str, str] = self.options.get("pick") or {}
        slots: dict[str, Any] = {}
        candidates = self.slot_candidates()
        for slot, entries in candidates.items():
            chosen = entries[0]
            if slot in picks:
                wanted = picks[slot]
                chosen = next((e for e in entries if e[0].name == wanted), None) or next(
                    ((s, None, 0) for s in self.bank.samples if s.name == wanted), None)
                if chosen is None:
                    raise ValueError(f"--map picks sample {wanted!r} for {slot}, which {self.bank_path.name} does not hold")
            emitted = self.emit(chosen[0], chosen[1])
            emitted["alternatives"] = [e[0].name for e in entries if e[0].index != chosen[0].index][:16]
            slots[slot] = emitted
        turbo_event = self.meta and next((e for e in self.meta.events if _event_leaf(e.path)[0] == "turbo"
                                          and e.instruments), None)
        requested = {str(r["id"]): self.resolve_request(r) for r in self.options.get("requests") or []}
        return {
            "requested": requested,
            "sim": "assetto-corsa",
            "traits": {"induction": "turbo" if turbo_event or "turboSpool" in slots or "blowOff" in slots else None,
                       "gearbox": None, "electric": False},
            "source": {"path": str(self.source), "bank": str(self.bank_path), "sha256": self.bank.sha256,
                       "name": self.car, "guids": str(self.guids_path) if self.guids_path else None,
                       "fmodFormat": f"0x{self.meta.fmt:x}" if self.meta else None,
                       "samples": len(self.bank.samples)},
            "ladders": {"engine": ladder, "exhaust": None},
            "ladderNotes": ladder_notes,
            "slots": slots,
            "absentReason": "the Assetto Corsa car's FMOD bank has no {slot} sound",
            "unmapped": self.unmapped(),
            "warnings": self.warnings,
            "cylinders": None,
        }
