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

#include <charconv>
#include <cmath>
#include <csignal>
#include <iostream>
#include <stdexcept>
#include <thread>

#include "discovery_options.h"
#include "command_lifecycle.h"
#include "base/log_util.h"
#include "engine/topic_io/topic_subscription.h"

namespace ibmw::cli::topic {
namespace {
using Clock = std::chrono::steady_clock;
using ibmw::runtime::core::topic_io::TopicSubscription;
constexpr double MAX_OBSERVATION_SECONDS = 86400 * 365;
constexpr size_t MIN_OBSERVATION_WINDOW = 2;
constexpr std::chrono::milliseconds SUBSCRIPTION_REFRESH_INTERVAL(250);
constexpr std::chrono::milliseconds OBSERVATION_POLL_INTERVAL(20);

double Seconds(const Invocation& invocation, const std::string& name, const char* fallback)
{
    const auto value = OptionValue(invocation, name, fallback);
    double number = 0;
    const auto [end, error] = std::from_chars(value.data(), value.data() + value.size(), number);
    if (error != std::errc{} || end != value.data() + value.size() || !std::isfinite(number) || number <= 0 ||
        number > MAX_OBSERVATION_SECONDS) {
        throw std::invalid_argument(name + " requires a finite positive number of seconds (at most one year).");
    }
    return number;
}

size_t ParseWindow(const Invocation& invocation, std::optional<size_t> defaultWindow)
{
    size_t window = 0;
    if (defaultWindow) {
        const auto windowText = OptionValue(invocation, "--window", std::to_string(*defaultWindow));
        const auto [end, error] = std::from_chars(windowText.data(), windowText.data() + windowText.size(), window);
        if (error != std::errc{} || end != windowText.data() + windowText.size() || window < MIN_OBSERVATION_WINDOW) {
            throw std::invalid_argument("--window requires an integer of at least 2 messages.");
        }
    }
    return window;
}

void ParseQosOverrides(const Invocation& invocation, TopicSubscription::Options& options)
{
    for (const auto& policy : {std::string("reliability"), std::string("durability")}) {
        const auto option = "--qos-" + policy;
        if (!invocation.HasOption(option)) {
            continue;
        }
        const auto value = OptionValue(invocation, option);
        const bool valid = policy == "reliability" ? value == "reliable" || value == "best_effort"
                                                   : value == "volatile" || value == "transient_local";
        if (!valid) {
            throw std::invalid_argument("Invalid value for " + option + ": " + value);
        }
        options.qos.policies[policy] = value;
    }
}

struct ObservationProgress {
    std::optional<Clock::time_point> measurementStart;
    Clock::time_point nextRefresh;
    uint64_t reportedDropped = 0;
};

void RefreshSubscription(TopicSubscription& subscription, const ObservationOptions& options, const std::string& topic,
                         ObservationProgress& progress)
{
    if (subscription.Refresh() && !progress.measurementStart) {
        progress.measurementStart = Clock::now();
        std::cerr << "Subscribed to " << topic << (options.window ? "; using a steady clock.\n" : ".\n");
    }
    progress.nextRefresh = Clock::now() + SUBSCRIPTION_REFRESH_INTERVAL;
    const auto dropped = subscription.DroppedMessages();
    if (dropped != progress.reportedDropped) {
        std::cerr << "ibmw topic " << options.command << ": Runtime Tap dropped " << dropped << " message(s).\n";
        progress.reportedDropped = dropped;
    }
}
} // namespace

ObservationOptions ParseObservationOptions(const Invocation& invocation, std::string_view command,
                                           std::optional<size_t> defaultWindow)
{
    auto sources = ParseDiscoveryOptions(invocation);
    if (sources.size() != 1) {
        throw std::invalid_argument("topic " + std::string(command) + " accepts exactly one discovery source.");
    }
    const size_t window = ParseWindow(invocation, defaultWindow);
    const auto timeout = std::chrono::duration<double>(Seconds(invocation, "--timeout", "10"));
    const auto duration = invocation.HasOption("--duration")
                              ? std::chrono::duration<double>(Seconds(invocation, "--duration", "1"))
                              : std::chrono::duration<double>::max();
    TopicSubscription::Options options{.source = sources.front(),
                                       .topic = invocation.positionalArgs.front(),
                                       .type = OptionValue(invocation, "--type"),
                                       .config_file = OptionValue(invocation, "--config-file")};
    if (options.topic.empty()) {
        throw std::invalid_argument("Topic name must not be empty.");
    }
    ParseQosOverrides(invocation, options);
    if (options.source.backend == ibmw::discovery::DiscoveryBackend::kRegistry &&
        (!options.config_file.empty() || !options.qos.Empty())) {
        throw std::invalid_argument("--config-file and QoS overrides require network observation.");
    }
    if (options.source.backend == ibmw::discovery::DiscoveryBackend::kZenoh && !options.qos.Empty()) {
        throw std::invalid_argument("DDS/ROS 2 QoS overrides do not apply to Zenoh observation.");
    }

    return {.command = std::string(command),
            .subscription = std::move(options),
            .window = window,
            .timeout = timeout,
            .duration = duration};
}

int RunObservation(ObservationOptions options, ibmw::transport::SerializedMessageCallback observe,
                   const std::function<void(bool final)>& print, const std::function<bool()>& poll)
{
    SignalGuard signals;
    LoggerLevelGuard loggerLevel;
    const auto topic = options.subscription.topic;
    TopicSubscription subscription(std::move(options.subscription));
    subscription.Start(std::move(observe));
    const auto discoveryStart = Clock::now();
    ObservationProgress progress{.nextRefresh = discoveryStart};
    auto& measurementStart = progress.measurementStart;
    auto nextPrint = discoveryStart + std::chrono::seconds(1);
    while (!g_stopRequested) {
        auto now = Clock::now();
        if (now >= progress.nextRefresh) {
            RefreshSubscription(subscription, options, topic, progress);
            now = Clock::now();
        }
        if (poll && poll()) {
            break;
        }
        if (!measurementStart && now - discoveryStart >= options.timeout) {
            throw std::runtime_error("Timed out waiting for a publisher of '" + topic + "'.");
        }
        if (measurementStart && now - *measurementStart >= options.duration) {
            break;
        }
        if (now >= nextPrint) {
            if (print) {
                print(false);
            }
            std::cout.flush();
            nextPrint = now + std::chrono::seconds(1);
        }
        std::this_thread::sleep_for(OBSERVATION_POLL_INTERVAL);
    }
    subscription.Stop();
    if (poll) {
        poll();
    }
    if (print) {
        print(true);
    }
    std::cout.flush();
    return 0;
}

void AddObservationOptions(ibmw::cli::Command& command, std::optional<size_t> defaultWindow)
{
    command.AddArgument("<topic>", "Topic to observe (including hidden topics)");
    AddDiscoveryOptions(command, false);
    using Mode = ibmw::cli::OptionValueMode;
    if (defaultWindow) {
        command.AddOption("--window", "-w", "messages",
                          "Window size in messages, at least 2 (default: " + std::to_string(*defaultWindow) + ")",
                          Mode::REQUIRED);
    }
    command.AddOption("--type", {}, "type", "Select a message type when the topic has multiple types", Mode::REQUIRED);
    command.AddOption("--timeout", {}, "seconds", "Wait for a publisher (default: 10 seconds)", Mode::REQUIRED);
    command.AddOption("--duration", {}, "seconds", "Stop after this observation duration (default: until Ctrl+C)",
                      Mode::REQUIRED);
    command.AddOption("--config-file", {}, "path",
                      "Transport connection configuration; domains come from discovery options", Mode::REQUIRED);
    command.AddOption("--qos-reliability", {}, "policy",
                      "best_effort (default; reliable for DDS exclusive ownership) or reliable; DDS/ROS 2 only",
                      Mode::REQUIRED);
    command.AddOption("--qos-durability", {}, "policy", "volatile (default) or transient_local; DDS/ROS 2 only",
                      Mode::REQUIRED);
    command.AddOption("--include-hidden-topics", {}, {}, "Explicit topic queries already include hidden topics");
}

} // namespace ibmw::cli::topic