/*
 * 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 "topic_check.h"

#include <algorithm>
#include <map>
#include <set>
#include <string>
#include <string_view>
#include <tuple>
#include <utility>

namespace ibmw::cli::doctor {

namespace {
using discovery::EndpointRole;
using Name = std::pair<bool, std::string>; // true means a wire name
using Key = std::pair<Name, Name>;         // topic, type

constexpr std::string_view RPC_REPLY_PREFIX = "ibmw_rpc/rr/";
constexpr std::string_view RPC_REQUEST_PREFIX = "ibmw_rpc/rq/";

struct SourceTopics {
    std::map<Key, TopicCheckResult> groups;
    std::map<Key, std::set<std::string>> publisherParticipants;
    std::set<Name> unknownSubscriberTypes;
    std::map<Name, size_t> subscriberTotals;
    bool unnamedSubscriber = false;
    bool unnamedEndpoint = false;
};

void AddEndpoint(const discovery::DiscoveredEndpoint& endpoint, const discovery::DiscoverySourceStatus& source,
                 SourceTopics& topics)
{
    const Name topic{endpoint.topic_name.empty(),
                     endpoint.topic_name.empty() ? endpoint.wire_topic_name : endpoint.topic_name};
    const Name type{endpoint.type_name.empty(),
                    endpoint.type_name.empty() ? endpoint.wire_type_name : endpoint.type_name};
    if (topic.second.empty()) {
        topics.unnamedEndpoint = true;
        topics.unnamedSubscriber |= endpoint.role == EndpointRole::kSubscriber;
        return;
    }
    auto& group = topics.groups[{topic, type}];
    group.source = source.source;
    group.topic = topic.second;
    group.type = type.second;
    if (endpoint.role == EndpointRole::kPublisher) {
        ++group.publishers;
        topics.publisherParticipants[{topic, type}].insert(endpoint.participant_id);
    } else {
        ++group.subscribers;
        ++topics.subscriberTotals[topic];
        if (type.second.empty()) {
            topics.unknownSubscriberTypes.insert(topic);
        }
    }
}

SourceTopics CollectTopics(const discovery::DiscoverySnapshot& snapshot, const discovery::DiscoverySourceStatus& source,
                           bool includeHidden)
{
    SourceTopics topics;
    std::set<std::tuple<std::string, std::string, EndpointRole>> seen;
    for (const auto& endpoint : snapshot.endpoints) {
        if (endpoint.source != source.source || (endpoint.hidden && !includeHidden)) {
            continue;
        }
        if (!endpoint.endpoint_id.empty() &&
            !seen.emplace(endpoint.participant_id, endpoint.endpoint_id, endpoint.role).second) {
            continue;
        }
        AddEndpoint(endpoint, source, topics);
    }
    return topics;
}

bool HasRequestReader(const discovery::DiscoverySnapshot& snapshot, const discovery::DiscoverySourceStatus& source,
                      bool includeHidden, const std::string& participant, const std::string& requestTopic)
{
    auto isRequestReader = [&source, &includeHidden, &participant, &requestTopic](const auto& request) {
        return request.source == source.source && (!request.hidden || includeHidden) &&
               request.role == EndpointRole::kSubscriber && request.participant_id == participant &&
               (request.topic_name.empty() ? request.wire_topic_name : request.topic_name) == requestTopic;
    };
    return std::any_of(snapshot.endpoints.begin(), snapshot.endpoints.end(), isRequestReader);
}

// An RPC server's reply writer has readers only while clients exist.
// Every publisher in the group must have its own request reader;
// one healthy server must not hide a separate orphan reply writer.
bool IsIdleRpcReply(const discovery::DiscoverySnapshot& snapshot, const discovery::DiscoverySourceStatus& source,
                    bool includeHidden, const TopicCheckResult& group, const std::set<std::string>& participants)
{
    if (source.source.backend != discovery::DiscoveryBackend::kDds || !group.topic.starts_with(RPC_REPLY_PREFIX) ||
        group.type.empty()) {
        return false;
    }
    const auto requestTopic = std::string(RPC_REQUEST_PREFIX) + group.topic.substr(RPC_REPLY_PREFIX.size());
    auto hasReader = [&snapshot, &source, &includeHidden, &requestTopic](const auto& participant) {
        return !participant.empty() && HasRequestReader(snapshot, source, includeHidden, participant, requestTopic);
    };
    return std::all_of(participants.begin(), participants.end(), hasReader);
}

void ClassifyGroup(const discovery::DiscoverySnapshot& snapshot, const discovery::DiscoverySourceStatus& source,
                   bool includeHidden, const Key& key, TopicCheckResult& group, SourceTopics& topics)
{
    if (group.publishers == 0) {
        group.status = CheckStatus::kSkipped;
        group.message = "No publisher observed; subscriber-only topics are outside this check.";
    } else if ((key.second.second.empty() && topics.subscriberTotals[key.first] > 0) ||
               (group.subscribers == 0 &&
                (topics.unnamedSubscriber || topics.unknownSubscriberTypes.contains(key.first)))) {
        group.status = CheckStatus::kUnknown;
        group.message = "Incomplete endpoint metadata prevents determining subscriber presence.";
    } else if (group.subscribers == 0) {
        const bool idleRpcReply =
            IsIdleRpcReply(snapshot, source, includeHidden, group, topics.publisherParticipants.at(key));
        group.status = idleRpcReply ? CheckStatus::kSkipped : CheckStatus::kWarning;
        group.message = idleRpcReply ? "Idle RPC reply publisher has a request subscriber in the same participant; no "
                                       "active client is required."
                                     : "Publisher without subscriber observed in this source for this topic/type.";
    } else {
        group.status = CheckStatus::kOk;
        group.message = "Publisher and subscriber observed; QoS and delivery were not checked.";
    }
}

void CheckSourceTopics(std::vector<TopicCheckResult>& results, const discovery::DiscoverySnapshot& snapshot,
                       const discovery::DiscoverySourceStatus& source, bool includeHidden)
{
    auto topics = CollectTopics(snapshot, source, includeHidden);
    if (topics.unnamedEndpoint) {
        results.push_back({.source = source.source,
                           .status = CheckStatus::kUnknown,
                           .message = "An endpoint has no topic name; the check is incomplete."});
    }
    for (auto& [key, group] : topics.groups) {
        ClassifyGroup(snapshot, source, includeHidden, key, group, topics);
        results.push_back(std::move(group));
    }
    if (topics.groups.empty() && !topics.unnamedEndpoint) {
        results.push_back({.source = source.source,
                           .status = CheckStatus::kSkipped,
                           .message = "No visible topic endpoints observed in this source."});
    }
}
} // namespace

std::vector<TopicCheckResult> CheckTopics(const discovery::DiscoverySnapshot& snapshot, bool includeHidden)
{
    std::vector<TopicCheckResult> results;
    if (snapshot.sources.empty()) {
        results.push_back({.status = CheckStatus::kUnknown, .message = "No discovery source status was returned."});
        return results;
    }
    for (const auto& source : snapshot.sources) {
        if (source.status != discovery::DiscoveryStatus::kReady) {
            results.push_back({.source = source.source,
                               .status = CheckStatus::kUnknown,
                               .message = source.message.empty() ? "Discovery did not complete." : source.message});
            continue; // Partial/stale endpoints cannot establish an absent subscriber.
        }
        CheckSourceTopics(results, snapshot, source, includeHidden);
    }
    return results;
}

} // namespace ibmw::cli::doctor