#!/usr/bin/env bash
# cost-lib.sh  -  shared token-cost pricing math, sourced by the bash cost
# renderers (phase-tracker.sh, render-agent-log-cost.sh, render-cost-summary.sh).
#
# The single source of the pricing formula for shell callers. Rate DATA still
# lives in cost-table.json; this file owns only the arithmetic so the formula
# is not copy-pasted across scripts.
#
# COST_JQ_DEFS is a jq prelude string callers prepend to their own jq program:
#
#   cost_usd_of($rate; $tin; $tout; $tcached)
#     -> USD for one row given a rate object (or null) and token counts.
#        tokens_in is fresh input (cache-exclusive); tokens_cached is priced at
#        the discounted cacheReadPerMtok rate (falling back to inPerMtok when
#        absent). Returns null when $rate is null.
#   cost_floor_cents($u)
#     -> floor USD to whole cents; null passes through.

COST_JQ_DEFS='
  def cost_usd_of($rate; $tin; $tout; $tcached):
    if $rate == null then null
    else ( ($tin / 1000000) * $rate.inPerMtok
         + ($tcached / 1000000) * ($rate.cacheReadPerMtok // $rate.inPerMtok)
         + ($tout / 1000000) * $rate.outPerMtok )
    end;
  def cost_floor_cents($u):
    if $u == null then null else (($u * 100) | floor) / 100 end;
'
