/**
 * Copyright (c) 2025-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 "array_ops.h"
#include "ge_ir_build.h"

#include "../op_graph/real_proto.h"

#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;
    } else if (dt == ge::DT_FLOAT16 || dt == ge::DT_BF16 || dt == ge::DT_INT16 || dt == ge::DT_UINT16) {
        return 2;
    } else if (dt == ge::DT_INT32 || dt == ge::DT_UINT32) {
        return 4;
    } else if (dt == ge::DT_INT64 || dt == ge::DT_UINT64) {
        return 8;
    } else if (dt == ge::DT_INT8 || dt == ge::DT_UINT8) {
        return 1;
    } else if (dt == ge::DT_COMPLEX64) {
        return 8;  // complex64 = 2 * float32
    } else if (dt == ge::DT_COMPLEX128) {
        return 16; // complex128 = 2 * float64
    }
    return 1;
}

// Generate complex64 data: interleaved (real, imag) pairs of float
int32_t GenComplex64Data(
    vector<int64_t> shapes, Tensor& input_tensor, TensorDesc& input_tensor_desc, DataType data_type)
{
    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 * GetDataTypeSize(data_type);
    uint8_t* pData = new (std::nothrow) uint8_t[data_len];
    if (pData == nullptr) {
        return FAILED;
    }
    // For complex64: each element = (real:float32, imag:float32)
    // Fill real=index, imag=0.5*index for deterministic test
    float* pFloat = reinterpret_cast<float*>(pData);
    for (uint32_t i = 0; i < size; ++i) {
        pFloat[2 * i] = static_cast<float>(i + 1);          // real part
        pFloat[2 * i + 1] = static_cast<float>(i) * 0.5f;   // imag part
    }
    input_tensor = Tensor(input_tensor_desc, pData, data_len);
    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 op1 = op::Real("op1");

    // --- 输入定义: COMPLEX64, shape (16,8) ---
    std::vector<int64_t> xShape = {16, 8};
    auto placeholder1 = op::Data("placeholder1").set_attr_index(0);
    TensorDesc placeholder1_desc = TensorDesc(ge::Shape(xShape), FORMAT_ND, inDtype);
    placeholder1_desc.SetPlacement(ge::kPlacementHost);
    placeholder1_desc.SetFormat(FORMAT_ND);
    Tensor tensor_placeholder1;
    ret = GenComplex64Data(xShape, tensor_placeholder1, placeholder1_desc, inDtype);
    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);
    op1.set_input_input(placeholder1);
    inputs.push_back(placeholder1);

    // --- 输出定义: FLOAT (real part of complex64) ---
    std::vector<int64_t> outShape = {16, 8};
    TensorDesc output1_desc = TensorDesc(ge::Shape(outShape), FORMAT_ND, ge::DT_FLOAT);
    op1.update_output_desc_output(output1_desc);

    outputs.push_back(op1);
    return SUCCESS;
}

int main(int argc, char* argv[])
{
    const char* graph_name = "e2e_verify_real_geir_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 - ERROR - [XIR]: Initialize ge failed\n", GetTime().c_str());
        return FAILED;
    }
    printf("%s - INFO - [XIR]: Initialize ge success\n", GetTime().c_str());

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

    // Critical: use COMPLEX64 so RealTilingFunc is actually triggered
    DataType inDtype = ge::DT_COMPLEX64;

    ret = CreateOppInGraph(inDtype, input, inputs, outputs, graph);
    if (ret != SUCCESS) {
        printf("%s - ERROR - [XIR]: Create graph failed\n", GetTime().c_str());
        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 session\n", GetTime().c_str());
    ge::Session* session = new Session(build_options);
    if (session == nullptr) {
        printf("%s - ERROR - [XIR]: Create session failed\n", GetTime().c_str());
        return FAILED;
    }
    printf("%s - INFO - [XIR]: Create session success\n", GetTime().c_str());

    std::map<AscendString, AscendString> graph_options = {};
    uint32_t graph_id = 0;
    ret = session->AddGraph(graph_id, graph, graph_options);
    printf("%s - INFO - [XIR]: Add graph success\n", GetTime().c_str());

    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());
        ge::AscendString error_msg = ge::GEGetErrorMsgV2();
        std::string error_str(error_msg.GetString());
        std::cout << "Error message: " << error_str << std::endl;
        delete session;
        GEFinalize();
        return FAILED;
    }
    printf("%s - INFO - [XIR]: Run graph success\n", GetTime().c_str());

    int output_num = output.size();
    for (int i = 0; i < output_num; i++) {
        int64_t output_shape = output[i].GetTensorDesc().GetShape().GetShapeSize();
        std::cout << "output " << i << " shape size = " << output_shape
                  << ", dtype = " << output[i].GetTensorDesc().GetDataType() << std::endl;
        // Print first few values
        const uint8_t* data = output[i].GetData();
        if (data != nullptr) {
            const float* fdata = reinterpret_cast<const float*>(data);
            std::cout << "  first 8 values: ";
            for (int j = 0; j < std::min((int64_t)8, output_shape); j++) {
                std::cout << fdata[j] << " ";
            }
            std::cout << std::endl;
        }
    }

    printf("%s - INFO - [XIR]: GE IR pathway verification PASSED\n", GetTime().c_str());

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