/**
 * 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 <cstddef>
#include <cstdint>
#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/ball_query_proto.h"
#include "nn_other.h"

#define FAILED -1
#define SUCCESS 0

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

enum RunMode { RUN_MODE_S = 0, RUN_MODE_D = 1 };

struct CaseResult {
    std::string case_name;
    bool build_ok;
    bool run_ok;
    bool output_exists;
    int output_count;
    std::string err_msg;
};

// 多输入 shape 组合:ball_query 的 xyz 与 center_xyz 形状不同且存在依赖关系,不能共用单个 xShape。
// 布局约束:
//   xyz.shape        = (B, 3, N),中间维必须为 3(坐标在中间维)
//   center_xyz.shape = (M, B, 3),最后一维必须为 3
//   xyz.shape[0] == center_xyz.shape[1](B 维一致)
//   输出 idx.shape   = (M, B, sample_num),dtype 固定 int32
// sample_num/min_radius/max_radius 既是属性也随场景变化。
struct ShapeCombo {
    std::vector<int64_t> xyz_shape;        // (B, 3, N)
    std::vector<int64_t> center_xyz_shape; // (M, B, 3)
    int64_t sample_num;
    float min_radius;
    float max_radius;
    std::string name;
};

// ADD_INPUT_MODE:新增 inputDShape 参数,用于显式指定 D 模式 graph shape。
// ball_query 的 InferShape 校验 xyz.dim(1)==3 与 center_xyz.dim(2)==3(坐标维),
// 若 D 模式把所有维都置 -1,会触发坐标维校验失败。因此 D 模式需保留坐标维已知(=3),
// 仅把动态维(B/M/N)置 -1。S 模式直接用 real shape。
#define ADD_INPUT_MODE(intputIndex, intputName, intputDtype, inputRealShape, inputDShape, mode)                      \
    vector<int64_t> placeholder##intputIndex##_real_shape = inputRealShape;                                          \
    vector<int64_t> placeholder##intputIndex##_graph_shape = ((mode) == RUN_MODE_D) ?                                \
                                                                 vector<int64_t>(inputDShape) :                      \
                                                                 placeholder##intputIndex##_real_shape;              \
    auto placeholder##intputIndex = op::Data("placeholder" #intputIndex).set_attr_index(0);                          \
    TensorDesc placeholder##intputIndex##_desc_graph = TensorDesc(ge::Shape(placeholder##intputIndex##_graph_shape), \
                                                                  FORMAT_ND, intputDtype);                           \
    placeholder##intputIndex##_desc_graph.SetPlacement(ge::kPlacementHost);                                          \
    placeholder##intputIndex##_desc_graph.SetFormat(FORMAT_ND);                                                      \
    TensorDesc placeholder##intputIndex##_desc_real = TensorDesc(ge::Shape(placeholder##intputIndex##_real_shape),   \
                                                                 FORMAT_ND, intputDtype);                            \
    placeholder##intputIndex##_desc_real.SetPlacement(ge::kPlacementHost);                                           \
    placeholder##intputIndex##_desc_real.SetFormat(FORMAT_ND);                                                       \
    placeholder##intputIndex##_desc_real.SetRealDimCnt(placeholder##intputIndex##_real_shape.size());                \
    Tensor tensor_placeholder##intputIndex;                                                                          \
    if (intputDtype == DT_FLOAT) {                                                                                   \
        ret = GenOnesData<float>(placeholder##intputIndex##_real_shape, tensor_placeholder##intputIndex,             \
                                 placeholder##intputIndex##_desc_real, 2.0f);                                        \
    } else if (intputDtype == DT_FLOAT16) {                                                                          \
        ret = GenOnesData<uint16_t>(placeholder##intputIndex##_real_shape, tensor_placeholder##intputIndex,          \
                                    placeholder##intputIndex##_desc_real, FloatToFloat16Bits(2.0f));                 \
    } else {                                                                                                         \
        ret = GenOnesData<int32_t>(placeholder##intputIndex##_real_shape, tensor_placeholder##intputIndex,           \
                                   placeholder##intputIndex##_desc_real, 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_graph);                             \
    placeholder##intputIndex.update_output_desc_y(placeholder##intputIndex##_desc_graph);                            \
    input.push_back(tensor_placeholder##intputIndex);                                                                \
    graph.AddOp(placeholder##intputIndex);                                                                           \
    ball1.set_input_##intputName(placeholder##intputIndex);                                                          \
    inputs.push_back(placeholder##intputIndex);

#define ADD_OUTPUT_MODE(outputIndex, outputName, outputDtype, outputShape, mode)                                    \
    vector<int64_t> output##outputIndex##_graph_shape = ((mode) == RUN_MODE_D) ?                                    \
                                                            vector<int64_t>(outputShape.size(), -1) :               \
                                                            outputShape;                                            \
    TensorDesc outputName##outputIndex##_desc = TensorDesc(ge::Shape(output##outputIndex##_graph_shape), FORMAT_ND, \
                                                           outputDtype);                                            \
    ball1.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;
}

// 将 float 转为 IEEE 754 half (binary16) 位模式,就近偶数舍入;供 FP16 输入数据生成使用。
static uint16_t FloatToFloat16Bits(float f)
{
    uint32_t u;
    memcpy(&u, &f, sizeof(u));
    uint16_t sign = static_cast<uint16_t>((u >> 16) & 0x8000u);
    uint32_t fexp = (u >> 23) & 0xffu;
    int32_t exp = static_cast<int32_t>(fexp) - 127;
    uint32_t frac = u & 0x7fffffu;
    if (fexp == 0xffu) {
        return sign | (frac ? 0x7e00u : 0x7c00u); // 输入为 NaN / Inf
    }
    if (exp >= 16) {
        return sign | 0x7c00u; // 有限值溢出 -> Inf
    }
    if (exp >= -14) {
        uint32_t mant = frac >> 13;
        bool roundUp = ((frac >> 12) & 1u) && (((frac & 0xfffu) != 0u) || (mant & 1u));
        uint16_t h = sign | static_cast<uint16_t>((exp + 15) << 10) | static_cast<uint16_t>(mant);
        if (roundUp) {
            h += 1u;
        }
        return h;
    }
    if (exp >= -24) {
        uint32_t m = frac | 0x800000u;
        int32_t shift = -exp - 1;
        uint32_t mant = m >> shift;
        bool roundUp = ((m >> (shift - 1)) & 1u) && (((m & ((1u << (shift - 1)) - 1u)) != 0u) || (mant & 1u));
        uint16_t h = sign | static_cast<uint16_t>(mant);
        if (roundUp) {
            h += 1u;
        }
        return h;
    }
    return sign; // underflow -> 0
}

// 按 T 的实际宽度分配 size 个元素并统一填充 value,字节数 data_len = size * sizeof(T),
// 保证 Tensor 收到的长度与 dtype 严格匹配。调用方需保证 T 的宽度与 TensorDesc 中 data_type 的宽度一致。
template <typename T>
int32_t GenOnesData(vector<int64_t> shapes, Tensor& input_tensor, TensorDesc& input_tensor_desc, T 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 * sizeof(T);
    T* pData = new (std::nothrow) T[size];
    if (pData == nullptr) {
        return FAILED;
    }
    for (size_t i = 0; i < size; ++i) {
        *(pData + i) = value;
    }
    input_tensor = Tensor(input_tensor_desc, reinterpret_cast<uint8_t*>(pData), data_len);
    return SUCCESS;
}

int CreateOppInGraph(RunMode mode, DataType inDtype, const std::vector<int64_t>& xyzShape,
                     const std::vector<int64_t>& centerXyzShape, int64_t sampleNum, float minRadius, float maxRadius,
                     std::vector<ge::Tensor>& input, std::vector<Operator>& inputs, std::vector<Operator>& outputs,
                     Graph& graph)
{
    Status ret = SUCCESS;
    // 添加单算子定义到图中
    auto ball1 = op::BallQuery("ball1");

    // D 模式 graph shape:保留坐标维已知(=3),动态维(B/M/N)置 -1。
    //   xyz        (B, 3, N) -> D shape {-1, 3, -1}
    //   center_xyz (M, B, 3) -> D shape {-1, -1, 3}
    std::vector<int64_t> xyzDShape = {-1, 3, -1};       // (B, 3, N)
    std::vector<int64_t> centerXyzDShape = {-1, -1, 3}; // (M, B, 3)

    // 输入:xyz(B,3,N) 与 center_xyz(M,B,3)
    ADD_INPUT_MODE(1, xyz, inDtype, xyzShape, xyzDShape, mode);
    ADD_INPUT_MODE(2, center_xyz, inDtype, centerXyzShape, centerXyzDShape, mode);

    // 输出:idx(M,B,sample_num),dtype 固定 INT32
    std::vector<int64_t> idxShape = {centerXyzShape[0], centerXyzShape[1], sampleNum};
    ADD_OUTPUT_MODE(1, idx, DT_INT32, idxShape, mode);

    // 属性设置:min_radius -> max_radius -> sample_num
    ball1.set_attr_min_radius(minRadius); // Float  -> float
    ball1.set_attr_max_radius(maxRadius); // Float  -> float
    ball1.set_attr_sample_num(sampleNum); // Int    -> int64_t

    outputs.push_back(ball1);
    return SUCCESS;
}

CaseResult RunOneCase(ge::Session* session, uint32_t graph_id, RunMode mode, DataType dtype, const ShapeCombo& combo,
                      const std::string& case_name)
{
    CaseResult r;
    r.case_name = case_name;
    r.build_ok = false;
    r.run_ok = false;
    r.output_exists = false;
    r.output_count = 0;
    r.err_msg = "";

    std::string graph_name = "tc_ge_irrun_test_" + std::to_string(graph_id);
    Graph graph(graph_name.c_str());
    std::vector<ge::Tensor> input;
    std::vector<Operator> inputs{};
    std::vector<Operator> outputs{};

    Status ret = CreateOppInGraph(mode, dtype, combo.xyz_shape, combo.center_xyz_shape, combo.sample_num,
                                  combo.min_radius, combo.max_radius, input, inputs, outputs, graph);
    if (ret != SUCCESS) {
        r.err_msg = "CreateOppInGraph failed";
        return r;
    }
    if (!inputs.empty() && !outputs.empty()) {
        graph.SetInputs(inputs).SetOutputs(outputs);
    }

    std::map<AscendString, AscendString> graph_options = {};
    ret = session->AddGraph(graph_id, graph, graph_options);
    if (ret != SUCCESS) {
        r.err_msg = "AddGraph failed, ret=" + std::to_string(ret);
        return r;
    }
    r.build_ok = true;

    std::vector<ge::Tensor> output;
    ret = session->RunGraph(graph_id, input, output);
    session->RemoveGraph(graph_id);
    if (ret != SUCCESS) {
        r.err_msg = "RunGraph failed, ret=" + std::to_string(ret);
        return r;
    }
    r.run_ok = true;
    r.output_count = output.size();
    r.output_exists = (output.size() > 0);

    for (size_t i = 0; i < output.size(); i++) {
        int64_t shape_size = output[i].GetTensorDesc().GetShape().GetShapeSize();
        printf("  [%s] output[%zu] dtype=%d shape_size=%lld\n", case_name.c_str(), i,
               output[i].GetTensorDesc().GetDataType(), (long long)shape_size);
    }

    return r;
}

void PrintReport(const std::vector<CaseResult>& results)
{
    printf("\n");
    printf("====================================================================================================\n");
    printf("| %-22s | %-8s | %-9s | %-12s | %-7s | %-20s\n", "Case", "Build", "RunGraph", "OutputExists", "OutCnt",
           "ErrMsg");
    printf("----------------------------------------------------------------------------------------------------\n");
    int pass_cnt = 0;
    int total = results.size();
    for (const auto& r : results) {
        bool pass = r.build_ok && r.run_ok && r.output_exists;
        if (pass)
            pass_cnt++;
        printf("| %-22s | %-8s | %-9s | %-12s | %-7d | %-20s\n", r.case_name.c_str(), r.build_ok ? "OK" : "FAIL",
               r.run_ok ? "OK" : "FAIL", r.output_exists ? "OK" : "FAIL", r.output_count,
               r.err_msg.empty() ? "-" : r.err_msg.c_str());
    }
    printf("====================================================================================================\n");
    printf("Summary: %d/%d passed\n", pass_cnt, total);
}

int main(int argc, char* argv[])
{
    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"}, // 应通过 `npu-smi info` 查询状态为 OK 的 device id
        {"ge.graphRunMode", "0"},
        {"ge.exec.precision_mode", "must_keep_origin_dtype"}};
    // 初始化图引擎
    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());

    // dtype 矩阵:ball_query 的 xyz/center_xyz 支持 float32/float16(idx 固定 int32)
    struct DtypeEntry {
        DataType dt;
        std::string name;
    };
    std::vector<DtypeEntry> dtype_list = {
        {DT_FLOAT, "FP32"},
        {DT_FLOAT16, "FP16"},
    };

    // shape 场景矩阵:ball_query 固定 3D(xyz=(B,3,N)、center_xyz=(M,B,3))。
    // 算子仅支持 3D 输入,保留常规 3D / 小规模 3D / 空点(N=0) / 空查询(M=0) / 多 batch 共 5 类场景。
    std::vector<ShapeCombo> shape_list = {
        {{2, 3, 1024}, {512, 2, 3}, 16, 0.1f, 0.2f, "regular3d"},
        {{1, 3, 64}, {16, 1, 3}, 8, 0.1f, 0.2f, "small3d"},
        {{1, 3, 0}, {16, 1, 3}, 8, 0.1f, 0.2f, "empty_xyz"},
        {{1, 3, 64}, {0, 1, 3}, 8, 0.1f, 0.2f, "empty_center"},
        {{4, 3, 256}, {128, 4, 3}, 16, 0.1f, 0.2f, "multibatch"},
    };

    // 单 session 复用
    std::map<AscendString, AscendString> build_options = {};
    ge::Session* session = new Session(build_options);
    if (session == nullptr) {
        printf("%s - ERROR - [XIR]: create session failed\n", GetTime().c_str());
        ge::GEFinalize();
        return FAILED;
    }

    std::vector<CaseResult> results;
    uint32_t graph_id = 0;

    // N_dtype × N_shape × (S + D) 全矩阵。S 模式用 real shape,D 模式用部分 -1(坐标维已知)。
    for (const auto& d : dtype_list) {
        for (const auto& s : shape_list) {
            for (auto mode : {RUN_MODE_S, RUN_MODE_D}) {
                std::string mode_name = (mode == RUN_MODE_S) ? "S" : "D";
                std::string case_name = d.name + "_" + s.name + "_" + mode_name;
                printf("\n%s - INFO - [XIR]: ===== %s =====\n", GetTime().c_str(), case_name.c_str());
                CaseResult r = RunOneCase(session, graph_id, mode, d.dt, s, case_name);
                results.push_back(r);
                graph_id++;
            }
        }
    }

    PrintReport(results);

    bool all_pass = true;
    for (const auto& r : results) {
        if (!r.build_ok || !r.run_ok || !r.output_exists) {
            all_pass = false;
        }
    }
    if (all_pass) {
        printf("\n%s - INFO - [XIR]: ALL CASES PASSED\n", GetTime().c_str());
    } else {
        printf("\n%s - ERROR - [XIR]: SOME CASES FAILED, see report above\n", GetTime().c_str());
    }

    delete session;
    printf("%s - INFO - [XIR]: Start to finalize ir graph session\n", GetTime().c_str());
    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 all_pass ? SUCCESS : FAILED;
}