"""Read-only X1 Ride Armor movie capture using the installed matching BizHawk core.
Private movie/configuration and output paths follow the existing Sponge X2 capture workflow.
"""
import argparse
import hashlib
import json
import shutil
import runpy
import subprocess
import zipfile
from pathlib import Path



_BACKGROUND = runpy.run_path(str(Path(__file__).resolve().parents[1] / "bizhawk" / "background_process.py"))
BackgroundProcess = _BACKGROUND["BackgroundProcess"]
run_background = _BACKGROUND["run_background"]

def digest(path):
    return hashlib.sha256(path.read_bytes()).hexdigest().upper()


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    for name in ("movie", "rom", "bizhawk", "output"):
        parser.add_argument("--" + name, required=True, type=Path)
    parser.add_argument("--timeout", type=int, default=240)
    args = parser.parse_args()
    movie, rom, emulator, output = (p.resolve() for p in (args.movie, args.rom, args.bizhawk, args.output))
    with zipfile.ZipFile(movie) as archive:
        header = dict(line.split(" ", 1) for line in archive.read("Header.txt").decode("utf-8-sig").splitlines() if " " in line)
        count = sum(line.startswith("|") for line in archive.read("Input Log.txt").decode("utf-8-sig").splitlines())
    payload = rom.read_bytes()
    if len(payload) % 32768 == 512:
        payload = payload[512:]
    sha1 = hashlib.sha1(payload).hexdigest().upper()
    if sha1 not in ("449A00631208FBCC8D58209E66D0D488674B7FB1", "C65216760BA99178100A10D98457CF11496C2097") or header.get("SHA1") != sha1:
        raise ValueError("Use the exact X1 USA/USA Rev 1 ROM identified by the movie.")
    if header.get("Platform") != "SNES" or header.get("Core") != "BSNESv115+" or header.get("emuVersion") != "Version 2.11":
        raise ValueError("The native state adapter requires BizHawk 2.11 / BSNESv115+.")
    if output.exists() and any(output.iterdir()):
        raise ValueError("Choose an absent or empty output directory.")
    output.mkdir(parents=True, exist_ok=True)
    user_config = emulator.parent / "config.ini"
    original_config_hash, original_movie_hash = digest(user_config), digest(movie)
    config = json.loads(user_config.read_text(encoding="utf-8-sig"))
    for entry in config["PathEntries"]["Paths"]:
        if entry["Type"] == "Firmware":
            path = Path(entry["Path"])
            entry["Path"] = str(path if path.is_absolute() else (emulator.parent / path).resolve())
        else:
            path = output / "paths" / entry["System"] / entry["Type"].replace("/", "_")
            path.mkdir(parents=True, exist_ok=True)
            entry["Path"] = str(path)
    config.update(SoundEnabled=False, SoundThrottle=False, ClockThrottle=False, VSyncThrottle=False,
                  Unthrottled=True, RunInBackground=True, AcceptBackgroundInput=False,
                  SingleInstanceMode=False, StartPaused=True, SkipLagFrame=False,
                  FrameSkip=0, AutoMinimizeSkipping=False)
    for key, value in config.items():
        if key.startswith("Recent") and isinstance(value, dict):
            value["AutoLoad"] = False
    config["PreferredCores"]["SNES"] = header["Core"]
    private_config = output / "config.json"
    private_config.write_text(json.dumps(config), encoding="utf-8")
    private_movie = output / "source.bk2"
    shutil.copyfile(movie, private_movie)
    template = Path(__file__).resolve().parent.parent / "bizhawk/MMX1_RideArmor_Capture.lua"
    script = template.read_text().replace("@OUTPUT@", output.as_posix()).replace("@FRAMES@", str(count))
    if "]]" in output.as_posix():
        raise ValueError("Output path contains Lua delimiters.")
    (output / "capture.lua").write_text(script, encoding="utf-8")
    command = [str(emulator), "--gdi", "--chromeless", "--config=" + str(private_config),
               "--movie=" + str(private_movie), "--lua=" + str(output / "capture.lua"), str(rom)]
    startup = subprocess.STARTUPINFO()
    startup.dwFlags |= subprocess.STARTF_USESHOWWINDOW
    startup.wShowWindow = 0
    with (output / "process.log").open("w") as log:
        run_background(command, cwd=emulator.parent, stdout=log, stderr=log, startupinfo=startup, timeout=args.timeout, check=True)
    if original_config_hash != digest(user_config) or original_movie_hash != digest(movie):
        raise RuntimeError("The source movie or user configuration changed.")
    if (output / "error.txt").exists():
        raise RuntimeError((output / "error.txt").read_text())
    if not (output / "done.txt").exists():
        raise RuntimeError("BizHawk did not complete the capture.")
    metadata = dict(movie=movie.name, movie_sha256=original_movie_hash, rom_sha1=sha1,
                    core=header["Core"], frames=count, trace_sha256=digest(output / "frames.csv"),
                    scene_sha256=digest(output / "scene.bin"), scene_bytes_per_frame=8192,
                    scope="Original input playback and read-only low WRAM; no memory writes or input replacement.")
    (output / "metadata.json").write_text(json.dumps(metadata, indent=2) + "\n")
    print(json.dumps(metadata))


if __name__ == "__main__":
    main()
