/**
 * 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 <errno.h>
#include <stdlib.h>

#include <iostream>
#include <fstream>
#include <string.h>
#include <stdint.h>
#include <vector>
#include <string>
#include <map>
#include <memory>
#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 "array_ops.h"
#include "ge_ir_build.h"

#include "nn_other.h"
#include "../op_graph/fresnel_sin_proto.h"

#define FAILED -1
#define SUCCESS 0

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

#define ADD_INPUT(intputIndex, intputName, intputDtype, inputShape)                                                    \
    vector<int64_t> placeholder##intputIndex##_shape = inputShape;                                                     \
    auto placeholder##intputIndex = op::Data(("placeholder" + std::to_string(intputIndex)).c_str()).set_attr_index(0); \
    TensorDesc placeholder##intputIndex##_desc = TensorDesc(ge::Shape(placeholder##intputIndex##_shape), FORMAT_ND,    \
                                                            intputDtype);                                              \
    placeholder##intputIndex##_desc.SetPlacement(ge::kPlacementHost);                                                  \
    placeholder##intputIndex##_desc.SetFormat(FORMAT_ND);                                                              \
    Tensor tensor_placeholder##intputIndex;                                                                            \
    ret = GenOnesData(placeholder##intputIndex##_shape, tensor_placeholder##intputIndex,                               \
                      placeholder##intputIndex##_desc, intputDtype, 2);                                                \
    if (ret != SUCCESS) {                                                                                              \
        printf("%s - ERROR - [XIR]: Generate input data failed\n", GetTime().c_str());                                 \
        return FAILED;                                                                                                 \
    }                                                                                                                  \
    placeholder##intputIndex.update_input_desc_x(placeholder##intputIndex##_desc);                                     \
    input.push_back(tensor_placeholder##intputIndex);                                                                  \
    graph.AddOp(placeholder##intputIndex);                                                                             \
    fresnel_sin1.set_input_##intputName(placeholder##intputIndex);                                                     \
    inputs.push_back(placeholder##intputIndex);

#define ADD_OUTPUT(outputIndex, outputName, outputDtype, outputShape)                                       \
    TensorDesc outputName##outputIndex##_desc = TensorDesc(ge::Shape(outputShape), FORMAT_ND, outputDtype); \
    fresnel_sin1.update_output_desc_##outputName(outputName##outputIndex##_desc);

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)
{
    uint32_t dilation = 1;
    uint32_t twoByte = 2;
    uint32_t fourByte = 4;
    uint32_t eightByte = 8;

    if (dt == ge::DT_FLOAT) {
        dilation = fourByte;
    } else if (dt == ge::DT_FLOAT16) {
        dilation = twoByte;
    } else if (dt == ge::DT_BF16) {
        dilation = twoByte;
    } else if (dt == ge::DT_INT16) {
        dilation = twoByte;
    } else if (dt == ge::DT_UINT16) {
        dilation = twoByte;
    } else if (dt == ge::DT_INT32) {
        dilation = fourByte;
    } else if (dt == ge::DT_UINT32) {
        dilation = fourByte;
    } else if (dt == ge::DT_INT64) {
        dilation = eightByte;
    } else if (dt == ge::DT_UINT64) {
        dilation = eightByte;
    } else if (dt == ge::DT_INT8) {
        dilation = 1;
    }
    return dilation;
}

int32_t GenOnesData(vector<int64_t> shapes, Tensor& input_tensor, TensorDesc& input_tensor_desc, DataType data_type,
                    int value)
{
    input_tensor_desc.SetRealDimCnt(shapes.size());
    size_t size = 1;
    for (uint32_t i = 0; i < shapes.size(); i++) {
        size *= shapes[i];
    }
    uint64_t data_len = size * GetDataTypeSize(data_type);
    uint8_t* pData = new (std::nothrow) uint8_t[data_len];
    if (pData == nullptr) {
        return FAILED;
    }
    FILE* fp = fopen("./test_input.bin", "rb");
    if (fp != nullptr) {
        size_t read = fread(pData, 1, data_len, fp);
        fclose(fp);
        if (read != data_len) {
            printf("[WARN] test_input.bin: read %zu bytes, expected %zu\n", read, static_cast<size_t>(data_len));
        }
    } else {
        memset(pData, 0, data_len);
        printf("[WARN] test_input.bin not found, using zeros\n");
    }
    input_tensor = Tensor(input_tensor_desc, pData, data_len);
    delete[] pData;
    pData = nullptr;
    return SUCCESS;
}

int32_t WriteDataToFile(string bin_file, uint64_t data_size, uint8_t* inputData)
{
    if (data_size > 0 && inputData == nullptr) {
        printf("%s - ERROR - [XIR]: Write file %s failed, input data buffer is null while data size is %zu\n",
               GetTime().c_str(), bin_file.c_str(), static_cast<size_t>(data_size));
        return FAILED;
    }
    FILE* fp = fopen(bin_file.c_str(), "w");
    if (fp == nullptr) {
        printf("%s - ERROR - [XIR]: Open file %s failed\n", GetTime().c_str(), bin_file.c_str());
        return FAILED;
    }
    size_t written = fwrite(inputData, sizeof(uint8_t), data_size, fp);
    if (written != data_size) {
        printf("%s - ERROR - [XIR]: Write file %s failed, written %zu of %zu bytes\n", GetTime().c_str(),
               bin_file.c_str(), written, static_cast<size_t>(data_size));
        if (fclose(fp) != 0) {
            printf("%s - ERROR - [XIR]: Close file %s failed after short write (%s)\n", GetTime().c_str(),
                   bin_file.c_str(), strerror(errno));
        }
        return FAILED;
    }
    if (fclose(fp) != 0) {
        printf("%s - ERROR - [XIR]: Close file %s failed after writing %zu bytes (%s)\n", GetTime().c_str(),
               bin_file.c_str(), static_cast<size_t>(data_size), strerror(errno));
        return FAILED;
    }
    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 fresnel_sin1 = op::FresnelSin("fresnel_sin1");
    std::vector<int64_t> xShape = {2, 4};
    ADD_INPUT(1, x, inDtype, xShape);

    ADD_OUTPUT(1, y, inDtype, xShape);

    outputs.push_back(fresnel_sin1);
    return SUCCESS;
}

int main(int argc, char* argv[])
{
    const char* graph_name = "tc_ge_irrun_test";
    Graph graph(graph_name);
    std::vector<ge::Tensor> input;

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

    std::vector<Operator> inputs{};
    std::vector<Operator> outputs{};

    if (argc < 2) {
        printf("%s - ERROR - [XIR]: Missing required argument. Usage: %s <dtype_index> (0: DT_FLOAT, 1: DT_FLOAT16, "
               "2: DT_BF16)\n",
               GetTime().c_str(), argv[0]);
        ge::GEFinalize();
        return FAILED;
    }
    errno = 0;
    char* endptr = nullptr;
    long dtypeIndex = strtol(argv[1], &endptr, 10);
    if (errno != 0 || endptr == argv[1] || *endptr != '\0' || dtypeIndex < 0 || dtypeIndex > 2) {
        printf("%s - ERROR - [XIR]: Invalid dtype index '%s'. Usage: %s <dtype_index> (0: DT_FLOAT, 1: DT_FLOAT16, "
               "2: DT_BF16)\n",
               GetTime().c_str(), argv[1], argv[0]);
        ge::GEFinalize();
        return FAILED;
    }
    DataType inDtype = DT_FLOAT;
    if (dtypeIndex == 1) {
        inDtype = DT_FLOAT16;
    } else if (dtypeIndex == 2) {
        inDtype = DT_BF16;
    }
    printf("%s - INFO - [XIR]: Using dtype index %ld\n", GetTime().c_str(), dtypeIndex);

    ret = CreateOppInGraph(inDtype, input, inputs, outputs, graph);
    if (ret != SUCCESS) {
        printf("%s - ERROR - [XIR]: Create ir session using build options failed\n", GetTime().c_str());
        ge::GEFinalize();
        return FAILED;
    }

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

    std::map<AscendString, AscendString> build_options = {

    };
    printf("%s - INFO - [XIR]: Start to create ir session using build options\n", GetTime().c_str());
    std::unique_ptr<ge::Session> session(new (std::nothrow) Session(build_options));
    if (!session) {
        printf("%s - ERROR - [XIR]: Create ir session using build options failed\n", GetTime().c_str());
        ge::GEFinalize();
        return FAILED;
    }
    printf("%s - INFO - [XIR]: Create ir session using build options success\n", GetTime().c_str());
    printf("%s - INFO - [XIR]: Start to add compute graph to ir session\n", GetTime().c_str());

    std::map<AscendString, AscendString> graph_options = {

    };
    uint32_t graph_id = 0;
    ret = session->AddGraph(graph_id, graph, graph_options);
    if (ret != SUCCESS) {
        ge::AscendString error_msg = ge::GEGetErrorMsgV2();
        std::string error_str(error_msg.GetString());
        printf("%s - ERROR - [XIR]: Session add ir compute graph to ir session failed, graph_id = %u, ret = %u, "
               "error message: %s\n",
               GetTime().c_str(), graph_id, static_cast<unsigned int>(ret), error_str.c_str());
        session.reset();
        ge::GEFinalize();
        return FAILED;
    }
    printf("%s - INFO - [XIR]: Session add ir compute graph to ir session success\n", GetTime().c_str());
    printf("%s - INFO - [XIR]: dump graph to txt\n", GetTime().c_str());
    std::string file_path = "./dump";
    aclgrphDumpGraph(graph, file_path.c_str(), file_path.length());
    printf("%s - INFO - [XIR]: Start to run ir compute graph\n", GetTime().c_str());
    std::vector<ge::Tensor> output;
    ret = session->RunGraph(graph_id, input, output);
    if (ret != SUCCESS) {
        printf("%s - INFO - [XIR]: Run graph failed\n", GetTime().c_str());
        session.reset();
        GEFinalize();
        return FAILED;
    }
    printf("%s - INFO - [XIR]: Session run ir compute graph success\n", GetTime().c_str());

    int input_num = input.size();
    for (int i = 0; i < input_num; i++) {
        std::cout << "input " << i << " dtype :  " << input[i].GetTensorDesc().GetDataType() << std::endl;
        string input_file = "./tc_ge_irrun_test_0008_npu_input_" + std::to_string(i) + ".bin";
        uint8_t* input_data_i = input[i].GetData();
        int64_t input_shape = input[i].GetTensorDesc().GetShape().GetShapeSize();
        std::cout << "this is " << i << "th input, input shape size =" << input_shape << std::endl;
        uint64_t data_size = input_shape * GetDataTypeSize(input[i].GetTensorDesc().GetDataType());
        if (WriteDataToFile((const char*)input_file.c_str(), data_size, input_data_i) != SUCCESS) {
            printf("%s - ERROR - [XIR]: Write input data to file %s failed\n", GetTime().c_str(), input_file.c_str());
            session.reset();
            ge::GEFinalize();
            return FAILED;
        }
    }

    int output_num = output.size();
    for (int i = 0; i < output_num; i++) {
        std::cout << "output " << i << " dtype :  " << output[i].GetTensorDesc().GetDataType() << std::endl;
        string output_file = "./tc_ge_irrun_test_0008_npu_output_" + std::to_string(i) + ".bin";
        uint8_t* output_data_i = output[i].GetData();
        int64_t output_shape = output[i].GetTensorDesc().GetShape().GetShapeSize();
        std::cout << "this is " << i << "th output, output shape size =" << output_shape << std::endl;
        uint64_t data_size = output_shape * GetDataTypeSize(output[i].GetTensorDesc().GetDataType());
        if (WriteDataToFile((const char*)output_file.c_str(), data_size, output_data_i) != SUCCESS) {
            printf("%s - ERROR - [XIR]: Write output data to file %s failed\n", GetTime().c_str(), output_file.c_str());
            session.reset();
            ge::GEFinalize();
            return FAILED;
        }
    }

    ge::AscendString error_msg = ge::GEGetErrorMsgV2();
    std::string error_str(error_msg.GetString());
    std::cout << "Error message: " << error_str << std::endl;
    ge::AscendString warning_msg = ge::GEGetWarningMsgV2();
    std::string warning_str(warning_msg.GetString());
    std::cout << "Warning message: " << warning_str << std::endl;
    printf("%s - INFO - [XIR]: Run graph success, input and output data have been written to bin files\n",
           GetTime().c_str());
    printf("%s - INFO - [XIR]: Start to finalize ir graph session\n", GetTime().c_str());
    session.reset();
    ret = ge::GEFinalize();
    if (ret != SUCCESS) {
        printf("%s - INFO - [XIR]: Finalize ir graph session failed\n", GetTime().c_str());
        return FAILED;
    }
    printf("%s - INFO - [XIR]: Finalize ir graph session success\n", GetTime().c_str());
    return SUCCESS;
}