import Foundation

/// Compact human formatting for counters surfaced in the UI.
enum Format {
    /// Bit-rate, e.g. 224229 → "224 kbps", 7216819 → "7.2 Mbps".
    static func bps(_ value: Double?) -> String {
        guard let value, value >= 0 else { return "—" }
        let units = ["bps", "kbps", "Mbps", "Gbps", "Tbps"]
        var x = value, i = 0
        while x >= 1000 && i < units.count - 1 { x /= 1000; i += 1 }
        let digits = (i == 0 || x >= 100) ? "%.0f" : "%.1f"
        return "\(String(format: digits, x)) \(units[i])"
    }

    /// Byte count, e.g. 7401438 → "7.1 MB".
    static func bytes(_ value: Double?) -> String {
        guard let value, value >= 0 else { return "—" }
        let units = ["B", "KB", "MB", "GB", "TB", "PB"]
        var x = value, i = 0
        while x >= 1024 && i < units.count - 1 { x /= 1024; i += 1 }
        let digits = (i == 0 || x >= 100) ? "%.0f" : "%.1f"
        return "\(String(format: digits, x)) \(units[i])"
    }

    /// Integer percent, e.g. 13 → "13%".
    static func percent(_ value: Int?) -> String {
        guard let value else { return "—" }
        return "\(value)%"
    }
}
