/*
 * Copyright (c) 2025-2026 IB-Robot Group & openEuler Embedded SIG & openharmony-robot sig_RoboFrame.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "message_text.h"

#include <cmath>
#include <stdexcept>

namespace ibmw::cli::topic {
namespace {
Json ScalarFromYaml(const YAML::Node& node)
{
    const auto text = node.Scalar();
    // yaml-cpp marks quoted strings with '!'; preserve strings such as "true"
    // and "123" when converting YAML to JSON or emitting YAML again.
    if (node.Tag() == "!" || node.Tag() == "tag:yaml.org,2002:str") {
        return text;
    }
    bool boolean;
    int64_t integer;
    uint64_t unsignedInteger;
    double number;
    if (YAML::convert<bool>::decode(node, boolean)) {
        return boolean;
    }
    if (YAML::convert<int64_t>::decode(node, integer)) {
        return integer;
    }
    if (YAML::convert<uint64_t>::decode(node, unsignedInteger)) {
        return unsignedInteger;
    }
    if (YAML::convert<double>::decode(node, number)) {
        if (!std::isfinite(number)) {
            throw std::runtime_error("Cannot represent non-finite YAML numbers as JSON.");
        }
        return number;
    }
    return text;
}
} // namespace

Json FromYaml(const YAML::Node& node, size_t depth)
{
    if (depth > MAX_MESSAGE_YAML_DEPTH) {
        throw std::runtime_error("Message YAML nesting is too deep or contains a cyclic alias.");
    }
    if (node.IsNull()) {
        return nullptr;
    }
    if (node.IsSequence()) {
        auto value = Json::array();
        for (const auto& item : node) {
            value.push_back(FromYaml(item, depth + 1));
        }
        return value;
    }
    if (node.IsMap()) {
        auto value = Json::object();
        for (const auto& item : node) {
            if (!item.first.IsScalar()) {
                throw std::runtime_error("Message requires scalar YAML map keys.");
            }
            const auto key = item.first.Scalar();
            if (value.contains(key)) {
                throw std::runtime_error("Duplicate message YAML key: " + key);
            }
            value[key] = FromYaml(item.second, depth + 1);
        }
        return value;
    }
    return ScalarFromYaml(node);
}

} // namespace ibmw::cli::topic