/**
 * 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_half.asc
 * \brief
 */

#include <algorithm>
#include <cmath>
#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "tiling/platform/platform_ascendc.h"
#include "simt_api/asc_fp16.h"

__global__ void math_custom(const half* x, half* 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 half results[] = {hlog2(x[idx]), hlog10(x[idx]), hcos(x[idx]), hsin(x[idx])};
    z[idx] = results[idx];
}

std::vector<uint16_t> run_math_functions(const std::vector<uint16_t>& x)
{
    size_t total_byte_size = x.size() * sizeof(uint16_t);
    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;
    half* x_device = nullptr;
    half* 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);
    // Calculate split parameters
    uint32_t block_num = 1;
    uint32_t thread_num_per_block = x.size();
    uint32_t dyn_ubuf_size = 0; // No need to alloc dynamic memory.
    // Call kernel function with <<<...>>>
    math_custom<<<block_num, thread_num_per_block, dyn_ubuf_size, 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<uint16_t> output((uint16_t*)z_host, (uint16_t*)(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<uint16_t>& output, const std::vector<float>& golden)
{
    constexpr float tolerance = 1e-2f;
    bool is_match = output.size() == golden.size();
    for (size_t i = 0; is_match && i < output.size(); ++i) {
        is_match = std::fabs(aclFloat16ToFloat(output[i]) - golden[i]) <= tolerance;
    }
    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> input = {0.5f, 0.6f, 0.7f, 0.8f};
    std::vector<uint16_t> x;
    x.reserve(input.size());
    for (float value : input) {
        x.push_back(aclFloatToFloat16(value));
    }
    std::vector<float> golden = {std::log2(input[0]), std::log10(input[1]), std::cos(input[2]), std::sin(input[3])};

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