"""Compile-time unrolling, folding and branching; inspect frontend MLIR."""

import os
from pathlib import Path

import legato
import legato.language.types as lt
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 static_for_each(
    to_add: lt.integer("int64"),
    num_cores: lt.constexpr(lt.integer("int64")),
):
    """Unroll per-core scalar expressions in frontend IR."""
    device = legato.get_context().get_device()

    def add_one(core_id):
        return arith.cast(core_id, lt.integer("int64")) + to_add

    with device.get_all_cores():
        core_range = legato.range(
            arith.cast(0, lt.index()),
            arith.cast(num_cores, lt.index()),
        )
        legato.static.for_each(core_range, add_one)


@legato.compile(backend=lambda ctx: bertha.Bertha(ctx, "bertha"))
def build_static_list(
    to_add: lt.integer("int64"),
    core_ids: lt.constexpr(lt.list(lt.integer("int64"))),
):
    """Fold and cast a constexpr list before emitting per-core expressions."""
    empty = legato.static.empty_list(lt.integer("int32"))
    casted_core_ids = legato.static.fold(
        core_ids,
        lambda core_id, acc: legato.static.append(acc, arith.cast(core_id, lt.integer("int32"))),
        empty,
    )

    def add_one(x: lt.integer("int32")):
        return x + arith.cast(to_add, lt.integer("int32"))

    device = legato.get_context().get_device()
    with device.get_all_cores():
        legato.static.for_each(casted_core_ids, add_one)


@legato.compile(backend=lambda ctx: bertha.Bertha(ctx, "bertha"))
def static_branch():
    """Select a branch at compile time; this entry point is not launched."""
    device = legato.get_context().get_device()
    with device.get_all_cores():
        x = 0

        def on_true():
            return x + 1

        def on_false():
            return x + 2

        result = legato.static.if_else(True, on_true, on_false)
        yield result


def verify_static_for_each():
    """Emit the unrolled 32-core expressions."""
    # Emit frontend MLIR without initializing a device or launching.
    with legato.session(output_type=legato.OutputType.MLIR, output_path=str(OUTPUT), launch=False):
        static_for_each(5, 32)


def verify_build_static_list():
    """Emit the three constexpr list elements."""
    # Emit frontend MLIR without initializing a device or launching.
    with legato.session(output_type=legato.OutputType.MLIR, output_path=str(OUTPUT), launch=False):
        build_static_list(5, [0, 1, 2])


def verify_static_branch():
    """Emit the selected branch's value, one."""
    # Emit frontend MLIR without initializing a device or launching.
    with legato.session(output_type=legato.OutputType.MLIR, output_path=str(OUTPUT), launch=False):
        static_branch()


def main():
    """Compile three illustrative entry points without launching them."""
    verify_static_for_each()
    verify_build_static_list()
    verify_static_branch()


if __name__ == "__main__":
    main()
