"""Persistent token usage and estimated cost widget for the ALiCE TUI."""

from __future__ import annotations

from textual.reactive import reactive
from textual.widgets import Static

# Default pricing — Sonnet-class models ($ per 1M tokens).
INPUT_RATE: float = 3.00
OUTPUT_RATE: float = 15.00


class TokenTracker(Static):
    """Persistent header widget showing cumulative token usage and estimated cost.

    Screens update the counters after each Bedrock API call::

        tracker = self.app.query_one(TokenTracker)
        tracker.input_tokens += usage.input
        tracker.output_tokens += usage.output

    Visibility is toggled via the ``$`` keybinding registered on
    ``AliceTUIApp``.
    """

    DEFAULT_CSS = """
    TokenTracker {
        width: 100%;
        height: 1;
        background: #2A1F00;
        color: #FFB000;
        text-align: center;
        dock: top;
    }
    """

    input_tokens: reactive[int] = reactive(0)
    output_tokens: reactive[int] = reactive(0)

    def render(self) -> str:  # noqa: D401
        """Return the formatted token/cost display string."""
        total = self.input_tokens + self.output_tokens
        cost = (self.input_tokens * INPUT_RATE + self.output_tokens * OUTPUT_RATE) / 1_000_000
        return f"▌ ↑{self.input_tokens:,}  ↓{self.output_tokens:,}  Σ{total:,}  ~${cost:.4f} ▐"
