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

#include <algorithm>
#include <chrono>
#include <future>
#include <iostream>
#include <stdexcept>
#include <string>
#include <thread>
#include <utility>

#include "command_lifecycle.h"
#include "engine/engine.h"
#include "engine/runtime_graph/type_support_registry.h"
#include "message_text.h"
#include "pub_options.h"

namespace ibmw::cli::topic {
namespace {

using Clock = std::chrono::steady_clock;
namespace core = ibmw::runtime::core;
constexpr std::chrono::milliseconds STOP_CHECK_INTERVAL(20);

void WaitUntil(Clock::time_point deadline)
{
    while (!g_stopRequested && Clock::now() < deadline) {
        std::this_thread::sleep_until(std::min(deadline, Clock::now() + STOP_CHECK_INTERVAL));
    }
}

struct StopGuard {
    core::Engine& engine;
    std::future<void>& running;
    ~StopGuard()
    {
        engine.Shutdown();
        if (running.valid()) {
            running.wait();
        }
    }
};

Clock::duration ToClockDuration(double seconds)
{
    return std::chrono::duration_cast<Clock::duration>(std::chrono::duration<double>(seconds));
}

ibmw::util::TypeSupportRef LoadMessageType(const Invocation& invocation, YAML::Node& runtime,
                                           core::runtime_graph::TypeSupportRegistry& types, const std::string& typeName)
{
    const auto packages = invocation.options.find("--type-support");
    if (packages == invocation.options.end()) {
        throw std::invalid_argument("Provide --type-support <library> for the message type.");
    }
    for (const auto& package : packages->second) {
        if (package.empty()) {
            throw std::invalid_argument("--type-support requires a nonempty library path.");
        }
        types.Load(package);
        runtime["runtime_graph"]["type_support_pkgs"].push_back(package);
    }
    auto type = types.Find(typeName);
    if (!type) {
        throw std::invalid_argument("No TypeSupport for '" + typeName + "' in the supplied libraries.");
    }
    if (!type.CheckSerializationTypeSupported("json")) {
        throw std::invalid_argument("TypeSupport for '" + typeName + "' does not support JSON message input.");
    }
    return type;
}

std::shared_ptr<void> ParseMessage(const Invocation& invocation, const ibmw::util::TypeSupportRef& type,
                                   const std::string& typeName)
{
    const auto documents = YAML::LoadAll(invocation.positionalArgs.at(2));
    if (documents.size() != 1) {
        throw std::invalid_argument("Message contents must be one JSON/YAML document.");
    }
    const auto text = FromYaml(documents.front()).dump();
    auto object = type.CreateSharedPtr();
    const ibmw_buffer_view_t buffer{.data = text.data(), .len = text.size()};
    if (!object || !type.Deserialize("json", {.data = &buffer, .len = 1}, object.get())) {
        throw std::invalid_argument("Invalid fields, values or bounds for message type '" + typeName + "'.");
    }
    return object;
}

struct PublisherRegistration {
    const std::string& typeName;
    const std::string& topic;
    const std::string& package;
    const std::string& module;
    const ibmw::util::TypeSupportRef& type;
};

// Register before RuntimeGraph snapshots the catalog, just as modules do.
void RegisterPublisher(core::Engine& engine, const PublisherRegistration& publisher,
                       const core::transport::SendTypeWrapper*& registered)
{
    auto& bus = engine.GetTransportBus();
    engine.RegisterHook(core::After(core::Phase::kInitialize, core::Subsystem::kTransport),
                        [&publisher, &bus, &registered] {
                            core::transport::SendTypeWrapper registration;
                            registration.info = {.msg_type = publisher.typeName,
                                                 .topic_name = publisher.topic,
                                                 .pkg_path = publisher.package,
                                                 .module_name = publisher.module,
                                                 .msg_type_support_ref = publisher.type};
                            if (!bus.RegisterSendType(std::move(registration))) {
                                throw std::runtime_error("Cannot register publisher.");
                            }
                            registered = bus.GetTransportCatalog()->GetSendTypeWrapperPtr(
                                publisher.typeName, publisher.topic, publisher.package, publisher.module);
                            if (!registered || registered->cached_drivers.empty()) {
                                throw std::runtime_error("No driver selected for publisher.");
                            }
                        });
}

uint64_t PublishMessages(core::Engine& engine, const core::transport::SendTypeWrapper& registered,
                         const std::shared_ptr<void>& object, const std::string& serialization,
                         const PublicationConfig& publication)
{
    auto& bus = engine.GetTransportBus();
    const auto period = ToClockDuration(1 / publication.rate);
    auto next = Clock::now();
    uint64_t sent = 0;
    while (!g_stopRequested && sent < publication.count) {
        ibmw::transport::Context context;
        context.SetSerializationType(serialization);
        core::transport::MessageFrame frame{
            .info = registered.info, .msg_ptr = object.get(), .ctx_ref = context, .msg_cache_ptr = object};
        bus.Send(std::move(frame));
        ++sent;
        if (sent == publication.count) {
            break;
        }
        next += period;
        if (next < Clock::now()) {
            next = Clock::now() + period;
        }
        WaitUntil(next);
    }
    return sent;
}

int RunTopicPubCommandImpl(const Invocation& invocation)
{
    auto publication = ParsePublicationOptions(invocation);
    const auto& driver = publication.driver;
    const auto& topic = publication.topic;
    const auto& typeName = publication.typeName;
    auto& config = publication.root;
    auto runtime = config["ibmw"];

    core::runtime_graph::TypeSupportRegistry types;
    const auto type = LoadMessageType(invocation, runtime, types, typeName);
    const auto object = ParseMessage(invocation, type, typeName);
    // Serialize before starting any transport: input/conversion failures must not create a publisher.
    const auto serialization = std::string(type.DefaultSerializationType());
    const auto bytes = type.SimpleSerialize(serialization, object.get());
    if (bytes.empty()) {
        throw std::runtime_error("Message serialization failed for '" + typeName + "'.");
    }
    if (driver == "dds" && !typeName.starts_with("dds:") && !typeName.starts_with("ros2:")) {
        throw std::invalid_argument("DDS publishing requires a dds: or ros2: message type.");
    }

    LoggerLevelGuard logger;
    core::Engine engine;
    const auto package = types.PackagePath(typeName);
    const std::string module = "ibmw-topic-pub";
    const core::transport::SendTypeWrapper* registered = nullptr;
    const PublisherRegistration publisher{
        .typeName = typeName, .topic = topic, .package = package, .module = module, .type = type};
    RegisterPublisher(engine, publisher, registered);
    engine.Initialize({.config_node = config});
    // During transport initialization (e.g. waiting for RouDi), keep the default
    // signal behavior so blocking third-party initialization can be interrupted.
    SignalGuard signals;
    auto running = engine.AsyncStart();
    StopGuard cleanup{engine, running};
    std::cerr << "Publishing " << topic << " [" << typeName << "] via " << driver << '\n';
    WaitUntil(Clock::now() + ToClockDuration(publication.wait));
    const uint64_t sent = PublishMessages(engine, *registered, object, serialization, publication);
    if (!g_stopRequested) {
        WaitUntil(Clock::now() + ToClockDuration(publication.keepAlive));
    }
    std::cerr << "Published " << sent << " message(s).\n";
    engine.Shutdown();
    running.get();
    return 0;
}

} // namespace

void AddPubCommand(Command& topic)
{
    auto& pub = topic.AddSubcommand("pub", "Publish JSON/YAML message contents using the runtime transport");
    pub.SetHandler(RunTopicPubCommandImpl);
    AddPublicationOptions(pub);
}

} // namespace ibmw::cli::topic