#!/usr/bin/env python3
"""tms-run -- load a tms-cc COFF with the dwt loader in MAME and show the result.

  tms-run hello.coff

The image must use the conformance entry/shim (the tms-cc default) for the
status/stdout result block.  This is the same loader/MAME acceptance path as
the gates; it does not use the real unit (see scripts/tests/m7/hardware.sh).
"""
from __future__ import annotations

import argparse
import os
import subprocess
import sys
import tempfile
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
MAME = Path(os.environ.get("MAME", ROOT / "build/mame-src/vt1200"))
LOADER_LUA = ROOT / "vendor/vt1200/dwt/loader/loader.lua"
LOADER_BIN = ROOT / "vendor/vt1200/dwt/loader/build/loader.bin"
CHECK_LUA = ROOT / "scripts/tests/m5/conformance/conformance-check.lua"
ROMS = ROOT / "vendor/vt1200/harness/mame/roms"


def fail(msg: str, code: int = 1):
    print(f"tms-run: error: {msg}", file=sys.stderr)
    raise SystemExit(code)


def main(argv):
    ap = argparse.ArgumentParser(prog="tms-run")
    ap.add_argument("coff")
    ap.add_argument("--at", default=os.environ.get("LOADER_AT", "200"))
    ap.add_argument("--end", default=os.environ.get("LOADER_END", "1000"))
    ap.add_argument("--timeout", default="120")
    ap.add_argument("-v", "--verbose", action="store_true")
    ap.add_argument("--keep", action="store_true")
    args = ap.parse_args(argv)

    coff = Path(args.coff)
    if not coff.is_file():
        fail(f"missing COFF: {coff}")
    for p in (MAME, LOADER_LUA, LOADER_BIN, CHECK_LUA):
        if not p.is_file():
            fail(f"missing required file: {p}")
    work = Path(tempfile.mkdtemp(prefix="tms-run-"))
    try:
        (work / "run/nvram").mkdir(parents=True)
        (work / "run/cfg").mkdir(parents=True)
        result = work / "result.txt"
        env = dict(os.environ)
        env.update({
            "M4_LOADER_LUA": str(LOADER_LUA),
            "VT1200_MONITOR": "VR319",
            "VT1200_SKIP_LEVEL1": "1",
            "LOADER_AT": args.at,
            "LOADER_END": args.end,
            "LOADER_BIN": str(LOADER_BIN),
            "LOADER_COFF": str(coff),
            "LOADER_OUT": str(work / "evidence"),
            "CONF_RESULT": str(result),
        })
        cmd = [str(MAME), "vt1200",
               "-rompath", str(ROMS),
               "-video", "none", "-sound", "none", "-nothrottle",
               "-skip_gameinfo",
               "-nvram_directory", str(work / "run/nvram"),
               "-cfg_directory", str(work / "run/cfg"),
               "-debug", "-debugger", "none",
               "-autoboot_script", str(CHECK_LUA), "-autoboot_delay", "0"]
        if args.verbose:
            print("+", " ".join(cmd), file=sys.stderr)
        try:
            with open(work / "mame.log", "wb") as log:
                r = subprocess.run(cmd, env=env, timeout=float(args.timeout),
                                   stdout=log, stderr=subprocess.STDOUT)
        except subprocess.TimeoutExpired:
            fail(f"MAME timed out after {args.timeout}s")
        if r.returncode != 0:
            tail = (work / "mame.log").read_text(errors="replace")[-2000:]
            fail(f"MAME exited {r.returncode}\n{tail}")
        if not result.is_file():
            tail = (work / "mame.log").read_text(errors="replace")[-2000:]
            fail("no result block (image did not use the conformance entry/shim)"
                 + (f"\n{tail}" if args.verbose else ""))
        vals = {}
        for line in result.read_text(errors="replace").splitlines():
            if "=" in line:
                k, v = line.split("=", 1)
                vals[k] = v
        status = int(vals.get("status", "FFFFFFFF"), 16)
        magic = vals.get("magic", "")
        out = bytes.fromhex(vals.get("out", ""))
        err = bytes.fromhex(vals.get("err", ""))
        print(f"status: {status} (0x{status:08X})")
        print(f"magic: {magic}")
        sys.stdout.flush()
        if out:
            sys.stdout.buffer.write(b"stdout:\n" + out)
            if not out.endswith(b"\n"):
                sys.stdout.buffer.write(b"\n")
        if err:
            sys.stdout.buffer.write(b"stderr:\n" + err)
            if not err.endswith(b"\n"):
                sys.stdout.buffer.write(b"\n")
        sys.stdout.buffer.flush()
        ok = status == 0 and magic == "434F4E46"
        return 0 if ok else 1
    finally:
        if not args.keep:
            import shutil
            shutil.rmtree(work, ignore_errors=True)


if __name__ == "__main__":
    raise SystemExit(main(sys.argv[1:]))
