/**
* Copyright (c) 2025 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 cosh.asc
 * \brief
 */

#include <random>
#include "acl/acl.h"
#include "kernel_operator.h"

template <typename T>
class KernelCosh {
public:
    __aicore__ inline KernelCosh() {}
    __aicore__ inline void Init(GM_ADDR srcGm, GM_ADDR dstGm, uint32_t srcSize, AscendC::TPipe* pipeIn)
    {
        pipe = pipeIn;
        srcGlobal.SetGlobalBuffer(reinterpret_cast<__gm__ T*>(srcGm), srcSize);
        dstGlobal.SetGlobalBuffer(reinterpret_cast<__gm__ T*>(dstGm), srcSize);
        pipe->InitBuffer(inQueueX, 1, srcSize * sizeof(T));
        pipe->InitBuffer(outQueue, 1, srcSize * sizeof(T));
        bufferSize = srcSize;
    }
    __aicore__ inline void Process()
    {
        CopyIn();
        Compute();
        CopyOut();
    }

    __aicore__ inline void CopyIn()
    {
        AscendC::LocalTensor<T> srcLocal = inQueueX.AllocTensor<T>();
        AscendC::DataCopy(srcLocal, srcGlobal, bufferSize);
        inQueueX.EnQue(srcLocal);
    }
    __aicore__ inline void Compute()
    {
        AscendC::LocalTensor<T> srcLocal = inQueueX.DeQue<T>();
        AscendC::LocalTensor<T> dstLocal = outQueue.AllocTensor<T>();
        AscendC::Cosh<T, false>(dstLocal, srcLocal, bufferSize);
        outQueue.EnQue<T>(dstLocal);
        inQueueX.FreeTensor(srcLocal);
    }
    __aicore__ inline void CopyOut()
    {
        AscendC::LocalTensor<T> dstLocal = outQueue.DeQue<T>();
        AscendC::DataCopy(dstGlobal, dstLocal, bufferSize);
        outQueue.FreeTensor(dstLocal);
    }

private:
    AscendC::TPipe* pipe;
    AscendC::TQue<AscendC::QuePosition::VECIN, 1> inQueueX;
    AscendC::TQue<AscendC::QuePosition::VECOUT, 1> outQueue;
    AscendC::GlobalTensor<T> srcGlobal;
    AscendC::GlobalTensor<T> dstGlobal;
    uint32_t bufferSize = 0;
};

__global__ __aicore__ void cosh_custom(GM_ADDR srcGm, GM_ADDR dstGm)
{
    KERNEL_TASK_TYPE_DEFAULT(KERNEL_TYPE_AIV_ONLY);
    AscendC::TPipe pipe;
    constexpr uint32_t srcSize = 256;
    KernelCosh<float> op;
    op.Init(srcGm, dstGm, srcSize, &pipe);
    op.Process();
}

static bool CompareResult(const void* outputData, const void* goldenData, uint32_t outSize)
{
    size_t goldenSize = outSize;
    constexpr float EPS = 1e-4;
    int64_t wrongNum = 0;

    for (size_t i = 0; i < outSize / sizeof(float); i++) {
        float a = (reinterpret_cast<const float*>(outputData))[i];
        float b = (reinterpret_cast<const float*>(goldenData))[i];
        float ae = std::abs(a - b);
        float re = ae / std::abs(b);
        if (ae > EPS && re > EPS) {
            printf("CompareResult failed output is %lf, golden is %lf\n", a, b);
            wrongNum++;
        }
    }
    if (wrongNum != 0) {
        return false;
    } else {
        printf("CompareResult success!\n");
        return true;
    }
}

// 定义返回结构体
struct GoldenData {
    std::vector<float> src;
    std::vector<float> golden;
};

GoldenData gen_golden_data()
{
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_real_distribution<float> dis(-11.089f, 11.089f);
    const int dtype = 0;
    const int src_shape = 256;
    std::vector<float> src(src_shape - 3);
    for (int i = 0; i < src.size(); ++i) {
        src[i] = dis(gen);
    }

    src.push_back(-11.089f);
    src.push_back(0.0f);
    src.push_back(11.089f);

    std::vector<float> golden(src.size());
    for (size_t i = 0; i < src.size(); ++i) {
        golden[i] = std::cosh(src[i]);
    }
    return {src, golden};
}

int32_t main(int32_t argc, char* argv[])
{
    size_t param1FileSize = 256 * sizeof(float);
    size_t param2FileSize = 256 * sizeof(float);
    uint32_t numBlocks = 1;

    auto genData = gen_golden_data();
    auto src = genData.src;
    auto golden = genData.golden;
    uint8_t* goldenHost = reinterpret_cast<uint8_t*>(golden.data());

    aclInit(nullptr);
    aclrtContext context;
    int32_t deviceId = 0;
    aclrtSetDevice(deviceId);
    aclrtCreateContext(&context, deviceId);
    aclrtStream stream = nullptr;
    aclrtCreateStream(&stream);

    uint8_t* param1Host = reinterpret_cast<uint8_t*>(src.data());
    uint8_t* param1Device = nullptr;
    aclrtMalloc((void**)&param1Device, param1FileSize, ACL_MEM_MALLOC_HUGE_FIRST);
    aclrtMemcpy(param1Device, param1FileSize, param1Host, param1FileSize, ACL_MEMCPY_HOST_TO_DEVICE);

    uint8_t* param2Host;
    uint8_t* param2Device;
    aclrtMallocHost((void**)(&param2Host), param2FileSize);
    aclrtMalloc((void**)&param2Device, param2FileSize, ACL_MEM_MALLOC_HUGE_FIRST);

    cosh_custom<<<numBlocks, nullptr, stream>>>(param1Device, param2Device);
    aclrtSynchronizeStream(stream);

    aclrtFree(param1Device);
    aclrtFreeHost(param1Host);
    aclrtMemcpy(param2Host, param2FileSize, param2Device, param2FileSize, ACL_MEMCPY_DEVICE_TO_HOST);

    bool goldenResult = true;
    goldenResult = CompareResult(param2Host, goldenHost, param2FileSize);
    if (goldenResult) {
        printf("test pass!\n");
    } else {
        printf("test failed!\n");
    }

    aclrtFree(param2Device);
    aclrtFreeHost(param2Host);

    aclrtDestroyStream(stream);
    aclrtDestroyContext(context);
    aclrtResetDevice(deviceId);
    aclFinalize();

    return 0;
}