/**
 * 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.
 */

/* Generated By CANNBot */

#include <iostream>
#include <fstream>
#include <string.h>
#include <stdint.h>
#include <vector>
#include <string>
#include <map>
#include "assert.h"

#include "graph.h"
#include "types.h"
#include "tensor.h"
#include "ge_error_codes.h"
#include "ge_api_types.h"
#include "ge_api.h"
#include "ops_proto_legacy.h"
#include "ge_ir_build.h"

// SoftplusGrad is registered in CANN built-in ops_proto_legacy.h (same op name).
// Use the built-in definition here for graph construction; do NOT include
// op_graph/softplus_grad_proto.h to avoid duplicate REG_OP(SoftplusGrad).
// Runtime implementation is resolved from the installed vendor package.

#define FAILED -1
#define SUCCESS 0

using namespace ge;
using std::map;
using std::string;
using std::vector;

string GetTime()
{
    time_t timep;
    time(&timep);
    char tmp[64];
    strftime(tmp, sizeof(tmp), "%Y-%m-%d %H:%M:%S,000", localtime(&timep));
    return tmp;
}

uint32_t GetDataTypeSize(DataType dt)
{
    if (dt == ge::DT_FLOAT) return 4;
    if (dt == ge::DT_FLOAT16) return 2;
    if (dt == ge::DT_BF16) return 2;
    if (dt == ge::DT_INT32) return 4;
    if (dt == ge::DT_INT64) return 8;
    if (dt == ge::DT_INT8) return 1;
    return 4;
}

int32_t GenOnesDataFloat32(vector<int64_t> shapes, Tensor &input_tensor, TensorDesc &input_tensor_desc, float value)
{
    input_tensor_desc.SetRealDimCnt(shapes.size());
    size_t size = 1;
    for (uint32_t i = 0; i < shapes.size(); i++) {
        size *= shapes[i];
    }
    uint32_t data_len = size * 4;
    float *pData = new (std::nothrow) float[size];
    if (pData == nullptr) {
        return FAILED;
    }
    for (size_t i = 0; i < size; ++i) {
        *(pData + i) = value;
    }
    input_tensor = Tensor(input_tensor_desc, (uint8_t *)pData, data_len);
    delete[] pData;
    pData = nullptr;
    return SUCCESS;
}

int32_t WriteDataToFile(string bin_file, uint64_t data_size, uint8_t *inputData)
{
    FILE *fp = fopen(bin_file.c_str(), "wb");
    if (fp == nullptr) {
        printf("Failed to open file: %s\n", bin_file.c_str());
        return FAILED;
    }
    fwrite(inputData, sizeof(uint8_t), data_size, fp);
    fclose(fp);
    return SUCCESS;
}

int CreateOppInGraph(DataType inDtype, std::vector<ge::Tensor> &input, std::vector<Operator> &inputs,
    std::vector<Operator> &outputs, Graph &graph)
{
    Status ret = SUCCESS;
    auto softplusGrad1 = op::SoftplusGrad("softplus_grad_1");

    // Broadcast scenario: gradients {1, 4} broadcasts to features {2, 4}
    // gradients = 1.0, features = 2.0
    // Expected: backprops = gradients * sigmoid(features) = 1.0 * sigmoid(2.0) = 0.8808
    vector<int64_t> gradShape = {1, 4};
    vector<int64_t> featShape = {2, 4};
    vector<int64_t> outShape = {2, 4};
    float gradValue = 1.0f;
    float featValue = 2.0f;

    // Input 0: gradients
    auto placeholder0 = op::Data("placeholder0").set_attr_index(0);
    TensorDesc placeholder0_desc = TensorDesc(ge::Shape(gradShape), FORMAT_ND, inDtype);
    placeholder0_desc.SetPlacement(ge::kPlacementHost);
    placeholder0_desc.SetFormat(FORMAT_ND);
    Tensor tensor_placeholder0;
    ret = GenOnesDataFloat32(gradShape, tensor_placeholder0, placeholder0_desc, gradValue);
    if (ret != SUCCESS) {
        printf("%s - ERROR - [XIR]: Generate input data failed\n", GetTime().c_str());
        return FAILED;
    }
    placeholder0.update_input_desc_x(placeholder0_desc);
    input.push_back(tensor_placeholder0);
    graph.AddOp(placeholder0);
    softplusGrad1.set_input_gradients(placeholder0);
    inputs.push_back(placeholder0);

    // Input 1: features
    auto placeholder1 = op::Data("placeholder1").set_attr_index(1);
    TensorDesc placeholder1_desc = TensorDesc(ge::Shape(featShape), FORMAT_ND, inDtype);
    placeholder1_desc.SetPlacement(ge::kPlacementHost);
    placeholder1_desc.SetFormat(FORMAT_ND);
    Tensor tensor_placeholder1;
    ret = GenOnesDataFloat32(featShape, tensor_placeholder1, placeholder1_desc, featValue);
    if (ret != SUCCESS) {
        printf("%s - ERROR - [XIR]: Generate input data failed\n", GetTime().c_str());
        return FAILED;
    }
    placeholder1.update_input_desc_x(placeholder1_desc);
    input.push_back(tensor_placeholder1);
    graph.AddOp(placeholder1);
    softplusGrad1.set_input_features(placeholder1);
    inputs.push_back(placeholder1);

    // Output 0: backprops
    TensorDesc backprops_desc = TensorDesc(ge::Shape(outShape), FORMAT_ND, inDtype);
    softplusGrad1.update_output_desc_backprops(backprops_desc);

    outputs.push_back(softplusGrad1);
    return SUCCESS;
}

int main(int argc, char *argv[])
{
    const char *graph_name = "softplus_grad_ge_ir_test";
    Graph graph(graph_name);
    std::vector<ge::Tensor> input;
    ge::Session *session = nullptr;
    bool geInitialized = false;
    int32_t ret = SUCCESS;

    printf("%s - INFO - [XIR]: Start to initialize ge\n", GetTime().c_str());
    std::map<AscendString, AscendString> global_options = {{"ge.exec.deviceId", "0"}, {"ge.graphRunMode", "1"}};
    ret = ge::GEInitialize(global_options);
    if (ret != SUCCESS) {
        printf("%s - ERROR - [XIR]: Initialize ge failed\n", GetTime().c_str());
        return FAILED;
    }
    geInitialized = true;
    printf("%s - INFO - [XIR]: Initialize ge success\n", GetTime().c_str());

    std::vector<Operator> inputs{};
    std::vector<Operator> outputs{};
    DataType inDtype = DT_FLOAT;

    ret = CreateOppInGraph(inDtype, input, inputs, outputs, graph);
    if (ret != SUCCESS) {
        printf("%s - ERROR - [XIR]: Create graph failed\n", GetTime().c_str());
        goto cleanup;
    }

    if (!inputs.empty() && !outputs.empty()) {
        graph.SetInputs(inputs).SetOutputs(outputs);
    }

    {
        std::map<AscendString, AscendString> build_options = {};
        session = new Session(build_options);
        if (session == nullptr) {
            printf("%s - ERROR - [XIR]: Create session failed\n", GetTime().c_str());
            ret = FAILED;
            goto cleanup;
        }
    }

    {
        uint32_t graph_id = 0;
        std::map<AscendString, AscendString> graph_options = {};
        ret = session->AddGraph(graph_id, graph, graph_options);
        if (ret != SUCCESS) {
            printf("%s - ERROR - [XIR]: Add graph failed\n", GetTime().c_str());
            goto cleanup;
        }

        printf("%s - INFO - [XIR]: Start to run graph\n", GetTime().c_str());
        std::vector<ge::Tensor> output;
        ret = session->RunGraph(graph_id, input, output);
        if (ret != SUCCESS) {
            printf("%s - ERROR - [XIR]: Run graph failed\n", GetTime().c_str());
            goto cleanup;
        }
        printf("%s - INFO - [XIR]: Run graph success\n", GetTime().c_str());

        for (size_t i = 0; i < output.size(); i++) {
            string output_file = "./softplus_grad_ge_output_" + std::to_string(i) + ".bin";
            uint8_t *output_data = output[i].GetData();
            int64_t output_shape_size = output[i].GetTensorDesc().GetShape().GetShapeSize();
            uint32_t data_size = output_shape_size * GetDataTypeSize(output[i].GetTensorDesc().GetDataType());
            WriteDataToFile(output_file.c_str(), data_size, output_data);
            printf("Output %zu: shape_size=%ld, data_size=%u, file=%s\n", i, output_shape_size, data_size,
                   output_file.c_str());
        }
        printf("%s - INFO - [XIR]: Precision is ok\n", GetTime().c_str());
    }

cleanup:
    if (session != nullptr) {
        delete session;
        session = nullptr;
    }
    if (geInitialized) {
        int32_t finRet = ge::GEFinalize();
        if (finRet != SUCCESS) {
            printf("%s - ERROR - [XIR]: Finalize ge failed\n", GetTime().c_str());
            if (ret == SUCCESS) {
                ret = FAILED;
            }
        } else {
            printf("%s - INFO - [XIR]: Finalize ge success\n", GetTime().c_str());
        }
    }
    return ret;
}