/*
 * 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 <stdexcept>
#include <string>
#include <charconv>
#include <cmath>
#include <cstdlib>
#include <optional>
#include <utility>

#include "extension_api/ibmw_runtime_directory.h"

namespace ibmw::cli::service {

namespace {
std::optional<std::string> Read(const Invocation& invocation, const std::string& name)
{
    const auto found = invocation.options.find(name);
    if (found == invocation.options.end()) {
        return std::nullopt;
    }
    if (found->second.size() != 1 || found->second.front().empty()) {
        throw std::invalid_argument(name + " requires exactly one nonempty value.");
    }
    return found->second.front();
}
uint32_t Domain(const std::string& value)
{
    uint32_t result = 0;
    const auto [end, error] = std::from_chars(value.data(), value.data() + value.size(), result);
    if (error != std::errc{} || end != value.data() + value.size()) {
        throw std::invalid_argument("Domain must be a nonnegative decimal integer.");
    }
    return result;
}

ibmw::discovery::ServiceDiscoveryTlsOptions ParseDiscoveryTlsOptions(const Invocation& invocation)
{
    // Values are read before each aggregate is built: GCC before 13 (PR66139)
    // leaks the members already constructed when an aggregate initializer throws.
    auto truststore = Read(invocation, "--mqtt-truststore").value_or("");
    auto clientCert = Read(invocation, "--mqtt-client-cert").value_or("");
    auto clientKey = Read(invocation, "--mqtt-client-key").value_or("");
    ibmw::discovery::ServiceDiscoveryTlsOptions result{
        .truststore = std::move(truststore), .client_cert = std::move(clientCert), .client_key = std::move(clientKey)};
    const auto broker = Read(invocation, "--mqtt");
    if (!result.Empty() && (!broker || !broker->starts_with("ssl://"))) {
        throw std::invalid_argument("MQTT TLS credentials require --mqtt ssl://host:port.");
    }
    if (result.client_cert.empty() != result.client_key.empty()) {
        throw std::invalid_argument("MQTT client certificate and key must be supplied together.");
    }
    for (const auto* path : {&result.truststore, &result.client_cert, &result.client_key}) {
        if (!path->empty() && !std::filesystem::is_regular_file(*path)) {
            throw std::invalid_argument("MQTT TLS credential file does not exist: " + *path);
        }
    }
    return result;
}
} // namespace

void AddDiscoveryOptions(Command& command)
{
    command.AddOption("--registry", {}, {}, "Query local runtime registrations (default)");
    command.AddOption("--registry-path", {}, "path",
                      "Local registry root (default: " + extension::DefaultRuntimeRegistryPath().string() + ")",
                      OptionValueMode::REQUIRED);
    command.AddOption("--include-hidden-services", {}, {}, "Consider hidden services as well");
    command.AddOption("--dds", "-d", {}, "Discover DDS request/reply endpoints");
    command.AddOption("--ros2", "-r", {}, "Query native ROS 2 services");
    command.AddOption("--zenoh", "-z", {}, "Query IBMW Zenoh service directories");
    command.AddOption("--http", {}, "host:port", "Query an IBMW HTTP server directory", OptionValueMode::REQUIRED);
    command.AddOption("--grpc", {}, "host:port", "Query an IBMW gRPC server directory (HTTP/2)",
                      OptionValueMode::REQUIRED);
    command.AddOption("--mqtt", {}, "broker-uri", "Query IBMW services through an MQTT broker",
                      OptionValueMode::REQUIRED);
    command.AddOption("--mqtt-truststore", {}, "path", "MQTT TLS CA certificate (otherwise system trust store)",
                      OptionValueMode::REQUIRED);
    command.AddOption("--mqtt-client-cert", {}, "path", "MQTT TLS client certificate", OptionValueMode::REQUIRED);
    command.AddOption("--mqtt-client-key", {}, "path", "MQTT TLS client private key", OptionValueMode::REQUIRED);
    command.AddOption("--domain", {}, "id", "Domain for selected DDS/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 (otherwise --domain, ROS_DOMAIN_ID or 0)",
                      OptionValueMode::REQUIRED);
    command.AddOption("--zenoh-domain", {}, "name", "Zenoh limit_domain", OptionValueMode::REQUIRED);
    command.AddOption("--zenoh-config", {}, "path", "Zenoh native connection configuration", OptionValueMode::REQUIRED);
    command.AddOption("--timeout", {}, "seconds", "Discovery deadline, including connections (default: 2)",
                      OptionValueMode::REQUIRED);
}

namespace {
using Backend = ibmw::discovery::ServiceDiscoveryBackend;
using Options = ibmw::discovery::ServiceDiscoveryOptions;

struct DiscoverySelection {
    bool dds = false;
    bool ros2 = false;
    bool zenoh = false;
    std::optional<std::string> http;
    std::optional<std::string> grpc;
    std::optional<std::string> mqtt;
    ibmw::discovery::ServiceDiscoveryTlsOptions mqttTls;
    bool registry = false;
    std::optional<std::string> common;
    std::optional<std::string> dd;
    std::optional<std::string> rd;
    std::optional<std::string> zd;
    std::optional<std::string> zc;
};

DiscoverySelection ReadDiscoverySelection(const Invocation& invocation)
{
    DiscoverySelection selection;
    selection.dds = invocation.HasOption("--dds");
    selection.ros2 = invocation.HasOption("--ros2");
    selection.zenoh = invocation.HasOption("--zenoh");
    selection.http = Read(invocation, "--http");
    selection.grpc = Read(invocation, "--grpc");
    selection.mqtt = Read(invocation, "--mqtt");
    selection.mqttTls = ParseDiscoveryTlsOptions(invocation);
    selection.registry = invocation.HasOption("--registry") || !(selection.dds || selection.ros2 || selection.zenoh ||
                                                                 selection.http || selection.grpc || selection.mqtt);
    selection.common = Read(invocation, "--domain");
    selection.dd = Read(invocation, "--dds-domain");
    selection.rd = Read(invocation, "--ros-domain");
    selection.zd = Read(invocation, "--zenoh-domain");
    selection.zc = Read(invocation, "--zenoh-config");
    const auto& s = selection;
    if ((s.common && !(s.dds || s.ros2)) || (s.dd && !s.dds) || (s.rd && !s.ros2) || ((s.zd || s.zc) && !s.zenoh) ||
        (invocation.HasOption("--registry-path") && !s.registry)) {
        throw std::invalid_argument("Discovery configuration requires its corresponding source to be selected.");
    }
    return selection;
}

void AddNetworkSources(const DiscoverySelection& selection, std::vector<Options>& result)
{
    // Each aggregate gets only moved or trivial values (PR66139, see above).
    if (selection.zenoh) {
        std::string domain = selection.zd.value_or("");
        std::filesystem::path config = selection.zc.value_or("");
        result.push_back(
            {.backend = Backend::kZenoh, .zenoh_domain = std::move(domain), .zenoh_config = std::move(config)});
    }
    if (selection.http) {
        std::string endpoint = *selection.http;
        result.push_back({.backend = Backend::kHttp, .endpoint = std::move(endpoint)});
    }
    if (selection.grpc) {
        std::string endpoint = *selection.grpc;
        result.push_back({.backend = Backend::kGrpc, .endpoint = std::move(endpoint)});
    }
    if (selection.mqtt) {
        std::string endpoint = *selection.mqtt;
        auto tls = selection.mqttTls;
        result.push_back({.backend = Backend::kMqtt, .endpoint = std::move(endpoint), .mqtt_tls = std::move(tls)});
    }
}
} // namespace

std::vector<ibmw::discovery::ServiceDiscoveryOptions> ParseDiscoveryOptions(const Invocation& invocation)
{
    const auto selection = ReadDiscoverySelection(invocation);
    std::vector<Options> result;
    if (selection.registry) {
        result.push_back({.registry_path = ParseRegistryPath(invocation)});
    }
    if (selection.dds) {
        const uint32_t ddsDomain = Domain(selection.dd.value_or(selection.common.value_or("0")));
        result.push_back({.backend = Backend::kDds, .domain_id = ddsDomain});
    }
    if (selection.ros2) {
        const char* env = std::getenv("ROS_DOMAIN_ID");
        const uint32_t rosDomain = Domain(selection.rd.value_or(selection.common.value_or(env && *env ? env : "0")));
        result.push_back({.backend = Backend::kRos2, .domain_id = rosDomain});
    }
    AddNetworkSources(selection, result);
    return result;
}

std::chrono::milliseconds ParseDiscoveryTimeout(const Invocation& invocation)
{
    const auto value = Read(invocation, "--timeout");
    if (!value) {
        return std::chrono::seconds(2);
    }
    double seconds = 0;
    const auto [last, error] = std::from_chars(value->data(), value->data() + value->size(), seconds);
    if (error != std::errc{} || last != value->data() + value->size() || !std::isfinite(seconds) || seconds < 0.01 ||
        seconds > 60) {
        throw std::invalid_argument("--timeout must be between 0.01 and 60 seconds.");
    }
    return std::chrono::milliseconds(static_cast<int64_t>(seconds * 1000));
}

std::filesystem::path ParseRegistryPath(const Invocation& invocation)
{
    const auto found = invocation.options.find("--registry-path");
    if (found == invocation.options.end()) {
        return extension::DefaultRuntimeRegistryPath();
    }
    if (found->second.size() != 1 || found->second.front().empty()) {
        throw std::invalid_argument("--registry-path requires exactly one nonempty value.");
    }
    return found->second.front();
}

} // namespace ibmw::cli::service