"""The sim-audio importer against generated fixtures: FSB5, FMOD Studio 1.x/2.x metadata, AC and BeamNG inventories.

Run from this folder: python3 -m unittest test_sim_audio
"""
from __future__ import annotations

import json
import os
import shutil
import struct
import sys
import tempfile
import unittest
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
os.environ["HELIX_VGMSTREAM"] = "/nonexistent/vgmstream-cli"  # exercise the built-in PCM decoder deterministically

import fmod_studio  # noqa: E402
import fsb5  # noqa: E402
import sim_audio  # noqa: E402
import sim_audio_fixtures as fx  # noqa: E402
from sim_audio_ac import AcInventory  # noqa: E402
from sim_audio_beamng import BeamngInventory, mix_from_sound_config, stock_event_to_fmod  # noqa: E402

HAS_FFMPEG = sim_audio.locate_ffmpeg() is not None


class Scratch(unittest.TestCase):
    def setUp(self) -> None:
        self.dir = Path(tempfile.mkdtemp(prefix="helix-sim-audio-"))

    def tearDown(self) -> None:
        shutil.rmtree(self.dir, ignore_errors=True)


class Fsb5(Scratch):
    def test_names_rates_and_pcm_decode(self) -> None:
        pcm = fx.tone(200, 0.1)
        path = self.dir / "x.fsb"
        path.write_bytes(fx.build_fsb5([("first", pcm, 44100, 1), ("second", fx.tone(300, 0.1, channels=2), 48000, 2)]))
        bank = fsb5.read_bank(path)
        self.assertEqual([s.name for s in bank.samples], ["first", "second"])
        self.assertEqual((bank.samples[1].rate, bank.samples[1].channels), (48000, 2))
        out = self.dir / "first.wav"
        decoder = fsb5.decode_sample(bank, bank.samples[0], out)
        self.assertIn("pcm16", decoder)
        header = sim_audio.read_wav_header(out.read_bytes())
        self.assertEqual((header["rate"], header["channels"], header["bits"]), (44100, 1, 16))
        start, end = header["data"]
        self.assertEqual(out.read_bytes()[start:end], pcm)  # byte for byte

    def test_refuses_a_codec_it_cannot_decode_without_vgmstream(self) -> None:
        sample = fsb5.FsbSample(0, 0, 0, "v", "fadpcm", 44100, 1, 10, 0, 0)
        bank = fsb5.FsbBank(self.dir / "none.bank", "0" * 64, [sample])
        with self.assertRaisesRegex(fsb5.FsbError, "vgmstream"):
            fsb5.decode_sample(bank, sample, self.dir / "v.wav")


class WavHygiene(Scratch):
    def test_repairs_the_mmbng_993_header_without_touching_samples(self) -> None:
        pcm = fx.tone(100, 0.1, channels=2)
        bad = self.dir / "bad.wav"
        bad.write_bytes(fx.wav(pcm, channels=2, malformed=True))
        problems = sim_audio.read_wav_header(bad.read_bytes())["problems"]
        self.assertTrue(any("blockAlign" in p for p in problems))
        out = self.dir / "good.wav"
        transforms = sim_audio.normalize_wav(bad, out)
        self.assertEqual(transforms[0]["kind"], "wav-header-repair")
        fixed = sim_audio.read_wav_header(out.read_bytes())
        self.assertEqual(fixed["problems"], [])
        self.assertEqual((fixed["blockAlign"], fixed["byteRate"]), (4, 44100 * 4))
        start, end = fixed["data"]
        self.assertEqual(out.read_bytes()[start:end], pcm)

    def test_copies_a_clean_wav_verbatim(self) -> None:
        clean = self.dir / "c.wav"
        clean.write_bytes(fx.wav(fx.tone(100, 0.1)))
        out = self.dir / "o.wav"
        self.assertEqual(sim_audio.normalize_wav(clean, out), [])
        self.assertEqual(out.read_bytes(), clean.read_bytes())


class MixFields(unittest.TestCase):
    def test_reads_the_runtime_mix_from_sound_config_the_way_lower_beamng_does(self) -> None:
        mix = mix_from_sound_config({"mainGain": -3, "intakeMuffling": 0.4, "minLoadMix": 0.2, "maxLoadMix": float("nan")},
                                    {"mainGain": 1.5, "muffling": 0.9})
        self.assertEqual({k: v["value"] for k, v in mix.items()},
                         {"engineGainDb": -3.0, "exhaustGainDb": 1.5, "minLoadMix": 0.2, "muffling": 0.4})
        self.assertEqual(mix["exhaustGainDb"]["from"], "soundConfigExhaust.mainGain")
        self.assertEqual(mix_from_sound_config({"mainGain": True}, {}), {})


class NameRules(unittest.TestCase):
    def test_kunos_and_beamng_names(self) -> None:
        table = {"horn": "horn", "door_open": "doorOpen", "door_close": "doorClose", "gearupEXT": "shiftUp",
                 "geardnEXT": "shiftDown", "blowoff_2": "blowOff", "turbo": "turboSpool", "limiter": "revLimiter",
                 "backfireEXT_3": "backfire", "Ferruccio_trans": "transmissionWhine", "skid_ext_mono": None,
                 "tyre_rolling": "tyreRollSlow", "brakes": None, "handbrake_ratchet": "handbrake",
                 "starter_v8": "startup", "shutoff": "shutdown", "missgear": None, "wind": None, "max": None}
        for name, slot in table.items():
            self.assertEqual(sim_audio.slot_for_name(name), slot, name)

    def test_exterior_beats_interior(self) -> None:
        self.assertLess(sim_audio.exterior_rank("skid_ext_mono"), sim_audio.exterior_rank("Skid"))
        self.assertLess(sim_audio.exterior_rank("gearupEXT"), sim_audio.exterior_rank("gearup_int"))

    def test_slot_list_matches_the_runtime_vocabulary(self) -> None:
        self.assertEqual(len(sim_audio.SLOTS), 26)
        self.assertEqual(len(set(sim_audio.SLOTS)), 26)
        self.assertFalse(set(sim_audio.SLOTS) & set(sim_audio.RETIRED_SLOTS))


class AcBank(Scratch):
    def test_metadata_events_autopitch_and_plateaus(self) -> None:
        facts = fx.build_ac_bank(self.dir)
        guids = fmod_studio.read_guids_txt(self.dir / "content" / "sfx" / "GUIDs.txt", "test_car")
        meta = fmod_studio.read_metadata(facts["bank"], guids)
        bank = fsb5.read_bank(facts["bank"])
        names = {s.index: s.name for s in bank.samples}
        engine = meta.event("event:/cars/test_car/engine_ext")
        self.assertIsNotNone(engine)
        mid = next(i for i in engine.instruments if names[i.subsound] == "TST_ex_on_mid")
        self.assertEqual(mid.autopitch, 4600.0)
        self.assertEqual(mid.plateau(), (5000.0, 5600.0))
        self.assertEqual(mid.audible(), (4500.0, 5800.0))
        door = meta.event("event:/cars/test_car/door")
        self.assertEqual(sorted(names[i.subsound] for i in door.instruments), ["door_close", "door_open"])

    def test_refuses_an_unmeasured_metadata_format(self) -> None:
        path = self.dir / "x.bank"
        path.write_bytes(fx.fev(0x77, []))
        with self.assertRaisesRegex(fmod_studio.FmodMetadataError, "0x77"):
            fmod_studio.read_metadata(path)

    @unittest.skipUnless(HAS_FFMPEG, "ffmpeg is needed to re-pitch an auto-pitched rung")
    def test_inventory_ladder_rows_and_slots(self) -> None:
        facts = fx.build_ac_bank(self.dir)
        inv = AcInventory(Path(facts["car_dir"]), self.dir / "stage", {}).inventory()
        ladder = inv["ladders"]["engine"]
        self.assertEqual(ladder["eventName"], "event:/cars/test_car/engine_ext")
        off, on = ladder["rows"]
        self.assertEqual([r["rpm"] for r in off], [2300, 4600])
        self.assertEqual([r["rpm"] for r in on], [1150, 2300, 5300])
        mid = on[-1]["provenance"]
        self.assertEqual(mid["autopitchReferenceRpm"], 4600.0)
        self.assertEqual(mid["transforms"][-1]["kind"], "fmod-autopitch-varispeed")
        self.assertAlmostEqual(mid["transforms"][-1]["ratio"], 5300 / 4600, places=4)
        self.assertNotIn("transforms", on[1]["provenance"])  # native rung: bytes as recorded
        for slot, sample in (("horn", "horn"), ("doorOpen", "door_open"), ("doorClose", "door_close")):
            self.assertEqual(inv["slots"][slot]["provenance"]["sample"], sample)
            self.assertEqual(inv["slots"][slot]["provenance"]["kind"], "sim-official")
            self.assertEqual(inv["slots"][slot]["provenance"]["sourceSha256"], fsb5.read_bank(facts["bank"]).sha256)


class BeamngStock(Scratch):
    def test_strings_bank_round_trip(self) -> None:
        paths = {"event:/A/b": fx.guid(), "event:/Engine/Starter/x": fx.guid()}
        path = self.dir / "s.strings.bank"
        path.write_bytes(fx.build_strings_bank(paths))
        self.assertEqual(fmod_studio.read_strings_bank(path), paths)

    def test_event_names(self) -> None:
        self.assertEqual(stock_event_to_fmod("event:>Engine>Starter>v8flat_1986_eng"), "event:/Engine/Starter/v8flat_1986_eng")

    def test_mod_inventory_with_the_base_game(self) -> None:
        fx.build_beamng_root(self.dir / "bng")
        fx.build_beamng_mod(self.dir / "mod")
        inv = BeamngInventory(self.dir / "mod", self.dir / "stage",
                              {"beamngRoot": str(self.dir / "bng"), "cacheDir": str(self.dir / "cache")}).inventory()
        ladder = inv["ladders"]["engine"]
        self.assertEqual(ladder["name"], "TST")
        rung = ladder["rows"][0][0]
        self.assertEqual(rung["rpm"], 1000)
        self.assertEqual(rung["provenance"]["kind"], "sim-mod")
        self.assertEqual(rung["provenance"]["sourceFile"], "art/sound/engine/TST/1000.wav")
        self.assertEqual(rung["provenance"]["transforms"][0]["kind"], "wav-header-repair")
        header = sim_audio.read_wav_header(Path(rung["wav"]).read_bytes())
        self.assertEqual(header["problems"], [])
        self.assertIsNone(inv["ladders"]["exhaust"])
        # A stock event named by the engine part, resolved through the strings + metadata + assets banks.
        start = inv["slots"]["startup"]["provenance"]
        self.assertEqual((start["kind"], start["event"], start["sample"]),
                         ("sim-official", "event:/Engine/Starter/test_eng", "starter_start_test"))
        # The horn comes from the common soundscape part the vehicle's slot selects; the loop take wins.
        self.assertEqual(inv["slots"]["horn"]["provenance"]["sample"], "horn_loop_test")
        # A recording the mod ships, matched by its file name.
        self.assertEqual(inv["slots"]["doorOpen"]["provenance"]["sourceFile"], "vehicles/testcar/sounds/door_open.wav")
        self.assertEqual(inv["traits"], {"induction": None, "gearbox": None, "electric": False})

    def test_map_picks_a_shipped_blend_and_finds_extensionless_recordings(self) -> None:
        fx.build_beamng_mod(self.dir / "mod")
        inv = BeamngInventory(self.dir / "mod", self.dir / "stage", {"engineBlend": "ALT"})
        result = inv.inventory()
        self.assertEqual(result["ladders"]["engine"]["name"], "ALT")
        self.assertEqual([r["rpm"] for r in result["ladders"]["engine"]["rows"][0]], [2000, 5000])
        self.assertTrue(any("chosen by --map" in n for n in result["ladderNotes"]))
        self.assertEqual(inv.find_named_recording("door_open").name, "door_open.wav")
        self.assertEqual(inv.find_named_recording("vehicles/elsewhere/DOOR_OPEN.ogg").name, "door_open.wav")
        self.assertIsNone(inv.find_named_recording("nothing_like_it"))
        routed = BeamngInventory(self.dir / "mod", self.dir / "stage2",
                                 {"requests": [{"id": "doorOpen", "slot": "doorOpen"}, {"id": "horn", "slot": "horn"}]}).inventory()
        self.assertEqual(routed["requested"]["doorOpen"]["provenance"]["sourceFile"], "vehicles/testcar/sounds/door_open.wav")
        self.assertIn("reason", routed["requested"]["horn"])

    @unittest.skipUnless(HAS_FFMPEG, "ffmpeg re-pitches the motor take")
    def test_an_ev_motor_event_becomes_a_ladder_the_way_its_pitch_automation_plays_it(self) -> None:
        from sim_audio_beamng import automation_ratio
        fx.build_beamng_root(self.dir / "bng")
        fx.build_beamng_mod(self.dir / "mod")
        # The mod's engine names a stock blend that has no rung samples, only the motor event.
        jbeam = self.dir / "mod" / "vehicles" / "testcar" / "testcar.jbeam"
        body = json.loads(jbeam.read_text())
        body["testcar_engine"]["soundConfig"]["sampleName"] = "TestMotor"
        body["testcar_engine"]["mainEngine"]["maxRPM"] = 9000
        jbeam.write_text(json.dumps(body))
        inv = BeamngInventory(self.dir / "mod", self.dir / "stage",
                              {"beamngRoot": str(self.dir / "bng"), "cacheDir": str(self.dir / "cache")}).inventory()
        ladder = inv["ladders"]["engine"]
        self.assertTrue(ladder["motor"])
        self.assertEqual(ladder["eventName"], "event:/Engine/Bands/Real/test_motor")
        self.assertEqual([r["rpm"] for r in ladder["rows"][0]], [1000, 2000, 4000, 6000, 8000, 9000])
        rung = ladder["rows"][0][0]["provenance"]
        self.assertEqual((rung["sample"], rung["transforms"][-1]["kind"]), ("motor_whine_test", "fmod-pitch-automation-varispeed"))
        self.assertAlmostEqual(rung["transforms"][-1]["ratio"], automation_ratio([(0, -1), (20000, 1)], 1000), places=4)
        self.assertAlmostEqual(automation_ratio([(0, -1), (20000, 1)], 10000), 1.0)
        self.assertEqual(ladder["provenance"]["pitchAutomation"]["parameter"], "RPM")

    def test_a_zipped_mod_wrapped_in_folders_with_backslash_paths(self) -> None:
        import zipfile
        fx.build_beamng_mod(self.dir / "mod")
        archive = self.dir / "wrapped.zip"
        with zipfile.ZipFile(archive, "w") as z:
            for path in (self.dir / "mod").rglob("*"):
                if path.is_file():
                    z.write(path, "unpacked\\66487-test\\" + path.relative_to(self.dir / "mod").as_posix().replace("/", "\\"))
        inv = BeamngInventory(archive, self.dir / "stage", {}).inventory()
        self.assertEqual(inv["ladders"]["engine"]["name"], "TST")
        self.assertEqual(inv["source"]["vehicle"], "testcar")

    def test_a_stock_event_without_the_install_names_the_event_needed(self) -> None:
        fx.build_beamng_mod(self.dir / "mod")
        inv = BeamngInventory(self.dir / "mod", self.dir / "stage", {}).inventory()
        self.assertNotIn("startup", inv["slots"])
        self.assertIn("event:/Engine/Starter/test_eng", inv["reasons"]["startup"])
        self.assertIn("--beamng-root", inv["reasons"]["startup"])


if __name__ == "__main__":
    unittest.main()
