# -*- coding: utf-8 -*-
"""Gemini API（Gemini Developer API）の月額を、公式の単価（100万トークンあたり米ドル）と架空の利用条件から計算する。
使い方: python calculator.py input.json [expected.json]
  expected.json は配布した条件の検算用。自社の値に書き換えたときは付けずに実行する（付けると期待値と一致せず exit 1 になる）。
外部パッケージ不要（Python 3.10 以上）。ネットワーク接続なし。

前提（input.json）:
  - models: モデルごとの Standard 単価（input / output / cached_input。100万トークンあたり米ドル）。price_until が入っているモデルは
    その日まで *_after でない単価、翌日から *_after の単価が適用される（2026-10-15 に ai.google.dev/gemini-api/docs/pricing で確認）。
    cache_storage_per_1m_tokens_hour は明示的キャッシュの保存料（100万トークン・1時間あたり）。modes はそのモデルで公式の表にあるタブ
  - mode_multipliers: 処理モードの倍率（Standard 1.0 / Batch 0.5 / Flex 0.5 / Priority 1.8 / Contributor 0.5）。
    公式の表で入力・出力の列がこの比だったので倍率で持つ（Contributor は招待制のプレビュー）。
    キャッシュ入力の列はモデルによって倍率が揃わない（Gemini 3.5 Flash-Lite は Standard $0.03 / Batch・Flex $0.02 / Priority $0.05 /
    Contributor $0.015。Gemini 3.1 Pro Preview・2.5 系は Batch・Flex でも Standard と同額）。倍率に乗らないモデルは
    cached_input_by_mode にモード別の実額を書く。無ければ cached_input × 倍率で計算する
  - vertex_non_global_uplift: Vertex AI（Agent Platform）の Non-global エンドポイントの上乗せ（Global の1.1倍）
  - grounding: Google 検索グラウンディングの無料枠（月5,000件・Gemini 3 以降で共有）と超過単価（1,000件あたり $14）
  - fx: 円換算に使う為替（3水準）。価格の表示は米ドルで、請求の通貨は Cloud Billing の設定による。円は目安
  - volumes: 月の入力トークン・出力トークン・入力のうちキャッシュから読む割合
  - scenarios: 1条件を固定して1つの要素だけ変えた比較（期日後・キャッシュ率・キャッシュ保存・グラウンディング・Vertex Non-global）
入力トークンは uncached（input）か cached（cached_input）のどちらか1つの単価で課金される。cached_share は 0〜1。
"""
import json
import sys
from pathlib import Path


def unit_prices(model, after):
    if after and model.get("input_after") is not None:
        return model["input_after"], model["output_after"], model.get("cached_input_after"), model.get("cache_storage_after")
    return model["input"], model["output"], model.get("cached_input"), model.get("cache_storage_per_1m_tokens_hour")


def token_cost(model, inp_tok, out_tok, cached_share, after, mode, mode_mult):
    if not (0.0 <= cached_share <= 1.0):
        raise SystemExit("cached_share must be within 0..1")
    p_in, p_out, p_cached, _ = unit_prices(model, after)
    if cached_share > 0 and p_cached is None:
        raise SystemExit("this model has no cached_input price; set cached_share to 0")
    cached = inp_tok * cached_share
    fresh = inp_tok - cached
    # 入力・出力はモード倍率。キャッシュ入力はモデルがモード別の実額を持てばそれを使う（倍率に乗らないモデルがある）
    by_mode = model.get("cached_input_by_mode")
    if by_mode and not after:
        if mode not in by_mode:
            raise SystemExit("cached_input_by_mode has no price for mode " + mode)
        cached_usd = cached * by_mode[mode] / 1_000_000
    else:
        cached_usd = cached * (p_cached or 0.0) * mode_mult / 1_000_000
    usd = (fresh * p_in + out_tok * p_out) / 1_000_000 * mode_mult
    return usd + cached_usd


def extra_costs(inp, model, s, after):
    _, _, _, p_store = unit_prices(model, after)
    store_usd = 0.0
    if s.get("cache_storage_tokens", 0) and s.get("cache_storage_hours", 0):
        if p_store is None:
            raise SystemExit("this model has no cache storage price")
        store_usd = s["cache_storage_tokens"] / 1_000_000 * s["cache_storage_hours"] * p_store
    g = inp["grounding"]
    req = s.get("grounding_requests", 0)
    over = max(0, req - g["free_requests_per_month"])
    ground_usd = over / 1000 * g["usd_per_1000_requests"]
    return store_usd, ground_usd


def calc(inp):
    fx_list = inp["fx"]["jpy_per_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]
                usd = token_cost(mdl, v["input_tokens"], v["output_tokens"], float(v.get("cached_share", 0.0)), False, mode, mult)
                row = {"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_within_tier1_cap": round(inp["tier1_cap_usd"] / usd, 2) if usd > 0 else None}
                if mdl.get("price_until"):
                    usd_after = token_cost(mdl, v["input_tokens"], v["output_tokens"], float(v.get("cached_share", 0.0)), True, mode, mult)
                    row["usd_after_deadline"] = round(usd_after, 2)
                    row["price_until"] = mdl["price_until"]
                rows.append(row)
    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"]]
        after = bool(s.get("after_deadline"))
        usd = token_cost(mdl, v["input_tokens"], v["output_tokens"], float(s.get("cached_share", 0.0)), after, s["mode"], mult)
        store_usd, ground_usd = extra_costs(inp, mdl, s, after)
        total = usd + store_usd + ground_usd
        if s.get("vertex_non_global"):
            total = total * inp["vertex_non_global_uplift"]
        scen.append({"scenario": skey, "label": s["label"], "tokens_usd": round(usd, 2), "cache_storage_usd": round(store_usd, 2),
                     "grounding_usd": round(ground_usd, 2), "usd": round(total, 2), "jpy": {str(fx): round(total * 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()
