#pragma once
#include <cmath>
#include <cstdio>
#include <string>

namespace wearable {
inline std::string compact_rate(double bytes,unsigned compact=0) {
    if(!std::isfinite(bytes) || bytes<0) bytes=0;
    constexpr const char* units[]={"B","K","M","G","T","P","E"};
    unsigned unit=0;
    while(bytes>=1000 && unit<6) {bytes/=1000;++unit;}
    char text[24];
    if(bytes>=1000) return "999E+/s";
    const bool decimal=!compact && unit>=2 && bytes<10;
    // Promote a rounded 1000 rather than wasting width on four digits.
    if(!decimal && std::round(bytes)>=1000 && unit<6) {bytes/=1000;++unit;}
    std::snprintf(text,sizeof(text),decimal?"%.1f%s%s/s":"%.0f%s%s/s",bytes,units[unit],
        !compact && unit?"B":"");
    return text;
}
template<class Measure> std::string monitor_network_line(double rx,double tx,int width,Measure measure) {
    for(unsigned compact=0;compact<3;++compact) {
        const auto gap=compact==2?"":" ";
        auto line=std::string("RX")+gap+compact_rate(rx,compact)+" TX"+gap+compact_rate(tx,compact);
        if(measure(line.c_str())<=width) return line;
    }
    // Bounded same-size fallback for extreme values; never clip or wrap.
    return "RX HIGH TX HIGH";
}
struct MonitorView {
    const char* hostname="LIGHTHOUSE";
    bool valid=false;
    float cpu=0,memory=0,disk=0,rx=0,tx=0;
};
} // namespace wearable
