"""Book what each Claude Agent SDK / Claude Code result actually added.

On Claude Code v2.1.277 and later, a call that resumes (or forks) a session
reports total_cost_usd and model_usage as the session's running totals, with
the earlier calls' spend restored. Booking those numbers per call double-counts.
book_result() books only the difference since the last result you saw.

Keep `ledger` somewhere that survives restarts (a JSON file, a database row):
if it is lost, the next resumed result is booked in full again.

MIT licence. https://neverpaytwice.com/claude-agent-sdk-cost-tracking
"""

MODEL_KEYS = ("inputTokens", "outputTokens", "cacheReadInputTokens",
              "cacheCreationInputTokens", "webSearchRequests", "costUSD")


def _numbers(model_usage):
    """{model: {key: number}} for the summable keys of model_usage."""
    return {m: {k: (u.get(k) or 0) for k in MODEL_KEYS}
            for m, u in (model_usage or {}).items()}


def book_result(ledger, session_id, total_cost_usd, model_usage=None, forked_from=None):
    """What one result message adds to the session, as a dict:
    {"cost_usd": float, "models": {model: {key: delta}}, "note": str or None}.

    ledger      -- dict you keep: session_id -> last running totals seen
    forked_from -- the parent session_id when this session is a fork, because a
                   fork starts from the parent's restored totals
    """
    if total_cost_usd is None:
        return {"cost_usd": 0.0, "models": {}, "note": "no total_cost_usd on this result"}
    empty = {"cost_usd": 0.0, "models": {}}
    last = ledger.get(session_id) or ledger.get(forked_from) or empty
    if total_cost_usd < last["cost_usd"] - 1e-9:
        # A running total never goes down. A zeroed result after a crash does;
        # keep the old baseline so the next result isn't booked twice.
        return {"cost_usd": 0.0, "models": {},
                "note": "running total went down (crash result?); nothing booked"}
    now = _numbers(model_usage) if model_usage is not None else last["models"]
    models = {}
    for m, vals in now.items():
        before = last["models"].get(m, {})
        d = {k: vals[k] - before.get(k, 0) for k in MODEL_KEYS}
        if any(d.values()):
            models[m] = d
    ledger[session_id] = {"cost_usd": total_cost_usd, "models": now}
    return {"cost_usd": total_cost_usd - last["cost_usd"], "models": models, "note": None}
