import numpy as _np
from mpi4py import MPI as _MPI

from jax import core
from jax.ffi import ffi_lowering
from jax.core import ShapedArray

from mpi4jax._src.utils import (
    HashableMPIType,
    default_primitive_impl,
    to_dtype_handle,
    to_mpi_handle,
    unpack_hashable,
    wrap_as_hashable,
    ordered_effect,
    NOTSET,
    raise_if_token_is_set,
)
from mpi4jax._src.jax_compat import (
    register_lowering,
    get_token_effect,
    set_token_effect,
    Primitive,
)
from mpi4jax._src.decorators import (
    translation_rule_cpu,
    translation_rule_cuda,
    translation_rule_xpu,
)
from mpi4jax._src.validation import enforce_types
from mpi4jax._src.utils import get_default_comm


# The Jax primitive
mpi_scatter_p = Primitive("scatter_mpi")  # Create the primitive
mpi_scatter_impl = default_primitive_impl(mpi_scatter_p)


# This function applies the primitive to an AST
@enforce_types(
    root=(_np.integer),
    comm=(type(None), _MPI.Intracomm, HashableMPIType),
)
def scatter(
    x,
    root,
    *,
    comm=None,
    token=NOTSET,
):
    """Perform a scatter operation.

    .. warning::

        Unlike mpi4py's scatter, this returns a *new* array with the received data.

    .. warning::

        The expected shape of the first input varies between ranks. On the root process,
        it is ``(nproc, *input_shape)``. On all other processes, it is ``input_shape``.

    Arguments:
        x: Array or scalar input with the correct shape and dtype. On the root process,
           this contains the data to send, and its first axis must have size ``nproc``.
           On non-root processes, this may contain arbitrary data and will not be
           overwritten.
        root (int): Rank of the root MPI process.
        comm (mpi4py.MPI.Comm): The MPI communicator to use (defaults to
            a clone of :obj:`COMM_WORLD`).

    Returns:
        DeviceArray: Received data.

    """
    raise_if_token_is_set(token)

    if comm is None:
        comm = get_default_comm()

    rank = comm.Get_rank()
    if rank == root:
        size = comm.Get_size()
        if x.shape[0] != size:
            raise ValueError("Scatter input must have shape (nproc, ...)")

    comm = wrap_as_hashable(comm)

    return mpi_scatter_p.bind(
        x,
        root=root,
        comm=comm,
    )


def _mpi_scatter_xla_encode(ctx, x, root, comm):
    """Common lowering for all platforms using FFI with attributes."""
    comm = unpack_hashable(comm)

    x_aval, *_ = ctx.avals_in
    x_nptype = x_aval.dtype
    out_aval, *_ = ctx.avals_out

    # compute total number of elements in output array
    nitems = _np.prod(out_aval.shape, dtype=_np.int64)
    dtype_handle = _np.int64(to_dtype_handle(x_nptype))

    token = get_token_effect(ctx, ordered_effect)
    operands = (x, token)

    ctx_with_token = ctx.replace(
        avals_in=(*ctx.avals_in, core.abstract_token),
        avals_out=(*ctx.avals_out, core.abstract_token),
    )

    lowering_rule = ffi_lowering(
        "mpi_scatter_ffi",
        has_side_effect=True,
    )

    results = lowering_rule(
        ctx_with_token,
        *operands,
        sendcount=nitems,
        sendtype=dtype_handle,
        recvcount=nitems,
        recvtype=dtype_handle,
        root=_np.int64(root),
        comm=_np.int64(to_mpi_handle(comm)),
    )

    results = list(results)
    token = results.pop(-1)
    set_token_effect(ctx, ordered_effect, token)

    return results


# Platform-specific lowering rules (all use the same FFI implementation)
mpi_scatter_xla_encode_cpu = translation_rule_cpu(_mpi_scatter_xla_encode)
mpi_scatter_xla_encode_cuda = translation_rule_cuda(_mpi_scatter_xla_encode)
mpi_scatter_xla_encode_xpu = translation_rule_xpu(_mpi_scatter_xla_encode)


# This function evaluates only the shapes during AST construction
def mpi_scatter_abstract_eval(x, root, comm):
    comm = unpack_hashable(comm)
    rank = comm.Get_rank()
    if rank == root:
        out_shape = x.shape[1:]
    else:
        out_shape = x.shape

    return ShapedArray(out_shape, x.dtype), {ordered_effect}


mpi_scatter_p.def_impl(mpi_scatter_impl)
mpi_scatter_p.def_effectful_abstract_eval(mpi_scatter_abstract_eval)

# assign to the primitive the correct encoder
register_lowering(mpi_scatter_p, mpi_scatter_xla_encode_cpu, platform="cpu")
register_lowering(mpi_scatter_p, mpi_scatter_xla_encode_cuda, platform="cuda")
register_lowering(mpi_scatter_p, mpi_scatter_xla_encode_xpu, platform="xpu")
