#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""AIエージェントの月額を、API 従量と席課金で並べ、従量が席課金を越える件数を出す。

AIディア「AIエージェントの費用」（2026-11-20）の配布物。記事内の判定欄（#ai-agent-cost-check）と同じ式。
標準ライブラリのみ・外部送信なし・ファイルも書かない。

  API 従量の月額 = 月の処理件数 × (1件の入力トークン × 入力単価 + 1件の出力トークン × 出力単価) ÷ 1,000,000
  席課金の月額   = 人数 × 席の単価
  越える件数     = 席課金の月額 ÷ 1件あたりの従量 を超える最小の件数

使い方:
  python budget_calc.py --items 2000 --preset short --seats 10 --fx 150
  python budget_calc.py --items 10000 --tin 5000 --tout 1500 --seats 30 --fx 155
  python budget_calc.py --items 2000 --preset short --model opus      # 別の単価の帯で API 従量だけ比べる
  python budget_calc.py --selftest                                     # 記事の数字と一致するかを自己検算する

単価（2026-11-20 に公式ページで取得した本文の表記。税の表記はどれも無い）:
  API（100万トークンあたり・USD）: GPT-6.2 Sol と Claude Sonnet 5.5 が入力 $2・出力 $10（判定欄はこの単価）
  席: ChatGPT Business スタンダードシート ￥3,050（年額課金・円建ての表示）／ Gemini Enterprise Business Edition 25.00 USD（one month term）
  Copilot Studio のクレジット単価は 2026-11-20 の価格ページ本文に無かったため、計算に入れていない。

税: 上の金額はどれも税込・税別の表記が無い。予算が足りなくなる側に見て、10% を足した見込みも出す
    （税別と決めたわけではない）。席と従量の両方に同じ 10% を足すので、越える件数は変わらない。
端数: 円は四捨五入（0.5 は切り上げ）、ドルはセント未満を四捨五入。整数で計算して、判定欄の JavaScript と同じ値にしている。
金額は取得日時点の公式ページの表記で、見積もり額ではありません。契約前に各社のページで確認してください。
"""
import argparse
import sys
from decimal import Decimal

FETCHED = "2026-11-20"

# 1件の目安（仮置き。当メディアの実測ではない）: キー → (表示名, 入力トークン, 出力トークン)
PRESETS = {
    "short": ("短い問い合わせ", 1000, 3000),
    "search": ("資料検索", 5000, 1500),
    "draft": ("長文の下書き", 8000, 4000),
}

# API の単価の帯（100万トークンあたり・セント）: キー → (入力, 出力, 表示名)
MODELS = {
    "sol-sonnet": (200, 1000, "GPT-6.2 Sol・Claude Sonnet 5.5"),        # $2.00 / $10.00
    "luna-haiku": (10, 50, "GPT-6 Luna・Claude Haiku 5.5（プロンプト10万トークン以下）"),  # $0.10 / $0.50
    "terra": (100, 500, "GPT-6.1 Terra"),                              # $1.00 / $5.00
    "opus": (400, 2000, "Claude Opus 5.5"),                            # $4 / $20
    "astra-fable": (800, 4000, "GPT-6.2 Astra・Claude Fable 5.2"),     # $8 / $40
}
DEFAULT_MODEL = "sol-sonnet"   # 判定欄で使う単価

CGPT_SEAT_YEN = 3050    # ChatGPT Business スタンダードシート「￥3,050」「から」（$20/ 月年額課金の場合）
GEM_SEAT_USD = 25       # Gemini Enterprise Business Edition: Subscription Prepay - one month term「25.00 USD per 1 month」

MAX_ITEMS = 1_000_000
MAX_TOKENS = 100_000
MAX_SEATS = 100_000


def fmt_int(n):
    return f"{int(n):,}"


def half_up_div(num, den):
    """整数どうしの割り算を四捨五入（0.5 は切り上げ）。num, den は 0 以上。"""
    return (num + den // 2) // den


def tax10(yen):
    """円に 10% を足した見込み（四捨五入）。"""
    return half_up_div(yen * 11, 10)


def dec_str(num, scale):
    """num / 10**scale を末尾の0を落とした10進の文字列にする（判定欄の toFixed→末尾削除と同じ）。"""
    d = (Decimal(num) / (Decimal(10) ** scale)).normalize()
    s = format(d, "f")
    return s


def usd_from_cents(cents):
    return f"{cents // 100:,}.{cents % 100:02d}"


def calc(items, tin, tout, seats, fx, model=DEFAULT_MODEL):
    """判定欄と同じ式。金額はすべて整数で持つ。pu は 1件あたりの費用（1e-8 USD 単位）。"""
    rin, rout, label = MODELS[model]
    pu = tin * rin + tout * rout                       # 1e-8 USD（セント/100万トークン × トークン）
    r = {"items": items, "tin": tin, "tout": tout, "seats": seats, "fx": fx, "model": model, "label": label, "pu": pu}
    r["per_usd"] = dec_str(pu, 8)                       # 1件のドル
    r["per_yen"] = dec_str(pu * fx, 8)                  # 1件の円
    r["api_cents"] = half_up_div(items * pu, 1_000_000)
    r["api_usd"] = usd_from_cents(r["api_cents"])
    r["api_yen"] = half_up_div(items * pu * fx, 100_000_000)
    r["api10"] = half_up_div(items * pu * fx * 11, 1_000_000_000)
    r["cgpt"] = CGPT_SEAT_YEN * seats
    r["cgpt10"] = tax10(r["cgpt"])
    r["gem_usd"] = GEM_SEAT_USD * seats
    r["gem_yen"] = GEM_SEAT_USD * seats * fx
    r["gem10"] = tax10(r["gem_yen"])
    # 越える件数: items × pu × fx / 1e8 > 席の円 を満たす最小の items
    r["cross_cgpt"] = (CGPT_SEAT_YEN * seats * 100_000_000) // (pu * fx) + 1
    r["cross_gem"] = (GEM_SEAT_USD * seats * 100_000_000) // pu + 1
    r["msg"] = message(r)
    return r


def message(r):
    """判定欄が画面に出す文と同じ文（単価が判定欄と同じ sol-sonnet のとき完全一致）。"""
    n = fmt_int
    items, seats, fx = r["items"], r["seats"], r["fx"]
    head = r["label"] if r["model"] != DEFAULT_MODEL else "GPT-6.2 Sol・Claude Sonnet 5.5"
    rin, rout, _ = MODELS[r["model"]]
    msg = ("API 従量（" + head + "、入力 $" + dec_str(rin, 2) + "・出力 $" + dec_str(rout, 2) + "／100万トークン）: 1件 $"
           + r["per_usd"] + "（" + str(fx) + "円換算 " + r["per_yen"] + "円）、月 " + n(items) + " 件で $" + r["api_usd"]
           + "（" + n(r["api_yen"]) + "円、10%を足すと " + n(r["api10"]) + "円）。")
    msg += (" 席課金 " + n(seats) + " 人: ChatGPT Business スタンダードシート " + n(r["cgpt"]) + "円（10%を足すと "
            + n(r["cgpt10"]) + "円）、Gemini Enterprise Business Edition $" + n(r["gem_usd"]) + "（" + n(r["gem_yen"])
            + "円、10%を足すと " + n(r["gem10"]) + "円）。")
    msg += (" 従量が席課金の月額を越えるのは、ChatGPT Business なら月 " + n(r["cross_cgpt"])
            + " 件から、Gemini Enterprise Business なら月 " + n(r["cross_gem"])
            + " 件から（税は両方に同じ10%を足すので件数は変わりません）。")
    over_c = items >= r["cross_cgpt"]
    over_g = items >= r["cross_gem"]
    if over_c and over_g:
        msg += " 今の月 " + n(items) + " 件は、両方の席課金の月額を越えています。"
    elif over_c:
        msg += " 今の月 " + n(items) + " 件は、ChatGPT Business の席課金の月額を越え、Gemini Enterprise Business の手前です。"
    elif over_g:
        msg += " 今の月 " + n(items) + " 件は、Gemini Enterprise Business の席課金の月額を越え、ChatGPT Business の手前です。"
    else:
        msg += " 今の月 " + n(items) + " 件は、どちらの席課金の月額にも届いていません。"
    if seats < 2 or seats > 200:
        msg += " ChatGPT Business の公式の対象は従業員2～200人のチームです。"
    msg += " Copilot Studio は2026年11月20日の価格ページ本文でクレジット単価を確認できなかったため、換算していません。"
    msg += (" 席は人数で決まり件数では増えませんが利用枠に上限があり、従量は件数に比例します。"
            "どちらが安いかではなく、件数がどこで席課金の月額を越えるかの目安です"
            "（単価は2026年11月20日の公式ページ、1件のトークン数は入力した値）。")
    return msg


def validate(items, tin, tout, seats, fx):
    if not (1 <= items <= MAX_ITEMS):
        return "月の処理件数は 1〜1,000,000 で入れてください"
    if not (0 <= tin <= MAX_TOKENS and 0 <= tout <= MAX_TOKENS) or tin + tout < 1:
        return "1件の入力・出力トークンはそれぞれ 0〜100,000（合計1以上）で入れてください"
    if not (1 <= seats <= MAX_SEATS):
        return "人数は 1〜100,000 で入れてください"
    if fx not in (145, 150, 155):
        return "為替は 145・150・155 のどれかで入れてください（記事と同じ3水準）"
    return None


def report(r):
    lines = [
        f"単価（{FETCHED} 取得の公式ページ・税の表記なし）: {r['label']}",
        f"1件: 入力 {fmt_int(r['tin'])}・出力 {fmt_int(r['tout'])} トークン → ${r['per_usd']}（{r['fx']}円換算 {r['per_yen']}円）",
        f"API 従量 月 {fmt_int(r['items'])} 件: ${r['api_usd']} ／ {fmt_int(r['api_yen'])}円 ／ 10%を足した見込み {fmt_int(r['api10'])}円",
        f"ChatGPT Business スタンダードシート {fmt_int(r['seats'])}席: {fmt_int(r['cgpt'])}円 ／ 10%を足した見込み {fmt_int(r['cgpt10'])}円",
        f"Gemini Enterprise Business Edition {fmt_int(r['seats'])}人: ${fmt_int(r['gem_usd'])} ／ {fmt_int(r['gem_yen'])}円 ／ 10%を足した見込み {fmt_int(r['gem10'])}円",
        f"従量が越える件数: ChatGPT Business 月 {fmt_int(r['cross_cgpt'])} 件から ／ Gemini Enterprise Business 月 {fmt_int(r['cross_gem'])} 件から",
        "",
        "判定欄と同じ文:",
        r["msg"],
    ]
    return "\n".join(lines)


def selftest():
    ok = True

    def check(label, got, want):
        nonlocal ok
        hit = got == want
        ok = ok and hit
        print(f"{'ok' if hit else 'NG'}  {label}: {got!r} (記事: {want!r})")

    # 判定欄の初期値（本文の例）: 月2,000件・短い問い合わせ・10人・150円
    d = calc(2000, 1000, 3000, 10, 150)
    for k, want in [("per_usd", "0.032"), ("per_yen", "4.8"), ("api_usd", "64.00"), ("api_yen", 9600),
                    ("api10", 10560), ("cgpt", 30500), ("cgpt10", 33550), ("gem_usd", 250), ("gem_yen", 37500),
                    ("gem10", 41250), ("cross_cgpt", 6355), ("cross_gem", 7813)]:
        check("例 2,000件 " + k, d[k], want)
    check("例 2,000件 の判定", "どちらの席課金の月額にも届いていません" in d["msg"], True)
    # 図2・図3: 月10,000件と、1件の長さ別
    check("短い問い合わせ 10,000件 10%込み", calc(10000, 1000, 3000, 10, 150)["api10"], 52800)
    check("短い問い合わせ 10,000件 の判定", "両方の席課金の月額を越えています" in calc(10000, 1000, 3000, 10, 150)["msg"], True)
    check("短い問い合わせ 7,000件 の判定", "ChatGPT Business の席課金の月額を越え、Gemini Enterprise Business の手前" in calc(7000, 1000, 3000, 10, 150)["msg"], True)
    s2, s10 = calc(2000, 5000, 1500, 10, 150), calc(10000, 5000, 1500, 10, 150)
    check("資料検索 1件", (s2["per_usd"], s2["per_yen"]), ("0.025", "3.75"))
    check("資料検索 2,000件・10,000件", (s2["api10"], s10["api10"]), (8250, 41250))
    r2, r10 = calc(2000, 8000, 4000, 10, 150), calc(10000, 8000, 4000, 10, 150)
    check("長文の下書き 1件", (r2["per_usd"], r2["per_yen"]), ("0.056", "8.4"))
    check("長文の下書き 2,000件・10,000件", (r2["api10"], r10["api10"]), (18480, 92400))
    # 表2: 単価の帯ごとの短い問い合わせ（1件と月2,000件の10%込み）
    for model, per, want in [("luna-haiku", "0.0016", 528), ("terra", "0.016", 5280), ("sol-sonnet", "0.032", 10560),
                             ("opus", "0.064", 21120), ("astra-fable", "0.128", 42240)]:
        m = calc(2000, 1000, 3000, 10, 150, model)
        check(f"表2 {model}", (m["per_usd"], m["api10"]), (per, want))
    # 表1: 席・パックの1人・月（10%を足した見込み）
    check("ChatGPT Business ￥3,050 +10%", tax10(3050), 3355)
    check("ChatGPT Business ￥15,250 +10%", tax10(15250), 16775)
    check("Gemini Business 25 USD 145/150/155 +10%", [tax10(25 * fx) for fx in (145, 150, 155)], [3988, 4125, 4263])
    check("Gemini Business 3,700 JPY +10%", tax10(3700), 4070)
    check("Gemini Standard 35 USD 150 +10%", tax10(35 * 150), 5775)
    check("Microsoft 365 Copilot ¥4,497 +10%", tax10(4497), 4947)
    check("Copilot Studio ¥29,985 +10%", tax10(29985), 32984)
    check("Dify Professional $590/年 150円 +10%", tax10(590 * 150), 97350)
    # 為替を変えても Gemini の越える件数は変わらない（両方ドル建て）
    check("為替145 の越える件数", (calc(2000, 1000, 3000, 10, 145)["cross_cgpt"], calc(2000, 1000, 3000, 10, 145)["cross_gem"]), (6574, 7813))
    check("為替155 の越える件数", (calc(2000, 1000, 3000, 10, 155)["cross_cgpt"], calc(2000, 1000, 3000, 10, 155)["cross_gem"]), (6150, 7813))
    # 境界: ちょうど席の月額と同じになる件数は「越える」に入れない
    b = calc(1, 1000, 3000, 1, 150)
    check("越える件数の境界（1人: 3,050 ÷ 4.8 = 635.4…）", b["cross_cgpt"], 636)
    check("入力チェック（件数0）", validate(0, 1000, 3000, 10, 150) is not None, True)
    check("入力チェック（トークン0・0）", validate(10, 0, 0, 10, 150) is not None, True)
    print("selftest:", "PASS" if ok else "FAIL")
    return 0 if ok else 1


def main():
    p = argparse.ArgumentParser(description="AIエージェントの月額（API 従量と席課金）と、従量が席課金を越える件数（2026-11-20 取得の単価）")
    p.add_argument("--items", type=int, help="月の処理件数")
    p.add_argument("--preset", choices=sorted(PRESETS), help="1件の目安（short=入力1,000・出力3,000／search=5,000・1,500／draft=8,000・4,000）")
    p.add_argument("--tin", type=int, help="1件の入力トークン（--preset より優先）")
    p.add_argument("--tout", type=int, help="1件の出力トークン（--preset より優先）")
    p.add_argument("--seats", type=int, default=10, help="席課金で使う人数")
    p.add_argument("--fx", type=int, default=150, choices=[145, 150, 155], help="1ドルあたりの円")
    p.add_argument("--model", choices=sorted(MODELS), default=DEFAULT_MODEL, help="API の単価の帯（判定欄は sol-sonnet）")
    p.add_argument("--selftest", action="store_true", help="記事の数字と一致するか自己検算する")
    a = p.parse_args()
    if a.selftest:
        return selftest()
    if a.items is None:
        p.error("--items（月の処理件数）を入れてください")
    tin, tout = PRESETS[a.preset or "short"][1:]
    if a.tin is not None:
        tin = a.tin
    if a.tout is not None:
        tout = a.tout
    err = validate(a.items, tin, tout, a.seats, a.fx)
    if err:
        p.error(err)
    print(report(calc(a.items, tin, tout, a.seats, a.fx, a.model)))
    return 0


if __name__ == "__main__":
    sys.exit(main())
