"""How a token, cost, or duration figure reads in a report cell.

Phase 7 fills the same numbers into two views — the AI-handoff Markdown and
the reader's HTML — so they format here once. A cell that is still null prints
``--`` rather than a zero: ``0`` tokens and ``$0.00`` are what a run that spent
nothing would look like, which is a different claim from "not measured".
"""
from __future__ import annotations

from datetime import datetime
from typing import Any


def format_int(value: Any) -> str:
    if value is None or not isinstance(value, (str, int, float)):
        return "--"
    try:
        return f"{int(value):,}"
    except (TypeError, ValueError):
        return "--"


def format_usd(value: Any) -> str:
    if value is None or not isinstance(value, (str, int, float)):
        return "--"
    try:
        return f"${float(value):.2f}"
    except (TypeError, ValueError):
        return "--"


def duration_ms_from_bounds(started_at: object, ended_at: object) -> int | None:
    """두 ISO 시각 사이의 벽시계 ms. 없거나 파싱 불가면 None."""
    if not isinstance(started_at, str) or not isinstance(ended_at, str):
        return None
    if not started_at or not ended_at:
        return None
    try:
        start = datetime.fromisoformat(started_at.replace("Z", "+00:00"))
        end = datetime.fromisoformat(ended_at.replace("Z", "+00:00"))
    except ValueError:
        return None
    return max(0, int((end - start).total_seconds() * 1000))


def format_duration_ms(value: Any) -> str:
    if value is None or not isinstance(value, (str, int, float)):
        return "--"
    try:
        ms = int(value)
    except (TypeError, ValueError):
        return "--"
    # A negative elapsed time is nonsensical (clock skew between start/end
    # timestamps); divmod would otherwise produce a malformed "-1m 59s".
    if ms < 0:
        return "--"
    total_seconds = ms // 1000
    hours, remainder = divmod(total_seconds, 3600)
    minutes, seconds = divmod(remainder, 60)
    if hours:
        return f"{hours}h {minutes:02d}m {seconds:02d}s"
    return f"{minutes}m {seconds:02d}s"
