/**
 * Copyright (c) 2026 Huawei Technologies Co., Ltd.
 * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
 * CANN Open Software License Agreement Version 2.0 (the "License").
 * Please refer to the License for details. You may not use this file except in compliance with the License.
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
 * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
 * See LICENSE in the root of the software repository for the full text of the License.
 */

/* !
 * \file math_cpp.asc
 * \brief
 */

#include <algorithm>
#include <cmath>
#include <iostream>
#include <iterator>
#include <vector>
#include "acl/acl.h"
#include "kernel_operator.h"
#include "simt_api/asc_simt.h"

__simt_vf__ __launch_bounds__(1024) inline void simt_math_custom(
    __gm__ float* x, __gm__ float* z, uint64_t total_length)
{
    // Calculate global thread ID
    int32_t idx = blockIdx.x * blockDim.x + threadIdx.x;

    // Maps to the row index of output tensor
    if (idx >= total_length) {
        return;
    }
    const float results[] = {AscendC::Simt::Tan(x[idx]),   AscendC::Simt::Tanh(x[idx]), AscendC::Simt::Atan(x[idx]),
                             AscendC::Simt::Atanh(x[idx]), AscendC::Simt::Exp(x[idx]),  AscendC::Simt::Log(x[idx]),
                             AscendC::Simt::Cos(x[idx]),   AscendC::Simt::Cosh(x[idx]), AscendC::Simt::Sin(x[idx]),
                             AscendC::Simt::Sinh(x[idx])};
    z[idx] = results[idx];
}

__global__ __vector__ void math_custom(__gm__ float* x, __gm__ float* z, uint64_t total_length)
{
    asc_vf_call<simt_math_custom>(dim3(10), x, z, total_length);
}

std::vector<float> run_math_functions(const std::vector<float>& x)
{
    size_t total_byte_size = x.size() * sizeof(float);
    int32_t device_id = 0;
    aclrtStream stream = nullptr;

    const uint8_t* x_host = reinterpret_cast<const uint8_t*>(x.data());
    uint8_t* z_host = nullptr;
    float* x_device = nullptr;
    float* z_device = nullptr;
    // Init
    aclInit(nullptr);
    aclrtSetDevice(device_id);
    aclrtCreateStream(&stream);
    // Malloc memory in host and device
    aclrtMallocHost((void**)(&z_host), total_byte_size);
    aclrtMalloc((void**)&x_device, total_byte_size, ACL_MEM_MALLOC_HUGE_FIRST);
    aclrtMalloc((void**)&z_device, total_byte_size, ACL_MEM_MALLOC_HUGE_FIRST);
    aclrtMemcpy(x_device, total_byte_size, x_host, total_byte_size, ACL_MEMCPY_HOST_TO_DEVICE);
    // Call kernel function with <<<...>>>
    math_custom<<<1, 0, stream>>>(x_device, z_device, x.size());
    aclrtSynchronizeStream(stream);
    // Copy result from device to host
    aclrtMemcpy(z_host, total_byte_size, z_device, total_byte_size, ACL_MEMCPY_DEVICE_TO_HOST);
    std::vector<float> output((float*)z_host, (float*)(z_host + total_byte_size));
    // Free memory
    aclrtFree(x_device);
    aclrtFree(z_device);
    aclrtFreeHost(z_host);
    // Deinitialize
    aclrtDestroyStream(stream);
    aclrtResetDevice(device_id);
    aclFinalize();
    return output;
}

uint32_t verify_result(const std::vector<float>& output, const std::vector<float>& golden)
{
    constexpr float relative_tolerance = 1e-4f;
    constexpr float absolute_tolerance = 1e-5f;
    bool is_match =
        output.size() == golden.size() &&
        std::equal(output.begin(), output.end(), golden.begin(), [](float actual, float expected) {
            return std::fabs(actual - expected) <= absolute_tolerance + relative_tolerance * std::fabs(expected);
        });
    std::cout << (is_match ? "[Success] Case accuracy verification passed." :
                             "[Failed] Case accuracy verification failed!")
              << std::endl;
    return is_match ? 0 : 1;
}

int32_t main(int32_t argc, char* argv[])
{
    std::vector<float> x = {0.1f, 0.2f, 0.3f, 0.4f, 0.5f, 0.6f, 0.7f, 0.8f, 0.9f, 1.0f};
    std::vector<float> golden = {std::tan(x[0]), std::tanh(x[1]), std::atan(x[2]), std::atanh(x[3]), std::exp(x[4]),
                                 std::log(x[5]), std::cos(x[6]),  std::cosh(x[7]), std::sin(x[8]),   std::sinh(x[9])};

    return verify_result(run_math_functions(x), golden);
}