"""Frontend fill patterns; standalone full/full_like lack EVT0 backend lowering."""

import os
from pathlib import Path

import torch

import legato
import legato.model.bertha as bertha
from legato.language import arith

# Store compiler artifacts and optional simulator logs in a configurable directory.
OUTPUT = Path(os.environ.get("LEGATO_EXAMPLE_OUTPUT", "legato_example_output"))


@legato.compile(backend=lambda ctx: bertha.Bertha(ctx, "bertha"))
def fill_tensor(
    out: legato.get_model().tensor_type(legato.types.float("bfloat16"), [16, 64], "shared_dram"),
):
    """A fixed-shape fill takes no dynamic-shape operands."""
    with legato.get_context().get_device().get_core(0):
        fill = arith.cast(-1.0, legato.types.float("bfloat16"))
        result = legato.tensor.full(
            legato.get_model().tensor_type(legato.types.float("bfloat16"), [16, 64], "row_major"), fill, None
        )
        legato.tensor.memcpy(out, result)


@legato.compile(backend=lambda ctx: bertha.Bertha(ctx, "bertha"))
def fill_like_loaded(
    x: legato.get_model().tensor_type(legato.types.float("bfloat16"), [16, 64], "shared_dram"),
    out: legato.get_model().tensor_type(legato.types.float("bfloat16"), [16, 64], "shared_dram"),
):
    """Describe a filled result with the loaded tensor's type and shape."""
    device = legato.get_context().get_device()
    with device.get_top():
        legato.tensor.request_load(x, device.get_core(0), "sram")
    with device.get_core(0):
        loaded = legato.tensor.receive(x, 0, "sram")
        fill = arith.cast(-1.0, legato.types.float("bfloat16"))
        legato.tensor.memcpy(out, legato.tensor.full_like(loaded, fill))


def verify_fill_tensor():
    """Emit the fixed-shape fill operation and its minus-one value."""
    cpu = torch.empty(16, 64, dtype=torch.bfloat16)
    # Emit frontend MLIR without initializing a device or launching.
    with legato.session(output_type=legato.OutputType.MLIR, output_path=str(OUTPUT), launch=False):
        fill_tensor(cpu)


def verify_fill_like_loaded():
    """Emit the fill-like operation and its minus-one value."""
    cpu = torch.empty(16, 64, dtype=torch.bfloat16)
    # Emit frontend MLIR without initializing a device or launching.
    with legato.session(output_type=legato.OutputType.MLIR, output_path=str(OUTPUT), launch=False):
        fill_like_loaded(cpu, cpu)


def main():
    """Emit frontend MLIR only, without advertising unsupported binary execution."""
    verify_fill_tensor()
    verify_fill_like_loaded()


if __name__ == "__main__":
    main()
