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

/**
 * NOTE: Portions of this code were AI-generated and have been
 * technically reviewed for functional accuracy and security
 */

/*!
 * \file atan_grad_tiling.cpp
 * \brief AtanGrad Tiling 实现(arch35 / Ascend910B / Ascend950)
 *
 * Tiling 核心逻辑:
 *   1. 获取平台信息(coreNum, ubSize)
 *   2. 获取输入 shape 和 dtype
 *   3. 多核切分:blockFactor = CeilAlign(CeilDiv(totalNum, coreNum), ubBlockSize)
 *   4. 双缓冲决策:totalNum > MIN_SPLIT_THRESHOLD
 *   5. UB 切分:ubFactor = FloorAlign(ubSize / typeSize / bufferNum, ubBlockSize)
 *   6. 设置 blockDim、workspace=0
 *   7. 设置 TilingKey(ASCENDC_TPL_SEL_PARAM)
 */

#include "register/op_def_registry.h"
#include "op_common/log/log.h"
#include "op_common/op_host/util/math_util.h"
#include "op_common/op_host/util/platform_util.h"
#include "../op_kernel/atan_grad_tiling_data.h"
#include "../op_kernel/atan_grad_tiling_key.h"

namespace optiling {

using Ops::Base::CeilDiv;
using Ops::Base::CeilAlign;
using Ops::Base::FloorDiv;
using Ops::Base::FloorAlign;
using Ops::Base::GetUbBlockSize;

// 双缓冲触发阈值:元素数量超过此值时启用双缓冲
constexpr int64_t MIN_SPLIT_THRESHOLD = 1024;

static const gert::Shape g_vec_1_shape = {1};

static inline const gert::Shape EnsureNotScalar(const gert::Shape& in_shape)
{
    if (in_shape.GetDimNum() == 0) {
        return g_vec_1_shape;
    }
    return in_shape;
}

static ge::graphStatus GetPlatformInfo(gert::TilingContext* context, uint64_t& ubSize, int64_t& coreNum)
{
    fe::PlatFormInfos* platformInfoPtr = context->GetPlatformInfo();
    OP_CHECK_NULL_WITH_CONTEXT(context, platformInfoPtr);
    auto ascendcPlatform = platform_ascendc::PlatformAscendC(platformInfoPtr);
    coreNum = ascendcPlatform.GetCoreNumAiv();
    OP_CHECK_IF(coreNum == 0, OP_LOGE(context, "coreNum is 0"), return ge::GRAPH_FAILED);
    ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::UB, ubSize);
    OP_CHECK_IF(ubSize == 0, OP_LOGE(context, "ubSize is 0"), return ge::GRAPH_FAILED);
    return ge::GRAPH_SUCCESS;
}

static ge::graphStatus GetShapeAttrsInfo(
    gert::TilingContext* context, int64_t& totalNum, ge::DataType& dataType)
{
    auto inputX = context->GetInputShape(0);
    OP_CHECK_NULL_WITH_CONTEXT(context, inputX);
    auto inputShapeX = EnsureNotScalar(inputX->GetStorageShape());

    totalNum = inputShapeX.GetShapeSize();

    const std::set<ge::DataType> supportedDtype = {ge::DT_FLOAT16, ge::DT_FLOAT, ge::DT_BF16};
    auto inputDesc = context->GetInputDesc(0);
    OP_CHECK_NULL_WITH_CONTEXT(context, inputDesc);
    dataType = inputDesc->GetDataType();
    if (supportedDtype.count(dataType) == 0) {
        OP_LOGE(context, "AtanGrad: unsupported dtype %d", static_cast<int>(dataType));
        return ge::GRAPH_FAILED;
    }
    return ge::GRAPH_SUCCESS;
}

static ge::graphStatus SetWorkspace(gert::TilingContext* context)
{
    size_t* currentWorkspace = context->GetWorkspaceSizes(1);
    OP_CHECK_NULL_WITH_CONTEXT(context, currentWorkspace);
    currentWorkspace[0] = 0;  // 逐元素算子无需额外 workspace
    return ge::GRAPH_SUCCESS;
}

static ge::graphStatus AtanGradTilingFunc(gert::TilingContext* context)
{
    // 1. 获取平台信息
    uint64_t ubSize;
    int64_t  coreNum;
    OP_CHECK_IF(
        GetPlatformInfo(context, ubSize, coreNum) != ge::GRAPH_SUCCESS,
        OP_LOGE(context, "GetPlatformInfo error"), return ge::GRAPH_FAILED);

    // 2. 获取 shape / dtype
    int64_t     totalNum;
    ge::DataType dataType = ge::DT_FLOAT;
    OP_CHECK_IF(
        GetShapeAttrsInfo(context, totalNum, dataType) != ge::GRAPH_SUCCESS,
        OP_LOGE(context, "GetShapeAttrsInfo error"), return ge::GRAPH_FAILED);

    if (totalNum == 0) {
        context->SetBlockDim(0);
        return ge::GRAPH_FAILED;
    }
    // 3. 设置 workspace
    OP_CHECK_IF(
        SetWorkspace(context) != ge::GRAPH_SUCCESS,
        OP_LOGE(context, "SetWorkspace error"), return ge::GRAPH_FAILED);

    // 4. 填写 TilingData
    AtanGradTilingData* tiling = context->GetTilingData<AtanGradTilingData>();
    OP_CHECK_NULL_WITH_CONTEXT(context, tiling);
    OP_CHECK_IF(
        memset_s(tiling, sizeof(AtanGradTilingData), 0, sizeof(AtanGradTilingData)) != EOK,
        OP_LOGE(context, "memset tiling data error"), return ge::GRAPH_FAILED);

    // DMA 最小对齐粒度(32B / sizeof(T))
    int64_t ubBlockSize = Ops::Base::GetUbBlockSize(context);

    tiling->totalNum    = totalNum;
    tiling->blockFactor = CeilAlign(CeilDiv(totalNum, coreNum), ubBlockSize);
    int64_t usedCoreNum = CeilDiv(totalNum, tiling->blockFactor);

    // 5. 双缓冲决策
    uint64_t useDoubleBuffer = (totalNum > MIN_SPLIT_THRESHOLD) ? 1U : 0U;

    // 6. UB 切分
    int64_t typeSize;
    int64_t bufferNum;
    if (dataType == ge::DT_FLOAT) {
        typeSize = 4;
        bufferNum = useDoubleBuffer ? 7 : 4;
    } else {
        typeSize = 4;
        bufferNum = useDoubleBuffer ? 10 : 7;
    }

    tiling->ubFactor = FloorAlign(
        FloorDiv(static_cast<int64_t>(ubSize) / typeSize, bufferNum),
        ubBlockSize);

    // ubFactor 最小为 ubBlockSize(否则无法正常 CopyIn)
    if (tiling->ubFactor < ubBlockSize) {
        tiling->ubFactor = ubBlockSize;
    }

    context->SetBlockDim(usedCoreNum);

    // 7. 选择模板(dtype × BUFFER_MODE)
    uint32_t dTypeX = static_cast<uint32_t>(dataType);
    ASCENDC_TPL_SEL_PARAM(context, dTypeX, useDoubleBuffer);

    return ge::GRAPH_SUCCESS;
}

static ge::graphStatus TilingParseForAtanGrad([[maybe_unused]] gert::TilingParseContext* context)
{
    return ge::GRAPH_SUCCESS;
}

struct AtanGradCompileInfo {};

IMPL_OP_OPTILING(AtanGrad).Tiling(AtanGradTilingFunc).TilingParse<AtanGradCompileInfo>(TilingParseForAtanGrad);

} // namespace optiling