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

#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
#include <utility>

#include "bandwidth_statistics.h"
#include "observation_command.h"

namespace ibmw::cli::topic {
namespace {

constexpr size_t DEFAULT_BW_WINDOW = 100;
constexpr int SCALED_UNIT_DECIMALS = 2;

int RunTopicBwCommandImpl(const Invocation& invocation)
{
    auto options = ParseObservationOptions(invocation, "bw", DEFAULT_BW_WINDOW);
    BandwidthStatistics statistics(options.window);
    return RunObservation(
        std::move(options),
        [&statistics](ibmw::transport::SerializedMessage&& message) { statistics.Observe(message.PayloadSize()); },
        [&statistics](bool final) {
            const auto result = statistics.Snapshot();
            if (result.received == 0) {
                std::cout << (final ? "no messages received\n" : "no new messages\n");
            } else if (!result.ready) {
                std::cout << "waiting for enough messages to calculate bandwidth\n";
            } else {
                const double scale = result.bytesPerSecond < 1000      ? 1
                                     : result.bytesPerSecond < 1000000 ? 1000
                                                                       : 1000000;
                const char* unit = scale == 1 ? "B" : scale == 1000 ? "KB" : "MB";
                std::ostringstream output;
                output << std::fixed << std::setprecision(scale == 1 ? 0 : SCALED_UNIT_DECIMALS);
                output << result.bytesPerSecond / scale << ' ' << unit << "/s from " << result.window;
                output << " messages\n\tMessage size mean: " << result.mean / scale << ' ' << unit;
                output << " min: " << result.minimum / scale << ' ' << unit << " max: " << result.maximum / scale;
                output << ' ';
                output << unit << '\n';
                std::cout << output.str();
            }
        });
}

} // namespace

void AddBwCommand(Command& topic)
{
    auto& bw = topic.AddSubcommand("bw", "Measure received serialized payload bandwidth (excludes transport overhead)");
    bw.SetHandler(RunTopicBwCommandImpl);
    AddObservationOptions(bw, DEFAULT_BW_WINDOW);
}

} // namespace ibmw::cli::topic