#!/usr/bin/env python3
# downloaded from berndkuhlen.de
"""Render synthetic session data from stdin. No network, files or credentials."""
import json
import math
import re
import sys


def render(data):
    if not isinstance(data, dict):
        raise ValueError('Expected a JSON object')
    model = data.get('model', 'Example model')
    if not isinstance(model, str):
        raise ValueError('model must be text')
    # Keep terminal escape/control sequences and unbounded text out of the output.
    model = re.sub(r'[^A-Za-z0-9 ._:/+()\-]', '', model)[:64] or 'Example model'
    used = data.get('contextUsedTokens')
    limit = data.get('contextLimitTokens')
    if (type(used) is not int or type(limit) is not int
            or not 0 <= used <= limit <= 1_000_000_000 or limit == 0):
        raise ValueError('Expected valid integer context counts')
    cost = data.get('estimatedCostUsd')
    if (type(cost) not in (int, float) or not math.isfinite(cost)
            or not 0 <= cost <= 1_000_000):
        raise ValueError('Expected a finite non-negative USD cost estimate')
    return f'{model} | context {used / limit:.0%} | est. ${cost:.2f}'


def main():
    if '--help' in sys.argv:
        print('Usage: python3 statusline-example.py < sample-session.json')
        return 0
    try:
        raw = sys.stdin.read(65_537)
        if len(raw) > 65_536:
            raise ValueError('Input exceeds 64 KiB characters')
        print(render(json.loads(raw)))
    except (ValueError, TypeError, OverflowError):
        print('Invalid session data. See the included sample JSON.', file=sys.stderr)
        return 1
    return 0


if __name__ == '__main__':
    sys.exit(main())
