# -*- coding: utf-8 -*-
"""音声認識 API（Speech to Text）の月額を同じ条件で出す計算スクリプト（配布物の元・2026-10-24）。
単価は 2026-10-24 に各社の公式ページ・公式 API から取った値（出典は README.md）。標準ライブラリのみ。
usage: python calculator.py [input.json] [--csv out.csv]
"""
import json, sys, csv
from pathlib import Path

if sys.stdout.encoding and sys.stdout.encoding.lower() != "utf-8":
    sys.stdout.reconfigure(encoding="utf-8")

# 1時間あたりの単価。USD は税抜（各社の表示どおり）。AmiVoice は税込表示なので税抜も併記する。
# tier: [(上限分/月, 単価/分), ...] 月間の累積量で段階的に下がるもの（Google V2 Standard・IBM Plus）
PRICES = {
    "Google Cloud Speech-to-Text V2 Standard": {
        "mode": "batch_or_realtime", "currency": "USD",
        "per_min_tiers": [(500_000, 0.016), (1_000_000, 0.010), (2_000_000, 0.008), (None, 0.004)],
        "free_min_per_month": 0,  # V2 の表に無料枠の行は無い（V1 は月60分）
        "unit": "1秒単位に切り上げ",
        "source": "cloud.google.com/speech-to-text/pricing（2026-10-24 静的取得）",
    },
    "Google Cloud Speech-to-Text V2 Dynamic batch": {
        "mode": "batch", "currency": "USD", "per_min": 0.003, "free_min_per_month": 0,
        "unit": "1秒単位に切り上げ", "source": "同上",
    },
    "Azure Speech Standard Real-time": {
        "mode": "realtime", "currency": "USD", "per_hour": 1.00, "free_min_per_month": 0,
        "unit": "秒単位（無料の F0 は月5時間だが別リソースなので S1 の月額から差し引かない）",
        "jpy_per_hour_official": 157.55,
        "source": "azure.microsoft.com/pricing/details/speech/（描画）・Azure Retail Prices API japaneast",
    },
    "Azure Speech Batch": {
        "mode": "batch", "currency": "USD", "per_hour": 0.18, "free_min_per_month": 0,
        "unit": "秒単位（REST API v3.2 以降）", "jpy_per_hour_official": 28.359, "source": "同上",
    },
    "Azure Speech Fast Transcription": {
        "mode": "batch", "currency": "USD", "per_hour": 0.36, "free_min_per_month": 0,
        "unit": "秒単位（REST API 2024-11-15 以降・東日本で提供）", "source": "同上",
    },
    "Amazon Transcribe Batch": {
        "mode": "batch", "currency": "USD", "per_min": 0.006, "free_min_per_month": 60,
        "unit": "1秒単位・最小課金なし（無料枠は最初の12か月）", "source": "aws.amazon.com/jp/transcribe/pricing/ の価格 JSON（2026-09-11 版）",
    },
    "Amazon Transcribe Streaming": {
        "mode": "realtime", "currency": "USD", "per_min": 0.010, "free_min_per_month": 60,
        "unit": "1秒単位・最小課金なし", "source": "同上",
    },
    "OpenAI gpt-transcribe": {
        "mode": "batch", "currency": "USD", "per_min": 0.0045, "free_min_per_month": 0,
        "unit": "音声トークン課金（$/分は公式の目安）", "source": "platform.openai.com/docs/pricing（描画）",
    },
    "OpenAI gpt-4o-mini-transcribe": {
        "mode": "batch", "currency": "USD", "per_min": 0.003, "free_min_per_month": 0,
        "unit": "音声トークン課金（$/分は公式の目安）。公式ガイドで非推奨・2027-02-26 停止予定", "source": "同上",
        "deprecated": "2027-02-26",
    },
    "OpenAI gpt-4o-transcribe / Whisper": {
        "mode": "batch", "currency": "USD", "per_min": 0.006, "free_min_per_month": 0,
        "unit": "音声トークン課金（Whisper は $/分）。公式ガイドで非推奨・2027-02-26 停止予定", "source": "同上",
        "deprecated": "2027-02-26",
    },
    "OpenAI gpt-live-transcribe": {
        "mode": "realtime", "currency": "USD", "per_min": 0.017, "free_min_per_month": 0,
        "unit": "音声トークン課金（$/分は公式の目安）", "source": "同上",
    },
    "IBM Watson Speech to Text Plus": {
        "mode": "batch_or_realtime", "currency": "USD",
        "per_min_tiers": [(999_900, 0.0212), (None, 0.0106)],  # $2.12／100分、10,000単位目（100万分）から $1.06
        "free_min_per_month": 0,  # Lite プランは月500分無料（別プラン）
        "unit": "100分単位の階層（JPY 333.41円／100分）", "jpy_per_min_official": 3.334124,
        "source": "IBM Cloud Global Catalog API（plus プラン pricing）",
    },
    "AmiVoice API 汎用 非同期HTTP（ログ保存なし）": {
        "mode": "batch", "currency": "JPY_incl_tax", "per_hour": 99.0, "free_min_per_month": 60,
        "unit": "1秒単位・発話区間のみ・1秒未満切り捨て（月50円未満は請求なし）",
        "source": "acp.amivoice.com/amivoice_api/price/（税込表示）",
    },
    "AmiVoice API 汎用 WebSocket（ログ保存なし）": {
        "mode": "realtime", "currency": "JPY_incl_tax", "per_hour": 148.5, "free_min_per_month": 60,
        "unit": "同上", "source": "同上",
    },
}

def unit_per_min(p):
    if "per_min" in p:
        return p["per_min"]
    return p["per_hour"] / 60.0

def monthly(name, minutes, apply_free=True, fx=150.0):
    p = PRICES[name]
    m = float(minutes)
    free = p.get("free_min_per_month", 0) if apply_free else 0
    billable = max(0.0, m - free)
    if "per_min_tiers" in p:
        cost, done, prev = 0.0, 0.0, 0
        remaining = billable
        for cap, rate in p["per_min_tiers"]:
            width = (cap - prev) if cap else float("inf")
            take = min(remaining, width)
            cost += take * rate
            remaining -= take
            prev = cap or prev
            if remaining <= 0:
                break
    else:
        cost = billable * unit_per_min(p)
    if p["currency"] == "USD":
        return {"usd": round(cost, 2), "jpy_ex_tax_at_fx": round(cost * fx), "note": f"USD 税抜・{fx:.0f}円換算は税抜"}
    # AmiVoice は税込表示 → 税抜は /1.1
    return {"jpy_incl_tax": round(cost), "jpy_ex_tax": round(cost / 1.1), "note": "税込表示（税抜は 1.1 で割った値）"}

def main():
    args = sys.argv[1:]
    inp = Path(args[0]) if args and not args[0].startswith("--") else None
    cfg = json.loads(inp.read_text(encoding="utf-8")) if inp else {"hours": [100, 500, 2000], "fx": 150, "apply_free": False}
    fx = float(cfg.get("fx", 150))
    rows = []
    for h in cfg["hours"]:
        for name in PRICES:
            r = monthly(name, h * 60, cfg.get("apply_free", False), fx)
            if PRICES[name].get("deprecated"):
                r["note"] = r["note"] + f"・非推奨モデル（{PRICES[name]['deprecated']} 停止予定）"
            rows.append({"hours_per_month": h, "service": name, "mode": PRICES[name]["mode"], **r})
    out = {"fx": fx, "apply_free": cfg.get("apply_free", False), "rows": rows}
    print(json.dumps(out, ensure_ascii=False, indent=1))
    if "--csv" in args:
        dst = Path(args[args.index("--csv") + 1])
        keys = ["hours_per_month", "service", "mode", "usd", "jpy_ex_tax_at_fx", "jpy_incl_tax", "jpy_ex_tax", "note"]
        with dst.open("w", encoding="utf-8-sig", newline="") as f:
            w = csv.DictWriter(f, fieldnames=keys)
            w.writeheader()
            for r in rows:
                w.writerow({k: r.get(k, "") for k in keys})
    return 0

if __name__ == "__main__":
    raise SystemExit(main())
