#!/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_usd <rate-json> <tin> <tout> [tcached]  -  scalar convenience wrapper
# that prints the raw (unrounded) USD via jq. Prints nothing when jq is absent.

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;
'

cost_usd() {
  local rate="$1" tin="$2" tout="$3" tcached="${4:-0}"
  command -v jq >/dev/null 2>&1 || return 0
  jq -n \
    --argjson rate "$rate" \
    --argjson tin "$tin" \
    --argjson tout "$tout" \
    --argjson tcached "$tcached" \
    "$COST_JQ_DEFS"'
    cost_usd_of($rate; $tin; $tout; $tcached)'
}
