#include "../../../tensor.h"
#include "rearrange_kernel.h"
#include "rearrange_moore.h"
#include <algorithm>
#include <cmath>
#include <memory>
#include <stdint.h>
#include <vector>

namespace op::rearrange::moore {

struct Descriptor::Opaque {
    std::shared_ptr<device::moore::Handle::Internal> internal;
};

Descriptor::~Descriptor() {
    delete _opaque;
}

infiniStatus_t Descriptor::create(
    infiniopHandle_t handle,
    Descriptor **desc_ptr,
    infiniopTensorDescriptor_t y_desc,
    infiniopTensorDescriptor_t x_desc) {

    auto dtype = y_desc->dtype();
    auto ndim = y_desc->ndim();

    CHECK_OR_RETURN(x_desc->dtype() == dtype, INFINI_STATUS_BAD_TENSOR_DTYPE);
    CHECK_OR_RETURN(x_desc->ndim() == ndim, INFINI_STATUS_BAD_TENSOR_SHAPE);

    auto x_shape = x_desc->shape();
    auto y_shape = y_desc->shape();
    auto y_strides = y_desc->strides();
    auto x_strides = x_desc->strides();

    CHECK_SAME_SHAPE(x_shape, y_shape);

    auto meta = utils::RearrangeMeta::create(
        y_shape.data(),
        y_strides.data(),
        x_strides.data(),
        ndim,
        infiniSizeOf(dtype));

    CHECK_RESULT(meta);

    *desc_ptr = new Descriptor(
        std::move(*meta),
        new Opaque{reinterpret_cast<device::moore::Handle *>(handle)->internal()},
        handle->device, handle->device_id);
    return INFINI_STATUS_SUCCESS;
}

struct Dim {
    size_t len;
    ARRAY_TYPE_STRIDE src_stride;
    ARRAY_TYPE_STRIDE dst_stride;
};

struct SplitDim {
    size_t choose_idx;
    size_t num_per_block;
    size_t num_per_grid;
    int array_struct_idx_block;
    int array_struct_idx_grid;
    size_t dim_len;
};


utils::Result<RearrangeParams> prepareRearrangeParams(const utils::RearrangeMeta &original_meta, int max_threads) {
    RearrangeParams params;

    auto meta_result = original_meta.distributeUnit({32, 16, 8, 4, 2, 1});
    CHECK_RESULT(meta_result);
    const utils::RearrangeMeta &meta = meta_result.take();

    const size_t ndim = meta.ndim();
    const size_t unit = meta.unit();

    if (ndim == 0) {
        params.block_dim = 0;
        params.block_len_total = 1;
        params.block_len = {static_cast<ARRAY_TYPE_SIZE>(1)};
        params.src_block_stride = {static_cast<ARRAY_TYPE_STRIDE>(0)};
        params.dst_block_stride = {static_cast<ARRAY_TYPE_STRIDE>(0)};
        params.grid_len = {static_cast<ARRAY_TYPE_SIZE>(1)};
        params.src_grid_stride = {static_cast<ARRAY_TYPE_STRIDE>(0)};
        params.dst_grid_stride = {static_cast<ARRAY_TYPE_STRIDE>(0)};
        params.unit_size = unit;
        return utils::Result<RearrangeParams>(params);
    }

    const ptrdiff_t *idx_strides = meta.idx_strides();
    const ptrdiff_t *dst_strides = meta.dst_strides();
    const ptrdiff_t *src_strides = meta.src_strides();

    std::vector<Dim> dims;
    std::vector<size_t> shape;
    dims.reserve(ndim);
    shape.reserve(ndim);

    auto prev_idx_stride = meta.count();
    for (size_t i = 0; i < ndim; ++i) {
        size_t len = prev_idx_stride / idx_strides[i];
        shape.push_back(len);
        dims.push_back({len, src_strides[i], dst_strides[i]});
        prev_idx_stride = idx_strides[i];
    }

    std::vector<bool> block_dim_choose(ndim, false);
    std::vector<SplitDim> split_dims;

    std::vector<size_t> dim_order(ndim);
    for (size_t i = 0; i < ndim; ++i) {
        dim_order[i] = i;
    }

    std::sort(dim_order.begin(), dim_order.end(),
              [&dims](size_t a, size_t b) {
                  return std::abs(dims[a].src_stride) < std::abs(dims[b].src_stride);
              });

    constexpr size_t MAX_BLOCK_DIM = MAX_BLOCK_ARRAY_SIZE;

    size_t block_elements = 1;
    size_t chosen_block_dims = 0;

    for (size_t i = 0; i < ndim; ++i) {
        size_t dim_idx = dim_order[i];
        size_t dim_len = shape[dim_idx];
    
        if (chosen_block_dims < MAX_BLOCK_DIM &&
            block_elements * dim_len <= (size_t)max_threads) {
    
            block_dim_choose[dim_idx] = true;
            block_elements *= dim_len;
            chosen_block_dims++;
            continue;
        }
    
        if (block_elements > 1 && dim_len > 1) {
    
            if (chosen_block_dims + 1 > MAX_BLOCK_DIM) {
                break; 
            }
    
            size_t num_per_block =
                std::min(dim_len, (size_t)max_threads / block_elements);
    
            if (num_per_block > 0) {
                size_t num_per_grid =
                    (dim_len + num_per_block - 1) / num_per_block;
    
                split_dims.push_back({
                    dim_idx,
                    num_per_block,
                    num_per_grid,
                    0,
                    0,
                    dim_len
                });
    
                block_elements *= num_per_block;
                chosen_block_dims++; 
            }
            break;
        }
    }
    


    if (block_elements == 1 && ndim > 0) {
        size_t dim_idx = dim_order[0];
        size_t dim_len = shape[dim_idx];

        if (dim_len <= (size_t)max_threads) {
            block_dim_choose[dim_idx] = true;
            block_elements = dim_len;
        } else {
            size_t num_per_block = std::min(dim_len, (size_t)max_threads);
            size_t num_per_grid = (dim_len + num_per_block - 1) / num_per_block;

            SplitDim split_dim = {
                dim_idx,
                num_per_block,
                num_per_grid,
                0,
                0,
                dim_len};
            split_dims.push_back(split_dim);
            block_elements = num_per_block;
        }
    }

    size_t block_dim = 0;
    size_t block_len_total = block_elements;

    std::vector<ARRAY_TYPE_SIZE> block_len;
    std::vector<ARRAY_TYPE_STRIDE> src_block_stride;
    std::vector<ARRAY_TYPE_STRIDE> dst_block_stride;

    std::vector<ARRAY_TYPE_SIZE> grid_len;
    std::vector<ARRAY_TYPE_STRIDE> src_grid_stride;
    std::vector<ARRAY_TYPE_STRIDE> dst_grid_stride;

    for (size_t i = 0; i < ndim; ++i) {
        if (block_dim_choose[i]) {
            block_len.push_back(shape[i]);
            src_block_stride.push_back(dims[i].src_stride);
            dst_block_stride.push_back(dims[i].dst_stride);
            block_dim += 1;
        }

        for (size_t j = 0; j < split_dims.size(); ++j) {
            if (i == split_dims[j].choose_idx) {
                block_len.push_back(split_dims[j].num_per_block);
                src_block_stride.push_back(dims[i].src_stride);
                dst_block_stride.push_back(dims[i].dst_stride);
                split_dims[j].array_struct_idx_block = static_cast<int>(block_dim);
                block_dim += 1;
            }
        }
    }

    for (size_t i = 0; i < ndim; ++i) {
        if (!block_dim_choose[i]) {
            bool is_split = false;

            for (size_t j = 0; j < split_dims.size(); ++j) {
                if (i == split_dims[j].choose_idx) {
                    is_split = true;
                    grid_len.push_back(split_dims[j].num_per_grid);
                    src_grid_stride.push_back(dims[i].src_stride * split_dims[j].num_per_block);
                    dst_grid_stride.push_back(dims[i].dst_stride * split_dims[j].num_per_block);
                    split_dims[j].array_struct_idx_grid = static_cast<int>(grid_len.size() - 1);
                    break;
                }
            }

            if (!is_split) {
                grid_len.push_back(shape[i]);
                src_grid_stride.push_back(dims[i].src_stride);
                dst_grid_stride.push_back(dims[i].dst_stride);
            }
        }
    }

    if (grid_len.empty()) {
        grid_len.push_back(1);
        src_grid_stride.push_back(0);
        dst_grid_stride.push_back(0);
    }

    std::vector<Constraint<ARRAY_TYPE_SIZE>> constraints;

    for (size_t i = 0; i < split_dims.size(); ++i) {
        if (split_dims[i].dim_len % split_dims[i].num_per_block == 0) {
            continue;
        }
        Constraint<ARRAY_TYPE_SIZE> constraint;
        constraint.grid_idx = split_dims[i].array_struct_idx_grid;
        constraint.block_idx = split_dims[i].array_struct_idx_block;
        constraint.grid_div_block = split_dims[i].num_per_block;
        constraint.total_len = split_dims[i].dim_len;
        constraints.push_back(constraint);

        if (constraints.size() >= 2) {
            break;
        }
    }

    params.block_dim = block_dim;
    params.block_len_total = block_len_total;
    params.block_len = block_len;
    params.src_block_stride = src_block_stride;
    params.dst_block_stride = dst_block_stride;
    params.grid_len = grid_len;
    params.src_grid_stride = src_grid_stride;
    params.dst_grid_stride = dst_grid_stride;
    params.constraints = constraints;
    params.unit_size = unit;

    return utils::Result<RearrangeParams>(params);
}

template <unsigned int BLOCK_SIZE>
infiniStatus_t launchKernel(
    void *y,
    const void *x,
    size_t grid_size,
    const RearrangeParams &params,
    size_t unit_size,
    musaStream_t stream) {

    RearrangeParams params_copy = params; 
    auto kernel_func_result = getRearrangeKernel(params_copy);

    CHECK_RESULT(kernel_func_result);
    auto kernel_func = kernel_func_result.take();

    size_t block_dim = params.block_dim;
    size_t block_len_total = params.block_len_total;

    // Calculate aligned thread block size to match MUSA architecture's Warp characteristics:
    // - MUSA architecture uses 32 threads as the fundamental scheduling unit (1 Warp).
    // - Round up to the nearest multiple of 32 to ensure the block consists of full Warps.
    // - MUSA hardware/scheduler typically requires thread counts to be multiples of 32.
    size_t aligned_block_size = ((block_len_total + 31) / 32) * 32;
    // block_len_total = aligned_block_size;

    // Ensure the aligned block size does not exceed hardware or template-defined limits.
    if (aligned_block_size > BLOCK_SIZE) {
        aligned_block_size = BLOCK_SIZE;  
    }

    // Validate that vector dimensions are sufficient for the specified block dimension.
    if (params.block_len.size() < block_dim || params.src_block_stride.size() < block_dim || params.dst_block_stride.size() < block_dim) {
        return INFINI_STATUS_BAD_PARAM;
    }

    if (params.grid_len.empty() || params.src_grid_stride.empty() || params.dst_grid_stride.empty()) {
        return INFINI_STATUS_BAD_PARAM;
    }

    const Constraint<ARRAY_TYPE_SIZE> *constraints_data;
    auto empty_constraints = Constraint<ARRAY_TYPE_SIZE>();
    if (params.constraints.empty()) {
        constraints_data = &empty_constraints;
    } else {
        constraints_data = params.constraints.data();
    }

    void *args[]
        = {
            &y, &x,
            &block_dim,
            &block_len_total,
            const_cast<void *>(static_cast<const void *>(params.block_len.data())),
            const_cast<void *>(static_cast<const void *>(params.src_block_stride.data())),
            const_cast<void *>(static_cast<const void *>(params.dst_block_stride.data())),
            const_cast<void *>(static_cast<const void *>(params.grid_len.data())),
            const_cast<void *>(static_cast<const void *>(params.src_grid_stride.data())),
            const_cast<void *>(static_cast<const void *>(params.dst_grid_stride.data())),
            const_cast<void *>(static_cast<const void *>(constraints_data))};

    // The blockDim for musaLaunchKernel must satisfy the following constraints:
    // - Must be a multiple of 32 (aligned with MUSA's Warp scheduling mechanism).
    // - Must be greater than or equal to the number of elements to process (block_len_total).
    // - Math equivalent: ceil(n / 32) * 32 (rounding up to the nearest warp).
    CHECK_OR_RETURN(musaLaunchKernel(
                        kernel_func,
                        static_cast<unsigned int>(grid_size), static_cast<unsigned int>(aligned_block_size),
                        args, 0, stream)
                        == musaSuccess,
                    INFINI_STATUS_INTERNAL_ERROR);

    // Synchronize the device to detect potential asynchronous kernel execution errors.
    musaError_t err = musaDeviceSynchronize();
    if (err != musaSuccess) {
        std::cerr << "[ERROR] musaDeviceSynchronize failed: " << err << std::endl;
        return INFINI_STATUS_INTERNAL_ERROR;
    }

    return INFINI_STATUS_SUCCESS;
}

infiniStatus_t Descriptor::calculate(
    void *y,
    const void *x,
    void *stream) const {

    auto musa_stream = reinterpret_cast<musaStream_t>(stream);

    if (_meta.ndim() == 0) {
        CHECK_OR_RETURN(musaMemcpyAsync(y, x, _meta.unit(), musaMemcpyDeviceToDevice, musa_stream) == musaSuccess,
                        INFINI_STATUS_INTERNAL_ERROR);
        return INFINI_STATUS_SUCCESS;
    }

    int max_threads = _opaque->internal->maxThreadsPerBlock();

    auto params_result = prepareRearrangeParams(_meta, std::min(MOORE_BLOCK_SIZE_1024, max_threads));
    CHECK_RESULT(params_result);
    auto params = params_result.take();

    size_t grid_size = 1;
    for (size_t i = 0; i < params.grid_len.size(); ++i) {
        grid_size *= params.grid_len[i];
    }

    if (grid_size == 0) {
        return INFINI_STATUS_BAD_PARAM;
    }

    infiniStatus_t status = INFINI_STATUS_DEVICE_ARCHITECTURE_NOT_SUPPORTED;

    size_t block_size = params.block_len_total;

    if (block_size <= MOORE_BLOCK_SIZE_512) {
        status = launchKernel<MOORE_BLOCK_SIZE_512>(y, x, grid_size, params, _meta.unit(), musa_stream);
    } else if (block_size <= MOORE_BLOCK_SIZE_1024) {
        status = launchKernel<MOORE_BLOCK_SIZE_1024>(y, x, grid_size, params, _meta.unit(), musa_stream);
    } else {
        return INFINI_STATUS_DEVICE_ARCHITECTURE_NOT_SUPPORTED;
    }

    return status;
}

} // namespace op::rearrange::moore
