#!/usr/bin/env python3
"""Offline synthetic scenario arithmetic. No network calls or cloud changes.
Rates are supplied assumptions, not a tariff lookup. Compare only alternatives
that pass the same quality, latency and availability requirements.
"""
import json
import sys
from decimal import Decimal, InvalidOperation


def nonnegative(value, label):
    if isinstance(value, bool):
        raise ValueError(label + ' must be a finite nonnegative number')
    try:
        number = Decimal(str(value))
    except InvalidOperation as exc:
        raise ValueError(label + ' must be numeric') from exc
    if not number.is_finite() or number < 0:
        raise ValueError(label + ' must be finite and nonnegative')
    return number


def compare(scenario):
    tokens = scenario['monthly_tokens']
    rates = scenario['usd_per_million_tokens']
    variable = sum(nonnegative(tokens[k], k) * nonnegative(rates[k], k)
                   / Decimal(1_000_000) for k in ('input', 'output'))
    ancillary = nonnegative(scenario['on_demand_ancillary_usd'], 'ancillary')
    alternatives = {}
    for name in ('provisioned_all_in_usd', 'eks_vllm_all_in_usd'):
        fixed = nonnegative(scenario[name], name)
        alternatives[name] = {
            'monthly_usd': str(fixed),
            # Only token usage scales in this intentionally bounded scenario.
            'break_even_workload_multiple': (str((fixed - ancillary) / variable)
                if variable and fixed >= ancillary else None),
            'cheaper_than_current_scenario': fixed < variable + ancillary,
        }
    return {'synthetic': True, 'currency': 'USD',
            'on_demand_monthly_usd': str(variable + ancillary),
            'alternatives': alternatives,
            'limits': 'No throughput, quality, cache, commitment or price verification. '
                      'Null break-even means undefined or outside the nonnegative model.'}


if __name__ == '__main__':
    try:
        with open(sys.argv[1], encoding='utf-8') as source:
            print(json.dumps(compare(json.load(source)), indent=2))
    except (IndexError, OSError, KeyError, TypeError, ValueError) as exc:
        sys.exit('Invalid scenario: ' + str(exc))
