"""Compile a four-core EVT0 tensor channel between two ranks without launching."""

import os
from pathlib import Path

import torch

import legato
from legato.model.bertha import BerthaDeviceMesh

OUTPUT = Path(os.environ.get("LEGATO_EXAMPLE_OUTPUT", "legato_example_output"))


@legato.compile(backend=lambda ctx: BerthaDeviceMesh(ctx, "channel_mesh", 2, num_cores=4))
def multi_core_transfer(value: legato.types.tensor(legato.types.float("bfloat16"), (1, 64))):
    """Send each core's tensor to the same-numbered core on the peer rank."""
    mesh = legato.get_context().get_mesh()
    source, peer = mesh.get_device(0), mesh.get_device(1)
    # Pair core N on the source rank with core N on the peer rank.
    channel = legato.Channel(mesh.pair_cores_by_id(source, peer))

    with source.get_all_cores():
        legato.write(channel, value)
    with peer.get_all_cores():
        received = legato.read(channel)
        yield received


def main():
    """Compile both ranks and verify their per-core address-slot bindings."""
    # CPU tensors describe the compiled payload; no device or simulator is initialized.
    value = torch.zeros((1, 64), dtype=torch.bfloat16)
    with legato.session(output_type=legato.OutputType.BINARY, output_path=str(OUTPUT), launch=False):
        # Only rank zero consumes the input argument. The receiver gets its value through the channel.
        multi_core_transfer(legato.RankArgs({0: value}))

    # Compilation produces one ELF binary for each logical rank.
    (artifacts,) = multi_core_transfer.mesh_artifacts.values()
    assert {artifact.rank for artifact in artifacts} == {0, 1}
    for artifact in artifacts:
        assert Path(artifact.path).read_bytes().startswith(b"\x7fELF")

    # Each sender core's slot zero points to the same-numbered receiver core's SRAM.
    bindings = tuple(binding for artifact in artifacts for binding in artifact.address_slot_bindings)
    assert {(b.rank, b.core, b.slot, b.peer_rank, b.peer_core, b.size_bytes) for b in bindings} == {
        (0, core, 0, 1, core, 128) for core in range(4)
    }
    assert {artifact.rank: artifact.address_slot_count for artifact in artifacts} == {0: 1, 1: 0}


if __name__ == "__main__":
    main()
