/**
 * 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 <cstdlib>
#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 "experiment_ops.h"
#include "nn_other.h"
#include "../op_graph/kl_div_proto.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;
    bool shape_ok;
    int output_count;
    std::string err_msg;
};

// ====== 以下三个宏定义必须原样复用,禁止重写、禁止改签名、禁止删行 ======
// ADD_INPUT_MODE 内部封装了三个关键逻辑,重写会丢失:
//   1. S/D 双 desc 分离:_desc_graph(D 模式含 -1,给图引擎做 infershape)和 _desc_real(具体值,给 GenOnesData 构造
//   Tensor)
//   2. #intputIndex 字符串化:生成 "placeholder1" 等合法 op 名(用 + 会变成指针算术)
//   3. update_output_desc_y:Data op 需要同时设置 input 和 output desc
// 多输入依赖算子只需在宏调用处传入各输入的 shape,无需修改宏定义。
#define ADD_INPUT_MODE(intputIndex, intputName, intputDtype, inputShape, mode)                                       \
    vector<int64_t> placeholder##intputIndex##_real_shape = inputShape;                                              \
    vector<int64_t> placeholder##intputIndex##_graph_shape = ((mode) == RUN_MODE_D) ?                                \
                                                                 vector<int64_t>(                                    \
                                                                     placeholder##intputIndex##_real_shape.size(),   \
                                                                     -1) :                                           \
                                                                 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;                                                                          \
    ret = GenOnesData(placeholder##intputIndex##_real_shape, tensor_placeholder##intputIndex,                        \
                      placeholder##intputIndex##_desc_real, 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_graph);                             \
    placeholder##intputIndex.update_output_desc_y(placeholder##intputIndex##_desc_graph);                            \
    input.push_back(tensor_placeholder##intputIndex);                                                                \
    graph.AddOp(placeholder##intputIndex);                                                                           \
    klDiv1.set_input_##intputName(placeholder##intputIndex);                                                         \
    inputs.push_back(placeholder##intputIndex);

#define ADD_CONST_INPUT(intputIndex, intputName, intputDtype, inputShape)                                           \
    vector<int64_t> placeholder##intputIndex##_shape = inputShape;                                                  \
    auto placeholder##intputIndex = op::Const("placeholder" #intputIndex);                                          \
    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.SetAttr("value", tensor_placeholder##intputIndex);                                     \
    placeholder##intputIndex.update_output_desc_y(placeholder##intputIndex##_desc);                                 \
    graph.AddOp(placeholder##intputIndex);                                                                          \
    klDiv1.set_input_##intputName(placeholder##intputIndex);                                                        \
    klDiv1.update_input_desc_##intputName(placeholder##intputIndex##_desc);                                         \
    inputs.push_back(placeholder##intputIndex);

// ADD_OUTPUT_MODE 内部封装了 S/D 模式 graph_shape 自动生成(D 模式含 -1),禁止重写。
#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);                                            \
    klDiv1.update_output_desc_##outputName(outputName##outputIndex##_desc);

// KLDiv 壳算子属性设置:reduction 为 REQUIRED_ATTR(String),必须显式设置;
// 原型无 log_target 属性(恒按 log_target=False 语义计算,禁止设置该属性)
#define ADD_INPUT_ATTR(attrName, attrValue) klDiv1.set_attr_##attrName(attrValue)

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 oneByte = 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 = oneByte;
    }
    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];
    }
    uint32_t data_len = size * GetDataTypeSize(data_type);
    int32_t* pData = new (std::nothrow) int32_t[size];
    if (pData == nullptr) {
        printf("%s - ERROR - [XIR]: GenOnesData alloc failed\n", GetTime().c_str());
        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);
    delete[] pData;
    return SUCCESS;
}

int CreateOppInGraph(RunMode mode, DataType inDtype, const std::vector<int64_t>& xShape, const std::string& reduction,
                     std::vector<ge::Tensor>& input, std::vector<Operator>& inputs, std::vector<Operator>& outputs,
                     Graph& graph)
{
    Status ret = SUCCESS;
    // 自定义代码:添加单算子定义到图中
    auto klDiv1 = op::KLDiv("kl_div");
    // x 与 target 同 shape 同 dtype:x 按 Data 输入构造,target 按 Const 输入构造(值嵌入图中)
    ADD_INPUT_MODE(1, x, inDtype, xShape, mode);
    ADD_CONST_INPUT(2, target, inDtype, xShape);
    // 输出 shape:reduction="none" 时 y 与 x 同 shape;mean/sum/batchmean 时 y 为标量(0 维)
    vector<int64_t> yShape = (reduction == "none") ? xShape : vector<int64_t>{};
    ADD_OUTPUT_MODE(1, y, inDtype, yShape, mode);
    // reduction 为 String 类型 REQUIRED 属性,必须显式设置,取值 none/mean/sum/batchmean
    ADD_INPUT_ATTR(reduction, reduction.c_str());

    outputs.push_back(klDiv1);
    // 添加完毕
    return SUCCESS;
}

CaseResult RunOneCase(ge::Session* session, uint32_t graph_id, RunMode mode, DataType dtype,
                      const std::vector<int64_t>& shape, const std::string& reduction, 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.shape_ok = 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, shape, reduction, 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);
    Status removeRet = session->RemoveGraph(graph_id);
    if (removeRet != SUCCESS) {
        printf("%s - WARN - [XIR]: RemoveGraph failed, ret=%s\n", GetTime().c_str(), std::to_string(removeRet).c_str());
    }
    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);

    // 输出 shape 冒烟校验(按维度语义比对,与壳 infershape 推导规则一致):
    //   reduction="none":输出与输入同维数且逐维相等(空 tensor 输出空,维度含 0);
    //   mean/sum/batchmean:输出为标量(0 维 tensor,GetDimNum()==0)。
    // 注:GE 框架对 0 维标量 shape 的 GetShapeSize() 返回 0(非数学空乘积 1),
    //     故标量场景按维度数校验,不能按元素数校验。
    r.shape_ok = true;
    for (size_t i = 0; i < output.size(); i++) {
        const ge::Shape outShape = output[i].GetTensorDesc().GetShape();
        bool dimOk = true;
        if (reduction == "none") {
            if (static_cast<size_t>(outShape.GetDimNum()) != shape.size()) {
                dimOk = false;
            } else {
                for (size_t d = 0; d < shape.size(); d++) {
                    if (outShape.GetDim(d) != shape[d]) {
                        dimOk = false;
                        break;
                    }
                }
            }
        } else {
            dimOk = (outShape.GetDimNum() == 0);
        }
        printf("  [%s] output[%zu] dtype=%d dim_num=%lld reduction=%s check=%s\n", case_name.c_str(), i,
               output[i].GetTensorDesc().GetDataType(), (long long)outShape.GetDimNum(), reduction.c_str(),
               dimOk ? "OK" : "FAIL");
        if (!dimOk) {
            r.shape_ok = false;
        }
    }

    return r;
}

void PrintReport(const std::vector<CaseResult>& results)
{
    printf("\n");
    printf("==========================================================================================================="
           "=\n");
    printf("| %-22s | %-8s | %-9s | %-12s | %-7s | %-7s | %-20s\n", "Case", "Build", "RunGraph", "OutputExists",
           "Shape", "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 && r.shape_ok;
        if (pass)
            pass_cnt++;
        printf("| %-22s | %-8s | %-9s | %-12s | %-7s | %-7d | %-20s\n", r.case_name.c_str(), r.build_ok ? "OK" : "FAIL",
               r.run_ok ? "OK" : "FAIL", r.output_exists ? "OK" : "FAIL", r.shape_ok ? "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);
}

std::string GetDeviceId()
{
    const char* env = std::getenv("ASCEND_DEVICE_ID");
    if (env != nullptr && strlen(env) > 0) {
        return std::string(env);
    }
    printf("%s - WARN - [XIR]: ASCEND_DEVICE_ID not set, fallback to 0\n", GetTime().c_str());
    return "0";
}

int main(int argc, char* argv[])
{
    std::string device_id = GetDeviceId();

    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", device_id.c_str()},
                                                           {"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 矩阵:DT_DOUBLE 为纸面声明(tiling 阶段 dtype 白名单拒绝),不纳入测试
    struct DtypeEntry {
        DataType dt;
        std::string name;
    };
    std::vector<DtypeEntry> dtype_list = {
        {DT_FLOAT, "FP32"},
        {DT_FLOAT16, "FP16"},
        {DT_BF16, "BF16"},
    };

    // shape 场景矩阵(x 与 target 同 shape;空 tensor 场景输出为空/标量短路值)
    struct ShapeEntry {
        std::vector<int64_t> shape;
        std::string name;
    };
    std::vector<ShapeEntry> shape_list = {
        {{32, 100}, "regular"},
        {{1024}, "1d"},
        {{0, 8}, "empty"},
    };

    // reduction 场景:REQUIRED 属性须显式设置;none 输出与 x 同 shape,sum/mean 输出标量;
    // none/sum 走 SumLogFalse DAG,mean 走 MeanLogFalse DAG,覆盖壳 kernel 两条转发路径
    std::vector<std::string> reduction_list = {"none", "sum", "mean"};

    // 单 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_reduction × N_dtype × N_shape × 2 mode 全矩阵
    for (const auto& red : reduction_list) {
        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 = red + "_" + 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.shape, red, 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 || !r.shape_ok) {
            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;
}