"""Per-source usage block constructors (consumed by collect())."""
from __future__ import annotations

from .paths import utc_now
from .pricing import (
    claude_billable_equivalent,
    claude_cost_usd,
)


def usage_block(totals: dict, source: str, note: str | None = None) -> dict:
    block = {
        "totalTokens": totals.get("totalTokens", 0) or 0,
        "inputTokens": totals.get("inputTokens", 0) or 0,
        "outputTokens": totals.get("outputTokens", 0) or 0,
        "toolUses": totals.get("toolUses", 0) or 0,
        "durationMs": totals.get("durationMs", 0) or 0,
        "startedAt": totals.get("startedAt"),
        "endedAt": totals.get("endedAt"),
        "source": source,
        "collectedAt": utc_now(),
    }
    for key in ("cacheCreationTokens", "cacheCreation5mTokens", "cacheCreation1hTokens",
                "cacheReadTokens", "cachedInputTokens",
                "reasoningOutputTokens", "cachedTokens", "thoughtsTokens", "toolTokens"):
        if totals.get(key):
            block[key] = totals[key]

    # Billable-equivalent + cost.
    if source == "claude-jsonl":
        cc_1h = totals.get("cacheCreation1hTokens", 0) or 0
        be = claude_billable_equivalent(
            totals.get("inputTokens", 0) or 0,
            totals.get("cacheCreationTokens", 0) or 0,
            totals.get("cacheReadTokens", 0) or 0,
            totals.get("outputTokens", 0) or 0,
            cache_create_1h_t=cc_1h,
        )
        block["billableEquivalentTokens"] = be
        cost = claude_cost_usd(
            totals.get("model"),
            totals.get("inputTokens", 0) or 0,
            totals.get("cacheCreationTokens", 0) or 0,
            totals.get("cacheReadTokens", 0) or 0,
            totals.get("outputTokens", 0) or 0,
            cache_create_1h_t=cc_1h,
        )
        if cost is not None:
            block["estimatedCostUsd"] = cost
        if totals.get("model"):
            block["model"] = totals["model"]
    if note:
        block["note"] = note
    return block


def na_block(reason: str) -> dict:
    return {
        "totalTokens": 0,
        "toolUses": 0,
        "durationMs": 0,
        "startedAt": None,
        "endedAt": None,
        "source": "unavailable",
        "collectedAt": utc_now(),
        "note": reason,
    }

