"""Web-UI formatting — cost, tokens, usage display strings.

CRITICAL: Must produce byte-identical strings to the TypeScript version.
"""

from __future__ import annotations

from typing import Any


def format_cost(cost: float) -> str:
    """Format a cost value as a dollar string with 4 decimal places.

    Example: 0.1234 → "$0.1234"
    """
    return f"${cost:.4f}"


def _format_num(num: float) -> str:
    """Format a number with adaptive decimal places, stripping trailing zeros.

    >= 100: no decimals
    >= 10: 1 decimal, strip .0
    >= 1: 2 decimals, strip trailing zeros
    < 1: 3 decimals, strip trailing zeros
    """
    if num >= 100:
        return f"{num:.0f}"
    if num >= 10:
        s = f"{num:.1f}"
        return s.rstrip("0").rstrip(".")
    if num >= 1:
        s = f"{num:.2f}"
        return s.rstrip("0").rstrip(".")
    s = f"{num:.3f}"
    return s.rstrip("0").rstrip(".")


def format_model_cost(cost: dict[str, Any] | None) -> str:
    """Format model cost as input/output dollar string.

    Example: {"input": 3, "output": 15} → "$3/$15"
    Returns "Free" if both zero or missing.
    """
    if not cost:
        return "Free"
    inp = cost.get("input", 0) or 0
    out = cost.get("output", 0) or 0
    if inp == 0 and out == 0:
        return "Free"
    return f"${_format_num(inp)}/${_format_num(out)}"


def format_token_count(count: int) -> str:
    """Format a token count with k suffix.

    < 1000: "123"
    < 10000: "1.2k"
    >= 10000: "12k"
    """
    if count < 1000:
        return str(count)
    if count < 10000:
        return f"{count / 1000:.1f}k"
    return f"{round(count / 1000)}k"


def format_usage(usage: dict[str, Any] | None) -> str:
    """Format usage statistics.

    Produces: "↑123 ↓456 R789 W12 $0.0012"
    """
    if not usage:
        return ""

    parts: list[str] = []
    inp = usage.get("input", 0)
    out = usage.get("output", 0)
    cache_read = usage.get("cacheRead", 0)
    cache_write = usage.get("cacheWrite", 0)
    cost = usage.get("cost", {})
    total = cost.get("total", 0) if cost else 0

    if inp:
        parts.append(f"↑{format_token_count(inp)}")
    if out:
        parts.append(f"↓{format_token_count(out)}")
    if cache_read:
        parts.append(f"R{format_token_count(cache_read)}")
    if cache_write:
        parts.append(f"W{format_token_count(cache_write)}")
    if total:
        parts.append(format_cost(total))

    return " ".join(parts)
