// Copyright (C) 2018-2026 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//

#include "transformations/op_conversions/hard_sigmoid_decomposition.hpp"

#include <memory>

#include "itt.hpp"
#include "openvino/core/graph_util.hpp"
#include "openvino/core/rt_info.hpp"
#include "openvino/op/add.hpp"
#include "openvino/op/constant.hpp"
#include "openvino/op/hard_sigmoid.hpp"
#include "openvino/op/maximum.hpp"
#include "openvino/op/minimum.hpp"
#include "openvino/op/multiply.hpp"
#include "openvino/pass/pattern/op/wrap_type.hpp"

using ov::pass::pattern::Matcher;

namespace v0 = ov::op::v0;
namespace v1 = ov::op::v1;
ov::pass::HardSigmoidDecomposition::HardSigmoidDecomposition() {
    MATCHER_SCOPE(HardSigmoidDecomposition);
    // Decomposes HardSigmoid(x) op into sub-graph max(0, min(1, alpha * x + beta))
    auto hard_sigmoid = ov::pass::pattern::wrap_type<v0::HardSigmoid>();

    matcher_pass_callback callback = [OV_CAPTURE_CPY_AND_THIS](Matcher& m) {
        auto& pattern_to_output = m.get_pattern_value_map();
        auto hard_sigmoid_node = pattern_to_output.at(hard_sigmoid).get_node_shared_ptr();

        if (transformation_callback(hard_sigmoid_node)) {
            return false;
        }

        auto alpha_constant = hard_sigmoid_node->input_value(1);
        auto multiply = std::make_shared<v1::Multiply>(hard_sigmoid_node->input_value(0), alpha_constant);

        auto betta_constant = hard_sigmoid_node->input_value(2);
        auto add = std::make_shared<v1::Add>(multiply, betta_constant);

        auto input_type = hard_sigmoid_node->input_value(0).get_element_type();
        auto min_constant = v0::Constant::create(input_type, ov::Shape{}, {1.f});
        auto min = std::make_shared<v1::Minimum>(add, min_constant);

        auto max_constant = v0::Constant::create(input_type, ov::Shape{}, {0.0});
        auto max = std::make_shared<v1::Maximum>(min, max_constant);

        max->set_friendly_name(m.get_match_root()->get_friendly_name());
        ov::copy_runtime_info(hard_sigmoid_node,
                              {alpha_constant.get_node_shared_ptr(),
                               multiply,
                               betta_constant.get_node_shared_ptr(),
                               add,
                               min_constant,
                               min,
                               max_constant,
                               max});
        ov::replace_node(m.get_match_root(), max);
        return true;
    };

    auto m = std::make_shared<Matcher>(hard_sigmoid, matcher_name);
    register_matcher(m, callback);
}
