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

#include <charconv>
#include <deque>
#include <exception>
#include <iostream>
#include <mutex>
#include <stdexcept>
#include <string>
#include <utility>

#include "echo_formatter.h"
#include "observation_command.h"

namespace ibmw::cli::topic {
namespace {

size_t ParseQueueSize(const Invocation& invocation)
{
    const auto queueSizeText = OptionValue(invocation, "--queue-size", "100");
    size_t queueSize = 0;
    const auto [end, parseError] =
        std::from_chars(queueSizeText.data(), queueSizeText.data() + queueSizeText.size(), queueSize);
    if (parseError != std::errc{} || end != queueSizeText.data() + queueSizeText.size() || queueSize == 0) {
        throw std::invalid_argument("--queue-size requires a positive integer.");
    }
    return queueSize;
}

// Messages received on transport threads, waiting for output on the CLI thread.
class EchoQueue {
public:
    EchoQueue(size_t queueSize, bool once) : queueSize_(queueSize), once_(once) {}

    void Accept(ibmw::transport::SerializedMessage&& message)
    {
        std::lock_guard lock(mutex_);
        if (error_ || (once_ && acceptedOnce_)) {
            return;
        }
        try {
            if (pending_.size() >= queueSize_) {
                throw std::runtime_error("Echo output queue is full (" + std::to_string(queueSize_) +
                                         " messages); output cannot keep up with reception.");
            }
            // Queued samples can outlive the observer Engine during final drain
            // or error cleanup. Release transport-owned storage while its DSO is
            // still loaded and keep a CLI-owned copy for decoding and output.
            if (message.payload) {
                message.payload = ibmw::transport::CopySerializedPayload(*message.payload);
            }
            pending_.push_back(std::move(message));
            acceptedOnce_ = true;
        } catch (...) {
            error_ = std::current_exception();
        }
    }

    // Prints queued messages; returns true once --once has printed its message.
    bool Drain(EchoFormatter& formatter, const std::string& format, bool raw)
    {
        std::deque<ibmw::transport::SerializedMessage> batch;
        {
            std::lock_guard lock(mutex_);
            if (error_) {
                std::rethrow_exception(error_);
            }
            batch.swap(pending_);
        }
        for (const auto& message : batch) {
            std::cout << formatter.Format(message) << (format == "json" && !raw ? "\n" : "\n---\n");
            std::cout.flush();
            if (!std::cout) {
                throw std::runtime_error("Cannot write echo output.");
            }
            ++printed_;
        }
        return once_ && printed_ != 0;
    }

    size_t Printed() const { return printed_; }

private:
    std::mutex mutex_;
    std::deque<ibmw::transport::SerializedMessage> pending_;
    std::exception_ptr error_;
    bool acceptedOnce_ = false;
    size_t printed_ = 0;
    size_t queueSize_;
    bool once_;
};

int RunTopicEchoCommandImpl(const Invocation& invocation)
{
    auto options = ParseObservationOptions(invocation, "echo");
    const size_t queueSize = ParseQueueSize(invocation);
    const bool raw = invocation.HasOption("--raw");
    const bool once = invocation.HasOption("--once");
    const auto format = OptionValue(invocation, "--format", "yaml");
    if (raw && (invocation.HasOption("--field") || invocation.HasOption("--format"))) {
        throw std::invalid_argument("--raw cannot be combined with --field or --format.");
    }
    EchoFormatter formatter(format, OptionValue(invocation, "--field"), raw);
    const auto packages = invocation.options.find("--type-support");
    if (packages != invocation.options.end()) {
        for (const auto& path : packages->second) {
            formatter.LoadPackage(path);
        }
    }
    formatter.LoadConfiguration(options.subscription.config_file);
    options.subscription.prepare_registry = [&formatter](const auto& publisher) { formatter.Remember(publisher); };

    EchoQueue queue(queueSize, once);
    const int result = RunObservation(
        std::move(options),
        [&queue](ibmw::transport::SerializedMessage&& message) { queue.Accept(std::move(message)); }, {},
        [&queue, &formatter, &format, &raw] { return queue.Drain(formatter, format, raw); });
    if (queue.Printed() == 0) {
        std::cerr << "ibmw topic echo: no messages received.\n";
    }
    return result;
}

} // namespace

void AddEchoCommand(Command& topic)
{
    using Mode = OptionValueMode;
    auto& echo = topic.AddSubcommand("echo", "Print received topic messages");
    echo.SetHandler(RunTopicEchoCommandImpl);
    AddObservationOptions(echo);
    echo.AddOption("--once", {}, {}, "Print one message and exit");
    echo.AddOption("--queue-size", {}, "messages",
                   "Maximum messages waiting for output, positive integer (default: 100)", Mode::REQUIRED);
    echo.AddOption("--field", {}, "path", "Print a dot-separated field path (numeric segments index arrays)",
                   Mode::REQUIRED);
    echo.AddOption("--format", {}, "format", "yaml (default) or json (one JSON value per line)", Mode::REQUIRED);
    echo.AddOption("--type-support", {}, "path", "Local TypeSupport package for binary-to-text decoding; repeatable",
                   Mode::REQUIRED);
    echo.AddOption("--raw", {}, {}, "Print serialized bytes as hexadecimal without decoding");
}

} // namespace ibmw::cli::topic