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

#include <charconv>
#include <cstdlib>
#include <optional>
#include <stdexcept>
#include <string>
#include <string_view>
#include <utility>

namespace ibmw::cli::topic {
namespace {

std::optional<std::string> ReadOption(const ibmw::cli::Invocation& invocation, std::string_view name)
{
    const auto found = invocation.options.find(std::string(name));
    if (found == invocation.options.end()) {
        return std::nullopt;
    }
    if (found->second.size() != 1) {
        throw std::invalid_argument(std::string(name) + " must be specified exactly once.");
    }
    return found->second.front();
}

uint32_t ParseDomain(std::string_view value, std::string_view name)
{
    uint32_t domain = 0;
    const auto [end, error] = std::from_chars(value.data(), value.data() + value.size(), domain);
    if (value.empty() || error != std::errc{} || end != value.data() + value.size()) {
        throw std::invalid_argument(std::string(name) + " must be a decimal integer in [0, 4294967295], got '" +
                                    std::string(value) + "'.");
    }
    return domain;
}

void RequireSelected(bool selected, std::string_view option, std::string_view backend)
{
    if (!selected) {
        throw std::invalid_argument(std::string(option) + " requires " + std::string(backend) +
                                    " discovery to be selected.");
    }
}

} // namespace

void AddDiscoveryOptions(ibmw::cli::Command& command, bool allowAll)
{
    using ibmw::cli::OptionValueMode;
    command.AddOption("--registry", {}, {}, "Query local runtime registrations across all drivers (default source)");
    command.AddOption("--dds", "-d", {}, "Query DDS endpoints in the selected domain");
    command.AddOption("--ros2", "-r", {}, "Query the ROS 2 graph in the selected domain");
    command.AddOption("--zenoh", "-z", {}, "Query IBMW Zenoh endpoint metadata");
    if (allowAll) {
        command.AddOption("--all", "-a", {}, "Query all four sources, not all domains");
    }
    command.AddOption("--domain", {}, "id", "Domain for selected DDS and ROS 2 sources", OptionValueMode::REQUIRED);
    command.AddOption("--dds-domain", {}, "id", "DDS domain (overrides --domain; default: 0)",
                      OptionValueMode::REQUIRED);
    command.AddOption("--ros-domain", {}, "id", "ROS 2 domain (overrides --domain; otherwise ROS_DOMAIN_ID or 0)",
                      OptionValueMode::REQUIRED);
    command.AddOption("--zenoh-domain", {}, "name", "Zenoh limit_domain (default: empty)", OptionValueMode::REQUIRED);
    command.AddOption("--zenoh-config", {}, "path", "Zenoh native connection configuration", OptionValueMode::REQUIRED);
    command.AddOption(
        "--registry-path", {}, "path",
        "Local registration directory (default: " + ibmw::discovery::DiscoveryOptions{}.registry_path.string() + ")",
        OptionValueMode::REQUIRED);
}

namespace {
using ibmw::discovery::DiscoveryBackend;
using ibmw::discovery::DiscoveryOptions;

struct DiscoverySelection {
    bool dds = false;
    bool ros2 = false;
    bool zenoh = false;
    bool registrySelected = false;
    std::optional<std::string> domain;
    std::optional<std::string> ddsDomain;
    std::optional<std::string> rosDomain;
    std::optional<std::string> zenohDomain;
    std::optional<std::string> zenohConfig;
    std::optional<std::string> registry;
};

void ValidateSelection(const DiscoverySelection& s)
{
    if (s.domain) {
        RequireSelected(s.dds || s.ros2, "--domain", "DDS or ROS 2");
    }
    if (s.ddsDomain) {
        RequireSelected(s.dds, "--dds-domain", "DDS");
    }
    if (s.rosDomain) {
        RequireSelected(s.ros2, "--ros-domain", "ROS 2");
    }
    if (s.zenohDomain) {
        RequireSelected(s.zenoh, "--zenoh-domain", "Zenoh");
    }
    if (s.zenohConfig) {
        RequireSelected(s.zenoh, "--zenoh-config", "Zenoh");
    }
    if (s.registry) {
        RequireSelected(s.registrySelected, "--registry-path", "registry");
    }
    if ((s.registry && s.registry->empty()) || (s.zenohConfig && s.zenohConfig->empty())) {
        throw std::invalid_argument("Discovery configuration paths must not be empty.");
    }
}

DiscoverySelection ReadSelection(const ibmw::cli::Invocation& invocation)
{
    DiscoverySelection selection;
    const bool all = invocation.HasOption("--all");
    selection.dds = all || invocation.HasOption("--dds");
    selection.ros2 = all || invocation.HasOption("--ros2");
    selection.zenoh = all || invocation.HasOption("--zenoh");
    selection.registrySelected =
        all || invocation.HasOption("--registry") || !(selection.dds || selection.ros2 || selection.zenoh);

    selection.domain = ReadOption(invocation, "--domain");
    selection.ddsDomain = ReadOption(invocation, "--dds-domain");
    selection.rosDomain = ReadOption(invocation, "--ros-domain");
    selection.zenohDomain = ReadOption(invocation, "--zenoh-domain");
    selection.zenohConfig = ReadOption(invocation, "--zenoh-config");
    selection.registry = ReadOption(invocation, "--registry-path");
    ValidateSelection(selection);
    return selection;
}

uint32_t SelectRosDomain(const DiscoverySelection& selection, uint32_t commonDomain)
{
    uint32_t selectedDomain = commonDomain;
    if (selection.rosDomain) {
        selectedDomain = ParseDomain(*selection.rosDomain, "--ros-domain");
    } else if (!selection.domain) {
        if (const char* environment = std::getenv("ROS_DOMAIN_ID"); environment != nullptr && *environment != '\0') {
            selectedDomain = ParseDomain(environment, "ROS_DOMAIN_ID");
        }
    }
    return selectedDomain;
}
} // namespace

std::vector<ibmw::discovery::DiscoveryOptions> ParseDiscoveryOptions(const ibmw::cli::Invocation& invocation)
{
    const auto selection = ReadSelection(invocation);
    const uint32_t commonDomain = selection.domain ? ParseDomain(*selection.domain, "--domain") : 0;
    std::vector<DiscoveryOptions> result;
    if (selection.registrySelected) {
        DiscoveryOptions options;
        if (selection.registry) {
            options.registry_path = *selection.registry;
        }
        result.push_back(std::move(options));
    }
    // Domains are parsed before each DiscoveryOptions aggregate is built: GCC
    // before 13 (PR66139) leaks the defaulted registry_path when an aggregate
    // initializer throws.
    if (selection.dds) {
        const uint32_t ddsDomainId =
            selection.ddsDomain ? ParseDomain(*selection.ddsDomain, "--dds-domain") : commonDomain;
        result.push_back(DiscoveryOptions{.backend = DiscoveryBackend::kDds, .domain_id = ddsDomainId});
    }
    if (selection.ros2) {
        const uint32_t selectedDomain = SelectRosDomain(selection, commonDomain);
        result.push_back(DiscoveryOptions{.backend = DiscoveryBackend::kRos2, .domain_id = selectedDomain});
    }
    if (selection.zenoh) {
        result.push_back(DiscoveryOptions{.backend = DiscoveryBackend::kZenoh,
                                          .zenoh_domain = selection.zenohDomain.value_or(""),
                                          .zenoh_config = selection.zenohConfig.value_or("")});
    }
    return result;
}

} // namespace ibmw::cli::topic