#!/usr/bin/env python3
"""Compare standard Claude API token charges offline. No API calls.

Prices checked 2026-09-23:
https://platform.claude.com/docs/en/about-claude/pricing
The input format is this article's normalized format, not an API response.
All five token counts must be known, non-negative integers.
Excludes fast/batch/region modifiers, tools, hosting, taxes and subscriptions.
"""

import argparse
import json
from decimal import Decimal
from pathlib import Path

FIELDS = ("fresh_input", "cache_write_5m", "cache_write_1h", "cache_read", "output")
RATES = {
    "claude-opus-5": tuple(map(Decimal, ("5", "6.25", "10", "0.50", "25"))),
    "claude-opus-5-5": tuple(map(Decimal, ("4", "5", "8", "0.20", "20"))),
}
MILLION = Decimal("1000000")


def validate_usage(usage):
    if not isinstance(usage, dict) or set(usage) != set(FIELDS):
        raise ValueError("Specify exactly these five fields: " + ", ".join(FIELDS))
    for field in FIELDS:
        if type(usage[field]) is not int or usage[field] < 0:
            raise ValueError(f"{field}: a known, non-negative integer is required")
    return usage


def token_cost(usage, model):
    validate_usage(usage)
    return sum(
        (Decimal(usage[field]) * rate / MILLION
         for field, rate in zip(FIELDS, RATES[model])),
        Decimal("0"),
    )


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("opus5_usage", type=Path)
    parser.add_argument("opus55_usage", type=Path, nargs="?")
    args = parser.parse_args()
    try:
        old_usage = json.loads(args.opus5_usage.read_text(encoding="utf-8"))
        new_usage = (json.loads(args.opus55_usage.read_text(encoding="utf-8"))
                     if args.opus55_usage else old_usage)
        old_cost = token_cost(old_usage, "claude-opus-5")
        new_cost = token_cost(new_usage, "claude-opus-5-5")
    except (OSError, ValueError) as error:
        parser.error(str(error))
    savings = (old_cost - new_cost) / old_cost * 100 if old_cost else None
    print(json.dumps({
        "comparison": ("separate_usage" if args.opus55_usage else "same_usage_price_only"),
        "rates_checked": "2026-09-23",
        "currency": "USD",
        "opus5_token_cost": str(old_cost),
        "opus55_token_cost": str(new_cost),
        "savings_percent": str(savings.quantize(Decimal("0.1"))) if savings is not None else None,
        "scope": "standard API token charges only; not a performance measurement",
    }, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
