# -*- coding: utf-8 -*-
"""Azure OpenAI Service の月額を、公式の単価（100万トークンあたり米ドル）と架空の利用条件から計算する。
使い方: python calculator.py input.json [expected.json]
  expected.json は配布した条件の検算用。自社の値に書き換えたときは付けずに実行する（付けると期待値と一致せず exit 1 になる）。
外部パッケージ不要（Python 3.10 以上）。ネットワーク接続なし。

前提（input.json）:
  - models: モデルごとの Global Standard の単価（input / cached_input / cache_write / output、100万トークンあたり米ドル）。
    2026-10-13 に Azure の価格ページで確認した値。Data Zone は価格ページの各行で Global の 1.1 倍だったので
    deployment_multipliers に 1.1 を置く（Regional Standard の行は GPT-5 系以降のモデルには無い）
  - deployment_multipliers: 処理場所による倍率（global 1.0 / data_zone 1.1）
  - batch_discount: Batch API の割引率（価格ページ: Global Standard の 50% 引き・24時間以内に返す）
  - fx: 円換算に使う為替（3水準）。Azure の円価格は「米ドルを前月末の為替で換算し、その月は固定」なので実際の請求とは一致しない
  - volumes: 月の入力トークン・出力トークン・入力のうちキャッシュから読む割合
  - ptu: プロビジョニング（PTU）の最小構成（Global 15 PTU・$1/PTU/時間、月予約 $260/PTU、年予約 $2,652/PTU）と1か月の時間数
"""
import json
import sys
from pathlib import Path


def calc(inp):
    fx_list = inp["fx"]["jpy_per_usd"]
    mid = fx_list[len(fx_list) // 2]
    rows = []
    for mkey, m in inp["models"].items():
        for vkey, v in inp["volumes"].items():
            cached_share = float(v.get("cached_share", 0.0))
            if not (0.0 <= cached_share <= 1.0):
                raise SystemExit("cached_share must be 0..1")
            in_tok = v["input_tokens"]
            out_tok = v["output_tokens"]
            cached = in_tok * cached_share
            fresh = in_tok - cached
            base_usd = (fresh * m["input"] + cached * m["cached_input"] + out_tok * m["output"]) / 1_000_000
            for dkey, mult in inp["deployment_multipliers"].items():
                usd = base_usd * mult
                rows.append({
                    "model": mkey, "label": m["label"], "volume": vkey, "volume_label": v["label"],
                    "deployment": dkey, "tier": "standard",
                    "usd": round(usd, 2),
                    "jpy": {str(fx): round(usd * fx) for fx in fx_list},
                })
            batch_usd = base_usd * (1.0 - inp["batch_discount"])
            rows.append({
                "model": mkey, "label": m["label"], "volume": vkey, "volume_label": v["label"],
                "deployment": "global", "tier": "batch",
                "usd": round(batch_usd, 2),
                "jpy": {str(fx): round(batch_usd * fx) for fx in fx_list},
            })
    p = inp["ptu"]
    ptu_rows = []
    for dkey, d in p["deployments"].items():
        hourly = d["min_ptu"] * d["usd_per_ptu_hour"] * p["hours_per_month"]
        monthly = d["min_ptu"] * d["usd_per_ptu_month_reservation"]
        yearly = d["min_ptu"] * d["usd_per_ptu_year_reservation"]
        ptu_rows.append({
            "deployment": dkey, "min_ptu": d["min_ptu"],
            "hourly_month_usd": round(hourly, 2), "monthly_reservation_usd": round(monthly, 2),
            "yearly_reservation_usd": round(yearly, 2), "yearly_reservation_per_month_usd": round(yearly / 12, 2),
            "hourly_month_jpy": {str(fx): round(hourly * fx) for fx in fx_list},
            "monthly_reservation_jpy": {str(fx): round(monthly * fx) for fx in fx_list},
            "yearly_reservation_per_month_jpy": {str(fx): round(yearly / 12 * fx) for fx in fx_list},
        })
    return {"rows": rows, "ptu": ptu_rows, "mid_fx": mid}


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()
