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

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

#include "observation_command.h"
#include "rate_statistics.h"

namespace ibmw::cli::topic {
namespace {

constexpr size_t DEFAULT_HZ_WINDOW = 10000;
constexpr int RATE_DECIMALS = 3;
constexpr int DEVIATION_DECIMALS = 5;

int RunTopicHzCommandImpl(const Invocation& invocation)
{
    auto options = ParseObservationOptions(invocation, "hz", DEFAULT_HZ_WINDOW);
    RateStatistics statistics(options.window);
    uint64_t printedReceived = 0;
    return RunObservation(
        std::move(options), [&statistics](ibmw::transport::SerializedMessage&&) { statistics.Observe(); },
        [&statistics, &printedReceived](bool final) {
            const auto result = statistics.Snapshot();
            if (final && result.received == printedReceived) {
                if (result.received == 0) {
                    std::cout << "no messages received\n";
                }
                return;
            }
            if (result.received == printedReceived) {
                std::cout << "no new messages\n";
            } else if (result.window < RateStatistics::MIN_WINDOW || result.rate == 0) {
                std::cout << "waiting for enough messages to calculate rate\n";
            } else {
                std::ostringstream output;
                output << std::fixed << std::setprecision(RATE_DECIMALS) << "average rate: " << result.rate;
                output << "\n\tmin: " << result.minimum << "s max: " << result.maximum;
                output << "s std dev: " << std::setprecision(DEVIATION_DECIMALS) << result.deviation;
                output << "s window: " << result.window << '\n';
                std::cout << output.str();
            }
            printedReceived = result.received;
        });
}

} // namespace

void AddHzCommand(Command& topic)
{
    auto& hz = topic.AddSubcommand("hz", "Measure the received topic rate using a steady clock");
    hz.SetHandler(RunTopicHzCommandImpl);
    AddObservationOptions(hz, DEFAULT_HZ_WINDOW);
}

} // namespace ibmw::cli::topic