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

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

#include "engine/runtime_graph/runtime_registry.h"

namespace ibmw::cli::module {
namespace {

using runtime::core::runtime_graph::RuntimeRegistration;

void PrintTopics(const RuntimeRegistration& runtime, const std::string& moduleName, bool published)
{
    // Report interfaces, not endpoint counts: repeated registrations with the
    // same topic and type appear once, while different types remain distinct.
    std::set<std::pair<std::string, std::string>> topics;
    for (const auto& endpoint : runtime.topics) {
        if (endpoint.module_name == moduleName && endpoint.published == published) {
            topics.emplace(endpoint.topic.topic, endpoint.topic.msg_type);
        }
    }
    std::cout << (published ? "Publishers:\n" : "Subscribers:\n");
    if (topics.empty()) {
        std::cout << "  (none)\n";
    }
    for (const auto& [topic, type] : topics) {
        std::cout << "  " << topic << " [" << type << "]\n";
    }
}

struct RuntimeMatches {
    std::vector<const RuntimeRegistration*> runtimes;
    bool foundRuntime = false;
    bool complete = true;
};

RuntimeMatches FindModuleRuntimes(const std::vector<RuntimeRegistration>& runtimes, const std::string& selected,
                                  const std::string& moduleName)
{
    RuntimeMatches result{.foundRuntime = selected.empty()};
    for (const auto& runtime : runtimes) {
        if (!selected.empty() && runtime.runtime_id != selected) {
            continue;
        }
        result.foundRuntime = true;
        if (!runtime.modules) {
            std::cerr << "ibmw module: runtime '" << runtime.runtime_id;
            std::cerr << "' does not advertise module information; upgrade and restart it.\n";
            result.complete = false;
            continue;
        }
        if (std::find(runtime.modules->begin(), runtime.modules->end(), moduleName) != runtime.modules->end()) {
            result.runtimes.push_back(&runtime);
        }
    }
    return result;
}

[[noreturn]] void ThrowAmbiguousModule(const std::string& moduleName,
                                       const std::vector<const RuntimeRegistration*>& matches)
{
    std::string candidates;
    for (const auto* runtime : matches) {
        if (!candidates.empty()) {
            candidates += ", ";
        }
        candidates += "'" + runtime->runtime_id + "'";
    }
    throw std::runtime_error("Module '" + moduleName + "' exists in multiple runtimes: " + candidates +
                             ". Select one with --runtime <id>.");
}

int RunModuleInfoCommandImpl(const Invocation& invocation)
{
    for (const auto& [name, values] : invocation.options) {
        if (values.size() != 1 || values.front().empty()) {
            throw std::invalid_argument(name + " requires exactly one nonempty value.");
        }
    }
    const auto& moduleName = invocation.positionalArgs.front();
    const auto selected = invocation.OptionValue("--runtime");
    const runtime::core::runtime_graph::RuntimeRegistry registry(
        invocation.OptionValue("--registry-path", extension::DefaultRuntimeRegistryPath().string()));
    const auto runtimes = registry.DiscoverLocalRuntimes();
    const auto matches = FindModuleRuntimes(runtimes, selected, moduleName);
    if (!matches.foundRuntime) {
        throw std::runtime_error("Runtime '" + selected + "' was not found in the local registry.");
    }
    if (matches.runtimes.empty()) {
        if (!matches.complete) {
            return 1;
        }
        throw std::runtime_error("Module '" + moduleName + "' was not found in the " +
                                 (selected.empty() ? "local registry." : "runtime '" + selected + "'."));
    }
    if (matches.runtimes.size() > 1) {
        ThrowAmbiguousModule(moduleName, matches.runtimes);
    }
    const auto& runtime = *matches.runtimes.front();
    std::cout << "Module: " << moduleName << '\n';
    std::cout << "Runtime: " << runtime.runtime_id << '\n';
    std::cout << "PID: " << runtime.pid << "\n\n";
    PrintTopics(runtime, moduleName, true);
    std::cout << '\n';
    PrintTopics(runtime, moduleName, false);
    return matches.complete ? 0 : 1;
}

} // namespace

void AddInfoCommand(Command& module)
{
    auto& info = module.AddSubcommand("info", "Show a local module's published and subscribed topics");
    info.SetHandler(RunModuleInfoCommandImpl);
    info.AddArgument("<module>", "Module name (use --runtime to select among identical names)");
    info.AddOption("--runtime", {}, "id", "Inspect the module in this runtime", OptionValueMode::REQUIRED);
    info.AddOption("--registry-path", {}, "path",
                   "Local registry root (default: " + extension::DefaultRuntimeRegistryPath().string() + ")",
                   OptionValueMode::REQUIRED);
}

} // namespace ibmw::cli::module