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

#include <algorithm>
#include <iostream>
#include <string>
#include <utility>
#include <vector>

#include "discovery_options.h"
#include "discovery_query.h"

namespace ibmw::cli::topic {
namespace {

using ibmw::cli::Invocation;
using ibmw::discovery::DiscoveredEndpoint;
using ibmw::discovery::DiscoverySnapshot;
using ibmw::discovery::DiscoveryStatus;
using ibmw::discovery::EndpointRole;

int RunTopicFindCommandImpl(const Invocation& invocation)
{
    const std::string requestedType = invocation.positionalArgs.front();
    const bool includeHiddenTopics = invocation.HasOption("--include-hidden-topics");
    const auto graph = DiscoverTopics(invocation);
    std::vector<std::string> matchingTopics;
    for (const auto& topicName : VisibleTopicNames(graph, includeHiddenTopics)) {
        const auto advertisements = VisibleEndpoints(graph, topicName, includeHiddenTopics);
        const bool matches = std::any_of(
            advertisements.begin(), advertisements.end(),
            [&requestedType](const auto& advertisement) { return TypeName(advertisement) == requestedType; });
        if (matches) {
            matchingTopics.emplace_back(topicName);
        }
    }

    if (invocation.HasOption("--count-topics")) {
        std::cout << matchingTopics.size() << '\n';
        return graph.Succeeded() ? 0 : 1;
    }
    for (const auto& topicName : matchingTopics) {
        std::cout << topicName << '\n';
    }
    return graph.Succeeded() ? 0 : 1;
}

} // namespace

void AddFindCommand(Command& topic)
{
    auto& find = topic.AddSubcommand("find", "Find topics by message type");
    find.SetHandler(RunTopicFindCommandImpl);
    find.AddArgument("<type>", "Message type");
    find.AddOption("--count-topics", "-c", {}, "Only display the number of topics");
    find.AddOption("--include-hidden-topics", {}, {}, "Consider hidden topics as well");
    AddDiscoveryOptions(find);
}

} // namespace ibmw::cli::topic