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 "—" }
        return scaled(value, divisor: 1000, units: ["bps", "kbps", "Mbps", "Gbps", "Tbps"])
    }

    /// Byte count, e.g. 7401438 → "7.1 MB".
    static func bytes(_ value: Double?) -> String {
        guard let value, value >= 0 else { return "—" }
        return scaled(value, divisor: 1024, units: ["B", "KB", "MB", "GB", "TB", "PB"])
    }

    private static func scaled(_ value: Double, divisor: Double, units: [String]) -> String {
        var x = value, i = 0
        while x >= divisor && i < units.count - 1 { x /= divisor; i += 1 }
        // Round at display precision FIRST, then carry to the next unit if rounding
        // reached the ceiling (999.95 kbps → "1000" should read "1.0 Mbps").
        var digits = (i == 0 || x >= 100) ? 0 : 1
        var rounded = (x * pow(10, Double(digits))).rounded() / pow(10, Double(digits))
        if rounded >= divisor && i < units.count - 1 {
            i += 1
            rounded /= divisor
            digits = rounded >= 100 ? 0 : 1
            rounded = (rounded * pow(10, Double(digits))).rounded() / pow(10, Double(digits))
        }
        return "\(String(format: "%.\(digits)f", rounded)) \(units[i])"
    }

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