# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

import pytest
import triton
import triton.language as tl
import triton.language.extra.cann.libdevice as libdevice
import test_common
import torch
import os
import numpy as np

PERF_TEST_ENABLE = os.getenv('PERF_TEST_ENABLE', 'False').lower() == 'true'

def torch_float_as_int(x0):
    expected = x0.cpu().numpy()
    expected = expected.view(np.int32)
    expected = torch.tensor(expected).npu()
    return expected

@triton.jit
def triton_float_as_int(in_ptr0, out_ptr0, XBLOCK: tl.constexpr, XBLOCK_SUB: tl.constexpr):
    xoffset = tl.program_id(0) * XBLOCK
    base = tl.arange(0, XBLOCK_SUB)
    loops: tl.constexpr = XBLOCK // XBLOCK_SUB

    for loop in range(loops):
        xindex = xoffset + loop * XBLOCK_SUB + base
        x0 = tl.load(in_ptr0 + xindex)
        y = libdevice.float_as_int(x0)
        tl.store(out_ptr0 + xindex, y)

    remaining: tl.constexpr = XBLOCK % XBLOCK_SUB
    if remaining > 0:
        rem_xindex = xoffset + loops * XBLOCK_SUB + base
        mask = base < remaining
        x0 = tl.load(in_ptr0 + rem_xindex, mask=mask)
        y = libdevice.float_as_int(x0)
        tl.store(out_ptr0 + rem_xindex, y, mask=mask)

default_param_list = test_common.make_default_param_list(['float32'])
full_param_list = test_common.make_full_param_list(['float32'])

@pytest.mark.parametrize(
    'param_list',
    default_param_list if not PERF_TEST_ENABLE else full_param_list,
)
def test_float_as_int_common(param_list):
    dtype, shape, ncore, xblock, xblock_sub = param_list
    x0 = test_common.generate_tensor(shape, dtype).npu()
    y_ref = torch_float_as_int(x0)
    y_cal = torch.zeros(shape, dtype=torch.int32).npu()

    if PERF_TEST_ENABLE:
        test_common.run_with_profiler(
            lambda: triton_float_as_int[ncore, 1, 1](x0, y_cal, xblock, xblock_sub),
            shape,
            'float_as_int'
        )
    else:
        triton_float_as_int[ncore, 1, 1](x0, y_cal, xblock, xblock_sub)

    test_common.validate_cmp("int32", y_cal, y_ref)


@pytest.mark.parametrize(
    'param_list',
    [['float32', (64,), 1, 64, 64]],
)
def test_float_as_int_special_values(param_list):
    dtype, shape, ncore, xblock, xblock_sub = param_list
    x0 = test_common.generate_tensor(shape, dtype).npu()
    x0[0] = float('inf')
    x0[1] = float('-inf')
    x0[2] = float('nan')
    x0[3] = 0.0
    x0[4] = -0.0
    x0[5] = 1e38
    y_ref = torch_float_as_int(x0)
    y_cal = torch.zeros(shape, dtype=torch.int32).npu()
    triton_float_as_int[ncore, 1, 1](x0, y_cal, xblock, xblock_sub)
    test_common.validate_cmp("int32", y_cal, y_ref)