#!/usr/bin/env python3
"""Generate a NOP-sled golden trace in the retroDE_ps2 common envelope.

Produces one EE IFETCH record per fetch, starting at --reset-vector (default
0xBFC00000), advancing PC += 4 each step. Each instruction word is 0x00000000
(MIPS NOP: sll $0, $0, 0).

Format: see docs/decisions/0000-trace-format.md.
Spec:   see sim/golden/trace_compare_spec.md.
"""
import argparse
import sys


def main() -> int:
    ap = argparse.ArgumentParser(description="NOP-sled golden trace generator")
    ap.add_argument("--count", type=int, default=32,
                    help="number of IFETCH records to emit (default: 32)")
    ap.add_argument("--reset-vector", type=lambda s: int(s, 0),
                    default=0xBFC00000,
                    help="starting PC (default: 0xBFC00000)")
    ap.add_argument("-o", "--output", default="-",
                    help="output file, '-' for stdout (default: -)")
    args = ap.parse_args()

    if args.count <= 0:
        print("error: --count must be positive", file=sys.stderr)
        return 2

    if args.output == "-":
        out = sys.stdout
        close = False
    else:
        try:
            out = open(args.output, "w")
        except OSError as e:
            print(f"error: cannot open {args.output}: {e}", file=sys.stderr)
            return 2
        close = True

    try:
        out.write("# retroDE_ps2 golden trace, schema v1, "
                  "source=generated, scenario=nop_sled\n")
        out.write("# columns: cycle subsystem event arg0 arg1 arg2 arg3 flags\n")
        for i in range(args.count):
            pc = (args.reset_vector + i * 4) & 0xFFFFFFFFFFFFFFFF
            out.write(
                f"{i} EE IFETCH "
                f"0x{pc:016x} 0x{0:016x} 0x{0:016x} 0x{0:016x} -\n"
            )
    finally:
        if close:
            out.close()

    return 0


if __name__ == "__main__":
    sys.exit(main())
