# -*- coding: utf-8 -*-
"""OpenAI API の月額を、公式の単価（100万トークンあたり米ドル）と架空の利用条件から計算する。
使い方: python calculator.py input.json [expected.json]
  expected.json は配布した条件の検算用。自社の値に書き換えたときは付けずに実行する（付けると期待値と一致せず exit 1 になる）。
外部パッケージ不要（Python 3.10 以上）。ネットワーク接続なし。

前提（input.json）:
  - models: モデルごとの Standard 単価（input / cached_input / cache_write / output と、272K 以上の長文脈 long_*。100万トークンあたり米ドル）。
    2026-10-14 に platform.openai.com/docs/pricing で確認した値。modes はそのモデルで公式の表にある処理モード
  - mode_multipliers: 処理モードの倍率（Standard 1.0 / Batch 0.5 / Flex 0.5 / Fast 2.0 / Ultrafast 6.0）。
    公式の表で GPT-6 Astra・GPT-6.1 Sol・GPT-6 Luna の各列がこの比だったので倍率で持つ（Ultrafast は Astra・6.1 Sol のみ）
  - regional_uplift: 地域処理（データレジデンシー）エンドポイントの上乗せ（2026年3月5日以降のモデル・1.1）
  - fx: 円換算に使う為替（3水準）。請求はカード決済の米ドル建てなので、円は目安
  - prepaid_credit_usd: 前払いクレジットの額。各条件で何か月ぶんに当たるかを出す
  - volumes: 月の入力トークン・出力トークン・入力のうちキャッシュから読む割合・キャッシュ書き込みの割合・長文脈か・地域処理か
  - scenarios: 1条件を固定して1つの要素だけ変えた比較（キャッシュ率・長文脈・地域処理）
入力トークンは uncached（input）・cached（cached_input）・cache write（cache_write）のどれか1つの単価で課金される
（公式: Cache-write pricing is not an additive fee）。cached_share + cache_write_share は 1 以下。
"""
import json
import sys
from pathlib import Path


def cost_usd(model, inp_tok, out_tok, cached_share, write_share, long_context, mode_mult, regional_mult):
    if not (0.0 <= cached_share <= 1.0 and 0.0 <= write_share <= 1.0 and cached_share + write_share <= 1.0):
        raise SystemExit("cached_share + cache_write_share must be within 0..1")
    pre = "long_" if long_context else ""
    p_in = model[pre + "input"]
    p_cached = model[pre + "cached_input"]
    p_write = model[pre + "cache_write"]
    p_out = model[pre + "output"]
    if p_write is None and write_share > 0:
        raise SystemExit("this model has no cache_write price; set cache_write_share to 0")
    cached = inp_tok * cached_share
    written = inp_tok * write_share
    fresh = inp_tok - cached - written
    usd = (fresh * p_in + cached * p_cached + written * (p_write or 0.0) + out_tok * p_out) / 1_000_000
    return usd * mode_mult * regional_mult


def calc(inp):
    fx_list = inp["fx"]["jpy_per_usd"]
    credit = inp["prepaid_credit_usd"]
    rows = []
    for mkey, mdl in inp["models"].items():
        for vkey, v in inp["volumes"].items():
            for mode in mdl["modes"]:
                mult = inp["mode_multipliers"][mode]
                reg = inp["regional_uplift"] if v.get("regional") else 1.0
                usd = cost_usd(mdl, v["input_tokens"], v["output_tokens"], float(v.get("cached_share", 0.0)),
                               float(v.get("cache_write_share", 0.0)), bool(v.get("long_context")), mult, reg)
                rows.append({
                    "model": mkey, "label": mdl["label"], "volume": vkey, "volume_label": v["label"], "mode": mode,
                    "usd": round(usd, 2),
                    "jpy": {str(fx): round(usd * fx) for fx in fx_list},
                    "months_per_credit": round(credit / usd, 2) if usd > 0 else None,
                })
    scen = []
    for skey, s in inp.get("scenarios", {}).items():
        mdl = inp["models"][s["model"]]
        v = inp["volumes"][s["volume"]]
        mult = inp["mode_multipliers"][s["mode"]]
        reg = inp["regional_uplift"] if s.get("regional") else 1.0
        usd = cost_usd(mdl, v["input_tokens"], v["output_tokens"], float(s.get("cached_share", 0.0)),
                       float(s.get("cache_write_share", 0.0)), bool(s.get("long_context")), mult, reg)
        scen.append({"scenario": skey, "label": s["label"], "usd": round(usd, 2),
                     "jpy": {str(fx): round(usd * fx) for fx in fx_list}})
    return {"rows": rows, "scenarios": scen}


def main():
    if len(sys.argv) < 2:
        raise SystemExit("usage: python calculator.py input.json [expected.json]")
    inp = json.loads(Path(sys.argv[1]).read_text(encoding="utf-8"))
    res = calc(inp)
    print(json.dumps(res, ensure_ascii=False, indent=1))
    if len(sys.argv) >= 3:
        exp = json.loads(Path(sys.argv[2]).read_text(encoding="utf-8"))
        if exp != res:
            print("MISMATCH with expected.json", file=sys.stderr)
            raise SystemExit(1)
        print("OK: matches expected.json", file=sys.stderr)


if __name__ == "__main__":
    main()
