"""Waveform tracing without touching the testbench.

Verilator writes a trace only when the testbench calls `$dumpfile`/`$dumpvars`.
The existing testbenches in this repository do not, and editing eight of them
to add dump calls would mean the tools changed the design they were meant to
observe.

Instead a one-module probe file is generated per run and bound into the
testbench, so the dump calls execute as if the testbench had made them while
the checked-in sources stay untouched:

    module ic_trace_probe;
      initial begin $dumpfile("wave.fst"); $dumpvars(0); end
    endmodule
    bind tb_npu_pe ic_trace_probe ic_trace_probe_i();

`bind` is IEEE 1800 and Verilator 5 supports it. Icarus 11 does not -- it
rejects `bind` as a syntax error -- so for Icarus the probe is instead elaborated
as a second top-level module (`iverilog -s tb -s ic_trace_probe`) that dumps the
testbench by hierarchical name. Same effect, no testbench edit either way.
"""

from __future__ import annotations

from pathlib import Path


PROBE_MODULE = "ic_trace_probe"


def write(directory: Path, tb_module: str, wave_file: str, *, use_bind: bool = True) -> Path:
    """Write the probe.

    `use_bind=True` binds it into the testbench (Verilator). `use_bind=False`
    leaves it a standalone root that the caller must elaborate alongside the
    testbench, dumping the testbench by name (Icarus).
    """
    path = directory / "ic_trace_probe.sv"
    scope = "" if use_bind else f", {tb_module}"
    body = (
        "// Generated by ic sim. Not part of the design.\n"
        f"module {PROBE_MODULE};\n"
        "  initial begin\n"
        f'    $dumpfile("{wave_file}");\n'
        f"    $dumpvars(0{scope});\n"
        "  end\n"
        "endmodule\n"
    )
    if use_bind:
        body += f"bind {tb_module} {PROBE_MODULE} {PROBE_MODULE}_i();\n"
    path.write_text(body)
    return path
