#!/usr/bin/env python3
"""Extract one simulator source's sound set into a staging directory and print its inventory as JSON.

Used by ``helix vehicle audio-import`` (src/vehicle/audioImport.ts), which runs this once per source, then merges the
sources a ``--map`` names, picks one recording per HELIX slot and writes the package ``audio`` block.

    sim_audio_import.py --source <mod dir | mod .zip | AC car dir | .bank> --staging <dir>
                        [--sim beamng|ac|auto] [--options <json file>]

Options JSON (all optional): vehicle, config, beamngRoot, vgmstream, modName, modUrl, kind, prefer
(exterior|interior), nativeOnly, noLadder, cylinders, rpm {sample: rpm}, pick {slot: sample|field|value}.
Exit 0 with the inventory on stdout; exit 2 with a one-line reason on stderr.
"""
from __future__ import annotations

import argparse
import json
import os
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))


def detect_sim(source: Path) -> str:
    if source.is_file():
        suffix = source.suffix.lower()
        if suffix in (".bank", ".fsb"):
            return "ac"
        if suffix == ".zip":
            return "beamng"
        raise ValueError(f"{source.name}: expected a mod folder, a .zip, an Assetto Corsa car folder or a .bank")
    if (source / "vehicles").is_dir():
        return "beamng"
    if (source / "sfx").is_dir() or any(source.glob("*.bank")):
        return "ac"
    if (source / "ui").is_dir() and (source / "data.acd").exists() is False and not (source / "sfx").exists():
        raise ValueError(f"{source} looks like an Assetto Corsa car without sfx/ (a DLC car this install does not own)")
    raise ValueError(f"{source}: cannot tell the simulator (no vehicles/ for BeamNG, no sfx/*.bank for Assetto Corsa); "
                     "pass --sim")


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--source", required=True)
    parser.add_argument("--staging", required=True)
    parser.add_argument("--sim", default="auto", choices=["auto", "beamng", "ac", "beamng-base", "recording"])
    parser.add_argument("--options")
    args = parser.parse_args()
    options = json.loads(Path(args.options).read_text()) if args.options else {}
    if not options.get("beamngRoot") and os.environ.get("HELIX_BEAMNG_ROOT"):
        options["beamngRoot"] = os.environ["HELIX_BEAMNG_ROOT"]
    source = Path(args.source).expanduser().resolve()
    staging = Path(args.staging).resolve()
    staging.mkdir(parents=True, exist_ok=True)
    try:
        if not source.exists():
            raise ValueError(f"{source} does not exist")
        sim = detect_sim(source) if args.sim == "auto" else args.sim
        if sim == "beamng-base":
            # The BeamNG base game's own defaults for the requested slots (source = the BeamNG.drive install).
            import beamng_stock_events
            from sim_audio_beamng import base_game_slots, stock_event_to_fmod
            stock = beamng_stock_events.StockEvents(source, staging / "bng-stock", options.get("vgmstream"),
                                                    Path(options["cacheDir"]) if options.get("cacheDir") else None)
            slots, reasons = base_game_slots(stock, list(options.get("slots") or []), options.get("traits") or {},
                                             set(options.get("taken") or []), options.get("events") or {})
            from sim_audio_beamng import extract_exact
            requested = {}
            for req in options.get("requests") or []:
                if req.get("event"):
                    requested[str(req["id"])] = extract_exact(stock, stock_event_to_fmod(str(req["event"])), req.get("slot"), req.get("sample"))
                else:
                    filled, failed = base_game_slots(stock, [req.get("slot")], options.get("traits") or {}, set())
                    requested[str(req["id"])] = filled.get(req.get("slot")) or {"reason": failed.get(req.get("slot"), "no base-game default for this slot")}
            ladders: dict = {"engine": None, "exhaust": None}
            ladder_notes: list = []
            if options.get("engineEvent"):
                from sim_audio_beamng import event_ladder, motor_rungs
                event = stock_event_to_fmod(str(options["engineEvent"]))
                guid = stock.lower.get(event.lower())
                curve = stock.events[guid].pitch_curve if guid in stock.events else []
                rpms = [float(r) for r in options.get("ladderRpms") or motor_rungs(float(options.get("maxRpm") or max((x for x, _ in curve), default=8000.0)))]
                name = event.rsplit("/", 1)[-1].upper().replace("-", "_")
                engine, reason = event_ladder(stock, event, rpms, staging, name)
                if engine:
                    ladders = {"engine": engine, "exhaust": event_ladder(stock, event, rpms, staging, name + "_L2", layer=1)[0]}
                else:
                    ladder_notes.append(f"engine: {reason}")
            inventory = {"requested": requested, "sim": "beamng", "source": {"path": str(source), "name": "BeamNG.drive base game"},
                         "ladders": ladders, "ladderNotes": ladder_notes, "slots": slots,
                         "reasons": reasons, "unmapped": [], "warnings": [], "cylinders": None,
                         "traits": options.get("traits") or {}, "stockEvents": stock.report()}
            json.dump(inventory, sys.stdout, default=str)
            return 0
        if sim == "recording":
            # Real recordings of the car (field recordings, a manufacturer clip): each request names a file.
            from sim_audio import normalize_wav, sha256_file, staged_name
            import shutil
            requested = {}
            for req in options.get("requests") or []:
                path = Path(str(req.get("file") or req.get("sample") or ""))
                if not path.is_absolute():
                    path = (source if source.is_dir() else source.parent) / path
                if not path.is_file():
                    requested[str(req["id"])] = {"reason": f"no recording at {path}"}
                    continue
                out = staging / f"rec-{sha256_file(path)[:16]}.wav"
                transforms = normalize_wav(path, out)
                final = staging / staged_name(path.stem, sha256_file(out))
                if not final.exists():
                    shutil.copyfile(out, final)
                requested[str(req["id"])] = {"wav": str(final), "provenance": {
                    "kind": "recording", "mod": options.get("modName") or path.stem, "sourceFile": path.name,
                    "sourceSha256": sha256_file(path), "extractor": "helix sim_audio_import (recording)",
                    **({"modUrl": options["modUrl"]} if options.get("modUrl") else {}),
                    **({"transforms": transforms} if transforms else {})}}
            json.dump({"requested": requested, "sim": "recording", "source": {"path": str(source), "name": options.get("modName") or source.name},
                       "ladders": {"engine": None, "exhaust": None}, "slots": {}, "reasons": {}, "traits": {}}, sys.stdout, default=str)
            return 0
        if sim == "ac":
            from sim_audio_ac import AcInventory
            inventory = AcInventory(source, staging, options).inventory()
        else:
            from sim_audio_beamng import BeamngInventory
            inventory = BeamngInventory(source, staging, options).inventory()
    except Exception as error:  # noqa: BLE001 - one line for the CLI
        print(f"{type(error).__name__}: {error}" if not isinstance(error, ValueError) else str(error), file=sys.stderr)
        return 2
    json.dump(inventory, sys.stdout, default=str)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
