from __future__ import annotations

from .numeric import safe_float, safe_int


def duration_phrase(seconds) -> str:
    s = safe_float(seconds, None)
    if s is None or s < 0:
        return "with invalid timing information"
    elif s <= 0.1:
        return "almost instantly"
    elif s <= 1.0:
        return "in just a fraction of a second"
    elif s <= 5.0:
        return "lasting only a few seconds"
    elif s <= 30.0:
        return "lasting several seconds"
    elif s <= 60.0:
        return "lasting close to a minute"
    else:
        return "lasting for minutes"


def bytes_phrase(total_bytes) -> str:
    b = safe_int(total_bytes, None)
    if b is None or b < 0:
        return "with corrupted data size information"
    elif b == 0:
        return "without exchanging data"
    elif b <= 100:
        return "a handful of bytes"
    elif b <= 512:
        return "a small amount of data"
    elif b <= 1024:
        return "a modest payload"
    elif b <= 5120:
        return "a moderate amount of data"
    elif b <= 10240:
        return "a significant volume of data"
    else:
        return "a heavy data transfer"


def packets_phrase(count) -> str:
    c = safe_int(count, None)
    if c is None or c < 0:
        return "with an invalid packet count"
    elif c == 0:
        return "with no packets exchanged"
    elif c <= 3:
        return "over just a couple of packets"
    elif c <= 10:
        return "through a handful of packets"
    elif c <= 50:
        return "spanning dozens of packets"
    elif c <= 500:
        return "over hundreds of packets"
    else:
        return "involving a flood of packets"


def rate_phrase(bytes_rate, packets_rate) -> str:
    br = safe_float(bytes_rate, 0.0)
    pr = safe_float(packets_rate, 0.0)

    def scale_bps(b: float) -> str:
        if b <= 1_000:
            return "very_low"
        elif b <= 10_000:
            return "low"
        elif b <= 100_000:
            return "steady"
        elif b <= 1_000_000:
            return "fast"
        else:
            return "very_intense"

    def scale_pps(p: float) -> str:
        if p <= 1:
            return "very_low"
        elif p <= 10:
            return "low"
        elif p <= 100:
            return "steady"
        elif p <= 1_000:
            return "high"
        else:
            return "very_intense"

    sb, sp = scale_bps(br), scale_pps(pr)
    levels = {sb, sp}

    if levels == {"very_low"}:
        return "at a very slow trickle"
    elif "very_intense" in levels:
        return "at a very intense pace"
    elif "fast" in levels or "high" in levels:
        return "at a fast pace"
    elif "steady" in levels:
        return "at a steady pace"
    else:
        return "at a slow pace"
