#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Salesforce Agentforce の月の件数・1件のアクション数・人数から、
Flex Credits・会話課金・Agentforceユーザーライセンス（とアドオン）の月額を並べ、
Salesforce Foundations の無料クレジットで何か月分かを出す。

AIディア「Agentforceの料金」（2026-11-26）の配布物。記事内の判定欄（#agentforce-plan-check）と同じ式です。
標準ライブラリのみ・外部送信なし・ファイルも書かない。

  Flex の月の必要クレジット = 月の件数 × 1件のアクション数 × 20（Agentforce Voice のアクションは30）
  Flex の月額               = 必要クレジット × 60,000円 ÷ 100,000（USD は $500 ÷ 100,000）
  会話課金の月額             = 月の件数 × 240円（USD は $2）
  ユーザーライセンスの月額   = 人数 × 600円（USD は $5） ＋ 従業員の Flex の月額
  アドオン                   = 人数 × $125（日本語の料金ページ）／$150（英語の料金ページ）。円の表示なし
  Foundations の月数         = 無料の10万クレジット（日本語ページの FAQ）÷ 月の必要クレジット

  1アクション12円・Voice 18円・解決240円・1件20アクションの境目・円の表示は USD の120倍、は記事の計算です。
  公式が「1ドル120円」と書いているわけではありません。

使い方:
  python budget_calc.py --use customer --conv 600 --acts 3
  python budget_calc.py --use employee --people 10 --ereq 200 --acts 3 --addon
  python budget_calc.py --use both --conv 600 --people 10 --ereq 200 --cur usd
  python budget_calc.py --table       # レートカードの乗数と円換算・公式の月額例5件
  python budget_calc.py --selftest    # 記事の表・判定欄・公式の月額例の数字に一致するかを自己検算する

金額は 2026-11-26 に salesforce.com/jp/agentforce/pricing/（日本語）と英語ページ、
Flex Credits Rate Card（Updated as of August 31, 2026）で取得した表示です。料金ページに税の表記はありません。
土台の Salesforce（Sales Cloud・Service Cloud）の席料、Data 360 などの費用は含みません。
契約前に料金ページと注文書（Order Form）の Usage Details を確かめてください。
"""
import argparse
import sys

FETCHED = "2026-11-26"
YEN_PER_100K, USD_PER_100K = 60000, 500     # 「60,000 円 JPY/100,000クレジットあたり」「$ 500 USD/100,000クレジットあたり」
ACTION, VOICE = 20, 30                        # 「Agentforce アクションは20 Flexクレジット、Agentforce Voiceアクションは30 Flexクレジットです。」
CONV_YEN, CONV_CENTS = 240, 200               # 「240 円 JPY/会話1件あたり」「$ 2 USD/会話1件あたり」
SEAT_YEN, SEAT_CENTS = 600, 500               # 「600 円 JPY/ユーザー/月 (Flexクレジットが必要)」「$ 5」
ADDON_JA, ADDON_EN = 125, 150                 # アドオン「$ 125 user / month」（日本語）・「$ 150 user / month」（英語）
FREE_JA = 100000                              # 「…10万Agentforce Flex Creditが付与されます。」（Foundations 日本語ページの FAQ）
CORE_YEN, CORE_USD = 23400, 195               # Sales Cloud Core「23,400 円 JPY/ユーザー/月 (年間契約)」「$ 195」
RESOLUTION = 400                              # レートカード「Help Agent Resolutions 400」
BREAKEVEN = CONV_YEN * 100000 // (YEN_PER_100K * ACTION)   # 240円 ÷ 12円 = 20（記事の計算）
USE_LABEL = {"customer": "顧客対応", "employee": "従業員向け", "both": "両方"}

# レートカード（本番／Sandbox）。(usage type, 本番, Sandbox, 単位)
RATE_CARD = [
    ("Standard Action", 20, 16, "1アクション"), ("Custom Action", 20, 16, "1アクション"),
    ("Standard Voice Action", 30, 24, "1アクション"), ("Custom Voice Action", 30, 24, "1アクション"),
    ("Starter Prompts", 2, 2, "1プロンプト（2,000トークンごと）"), ("Basic Prompts", 2, 2, "1プロンプト（2,000トークンごと）"),
    ("Standard Prompts", 4, 4, "1プロンプト（2,000トークンごと）"), ("Advanced Prompts", 16, 16, "1プロンプト（2,000トークンごと）"),
    ("Help Agent Resolutions", 400, 0, "1解決"), ("Leads Worked", 400, 320, "1リード"),
    ("Speech to Text", 150, 150, "1時間"), ("Text to Speech", 6000, 6000, "100万文字"), ("Translation", 4000, 4000, "100万文字"),
    ("Slackbot Standard Action", 40, None, "1アクション（Slack Workspace ごと）"), ("Slackbot Advanced Action", 200, None, "1アクション（Slack Workspace ごと）"),
]
# 料金ページの月額例5件。(名前, 1件のアクション数, 1件のクレジット, 「Flex Creditの費用」列の米ドル, 月のクレジット, 月額米ドル)
EXAMPLES = [
    ("例1 カスタマーセルフサービス（注文処理状況）", 2, 40, "0.20", 24000, 120),
    ("例2 サービス（ケース管理）", 3, 60, "0.30", 360000, 1800),
    ("例3 フィールドサービス（予約の日程調整）", 5, 100, "0.50", 60000, 300),
    ("例4 ITサポート（新入社員研修）", 1, 20, "0.10", 2000, 10),
    ("例5 Agentforce音声カスタマーサービス（予約管理）", 4, 120, "0.15", 36000, 180),
]
# 円の表示がある項目と USD（料金ページ・Sales Cloud の販売価格ページ）
YEN_USD = [("Flexクレジット（100,000クレジット）", 60000, 500), ("会話（1件）", 240, 2), ("Agentforceユーザーライセンス", 600, 5),
           ("定額料金でのアクセス", 15000, 125), ("Starter Suite", 3000, 25), ("Pro Suite", 12000, 100),
           ("Core", 23400, 195), ("Advanced", 47400, 395), ("Max", 66000, 550)]


def fi(v):
    return f"{v:,}"


def yen_of(credits):
    """クレジットの円（60,000円/100,000クレジット）。クレジットは10の倍数なので割り切れる。"""
    return credits * 6 // 10


def cents_of(credits):
    """クレジットのセント（$500/100,000クレジット＝0.5セント/クレジット）。クレジットは偶数なので割り切れる。"""
    return credits // 2


def usd(cents):
    d, r = divmod(cents, 100)
    return "$" + fi(d) + ("" if r == 0 else "." + f"{r:02d}")


def money(y, c, cur):
    return fi(y) + "円" if cur == "jpy" else usd(c)


def months_tenths(total):
    """無料の10万クレジットが月の必要クレジットの何か月分か（0.1か月単位・四捨五入）。判定欄と同じ整数の式。"""
    return (2 * FREE_JA * 10 + total) // (2 * total)


def judge(use="customer", conv=600, acts=3, voice=False, people=10, ereq=200, addon=False, cur="jpy"):
    """判定欄と同じ計算。戻り値は dict（各月額と、判定欄に出す文 msg）。"""
    cust = use in ("customer", "both")
    emp = use in ("employee", "both")
    jp = cur == "jpy"
    conds = []
    if cust:
        conds.append("顧客対応 " + fi(conv) + "件/月" + ("（音声）" if voice else ""))
    if emp:
        conds.append("従業員 " + fi(people) + "人・" + fi(ereq) + "件/月" + ("・アドオンも比べる" if addon else ""))
    conds.append("1件 " + str(acts) + "アクション")
    conds.append("表示は円" if jp else "表示は USD")
    msg = "条件: " + "・".join(conds) + "。"
    res = {"use": use}
    total = 0
    if cust:
        per = VOICE if voice else ACTION
        cc = conv * acts * per
        fy, fc = yen_of(cc), cents_of(cc)
        cy, ccn = conv * CONV_YEN, conv * CONV_CENTS
        msg += (" 顧客対応: Flex Credits は " + fi(conv) + "件 × " + str(acts) + "アクション × " + str(per) + "クレジット ＝ 月"
                + fi(cc) + "クレジットで " + money(fy, fc, cur) + "。会話課金は " + fi(conv) + "件 × " + ("240円" if jp else "$2")
                + " ＝ " + money(cy, ccn, cur) + "。")
        dm = money(abs(fy - cy), abs(fc - ccn), cur)
        if voice:
            msg += " この入力での差は " + dm + "。Voice は1アクション30クレジットで、会話課金が音声の通話に当てはまるかは確認できず（2026-11-26）。"
        elif acts == BREAKEVEN:
            msg += " 1件20アクションで、2つの計算は同じ額です（本記事の計算）。"
        else:
            msg += " この入力での差は " + dm + " で、1件あたり20アクションのとき2つの計算は同じ額になります（本記事の計算）。"
        msg += " 解決で払う形（ヘルプエージェントによる解決・$2・400クレジット・円の表示なし）は、解決したセッションだけを数えます。"
        res.update({"cust_credits": cc, "flex_yen": fy, "flex_cents": fc, "conv_yen": cy, "conv_cents": ccn})
        total += cc
    if emp:
        ec = ereq * acts * ACTION
        sy, sc = people * SEAT_YEN, people * SEAT_CENTS
        ey, ecn = yen_of(ec), cents_of(ec)
        msg += (" 従業員向け: Agentforceユーザーライセンスは " + fi(people) + "人 × " + ("600円" if jp else "$5") + " ＝ " + money(sy, sc, cur)
                + " に、Flex Credits " + fi(ereq) + "件 × " + str(acts) + "アクション × 20クレジット ＝ 月" + fi(ec) + "クレジット（"
                + money(ey, ecn, cur) + "）を足して月" + money(sy + ey, sc + ecn, cur) + "。")
        if addon:
            msg += (" 使い放題のアドオンは " + fi(people) + "人 × $125 ＝ $" + fi(people * ADDON_JA) + "（英語ページの $150 なら $"
                    + fi(people * ADDON_EN) + "）。")
            if jp:
                msg += "アドオンに円の表示は無く、USD の120倍で置くと " + fi(people * ADDON_JA * 120) + "円（本記事の仮置き・要確認）。"
        else:
            msg += " 人数分を使い放題にする形は、アドオン（$125/人・英語ページ $150）にチェックを入れると並べます。"
        res.update({"emp_credits": ec, "seat_flex_yen": sy + ey, "seat_flex_cents": sc + ecn,
                    "addon_usd_ja": people * ADDON_JA, "addon_usd_en": people * ADDON_EN})
        total += ec
    if use == "both":
        msg += (" 同じ組織で Flex Credits と会話課金は併用できません（料金ページの FAQ）。顧客対応を会話課金にすると、"
                "Flexクレジットが必要なユーザーライセンスとは同じ組織で組み合わせられない、と読めます（FAQ からの読み取りなので営業担当者に確認）。")
    res["total_credits"] = total
    if total > 0:
        t = months_tenths(total)
        res["free_months"] = f"{t // 10}.{t % 10}"
        msg += (" Foundations の無料10万クレジット（日本語ページの FAQ）は、月" + fi(total) + "クレジットの約" + res["free_months"]
                + "か月分です（同じページの機能一覧は20万、英語ページは200K と、Data 360 と合わせた450k の表記）。")
    msg += (" 土台の Salesforce の席料（Sales Cloud の Core は " + ("23,400円" if jp else "$195") + "/ユーザー/月・年間契約）と、"
            "Data 360 などの費用は含みません。税の表記は料金ページに無く、見積もりは注文書の Usage Details で確かめてください（2026-11-26）。")
    res["msg"] = msg
    return res


def print_table():
    print("レートカード（Updated as of August 31, 2026）の乗数と、本番の円換算（60,000円/100,000クレジット・記事の計算）")
    for name, prod, sb, unit in RATE_CARD:
        y10 = prod * 6  # 円の10倍（0.6円/クレジット）
        print(f"  {name}: 本番 {prod:,}・Sandbox {sb if sb is not None else '-'}（{unit}） → {y10 // 10:,}{'' if y10 % 10 == 0 else '.' + str(y10 % 10)}円")
    print("料金ページの月額例5件（米ドル）")
    for name, a, c, col, mc, m in EXAMPLES:
        print(f"  {name}: {a}アクション・{c}クレジット・列 {col}米ドル・月 {mc:,}クレジット・{m:,}米ドル（円にすると {yen_of(mc):,}円）")


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} (記事: {want})")

    # 記事の計算値
    check("1アクションの円（20クレジット）", yen_of(ACTION), 12)
    check("Voice 1アクションの円（30クレジット）", yen_of(VOICE), 18)
    check("1アクションの USD（$0.10）", usd(cents_of(ACTION)), "$0.10")
    check("Voice 1アクションの USD", usd(cents_of(VOICE)), "$0.15")
    check("解決1件の円（400クレジット）", yen_of(RESOLUTION), 240)
    check("解決1件の USD（比較表の $2 と同じ）", usd(cents_of(RESOLUTION)), "$2")
    check("会話1件と Flex の境目（240円 ÷ 12円）", BREAKEVEN, 20)
    check("1クレジットの USD（$0.005 = 0.5セント）", USD_PER_100K * 100 / 100000, 0.5)
    check("円の表示がある9項目はすべて USD の120倍", sorted(set(y / u for _, y, u in YEN_USD)), [120.0])
    check("円の表示がある項目の数", len(YEN_USD), 9)
    check("アドオンを120倍した仮置き", ADDON_JA * 120, 15000)
    # レートカードの円換算（表3）
    want3 = {"Standard Action": "12", "Standard Voice Action": "18", "Starter Prompts": "1.2", "Standard Prompts": "2.4",
             "Advanced Prompts": "9.6", "Help Agent Resolutions": "240", "Leads Worked": "240", "Speech to Text": "90",
             "Text to Speech": "3,600", "Translation": "2,400"}
    for name, prod, sb, unit in RATE_CARD:
        if name in want3:
            y10 = prod * 6
            got = f"{y10 // 10:,}" + ("" if y10 % 10 == 0 else "." + str(y10 % 10))
            check(f"表3 {name}", got, want3[name])
    # 公式の月額例5件（クレジット・月額・例5の列）
    for name, a, c, col, mc, m in EXAMPLES:
        per = VOICE if "音声" in name else ACTION
        check(f"{name} 1件のクレジット", a * per, c)
        check(f"{name} 月額（クレジット × $500/100,000）", cents_of(mc) // 100, m)
    check("例1 の月のクレジット（40 × 20件 × 30日）", 40 * 20 * 30, 24000)
    check("例2 の月のクレジット（60 × 3件 × 20日 × 100人）", 60 * 3 * 20 * 100, 360000)
    check("例3 の月のクレジット（100 × 3件 × 20日 × 10人）", 100 * 3 * 20 * 10, 60000)
    check("例4 の月のクレジット（20 × 5問 × 20名）", 20 * 5 * 20, 2000)
    check("例5 の月のクレジット（120 × 300通話）", 120 * 300, 36000)
    check("例5 の列（0.15）は Voice 1アクション分", usd(cents_of(VOICE)), "$0.15")
    check("例5 の120クレジットなら0.60米ドル", usd(cents_of(120)), "$0.60")
    check("例1〜4 の列は1件全体の額", [usd(cents_of(c)) for _, a, c, col, mc, m in EXAMPLES[:4]], ["$0.20", "$0.30", "$0.50", "$0.10"])
    check("例1 を円にすると", yen_of(24000), 14400)
    check("例2 を円にすると", yen_of(360000), 216000)
    check("無料10万クレジットは例1 の約4.2か月分", months_tenths(24000), 42)
    check("無料10万クレジットは例2 の1か月に足りない", months_tenths(360000) < 10, True)
    # 当メディアの操作回数を標準アクションに当てた値（記事の計算・別製品）
    check("192回 × 20クレジット", 192 * ACTION, 3840)
    check("343回 × 20クレジット", 343 * ACTION, 6860)
    check("192回 × 12円", yen_of(192 * ACTION), 2304)
    check("343回 × 12円", yen_of(343 * ACTION), 4116)
    check("中央値260回 × 20クレジット・12円", (260 * ACTION, yen_of(260 * ACTION)), (5200, 3120))
    # 判定欄の既定条件
    r = judge()
    check("既定（顧客対応・600件・3アクション）の月のクレジット", r["cust_credits"], 36000)
    check("既定の Flex（円・USD）", (r["flex_yen"], usd(r["flex_cents"])), (21600, "$180"))
    check("既定の会話（円・USD）", (r["conv_yen"], usd(r["conv_cents"])), (144000, "$1,200"))
    check("既定の Foundations の月数", r["free_months"], "2.8")
    check("既定の文（Flex）", "月36,000クレジットで 21,600円" in r["msg"], True)
    check("既定の文（会話）", "600件 × 240円 ＝ 144,000円" in r["msg"], True)
    check("既定の文（差）", "この入力での差は 122,400円" in r["msg"], True)
    r = judge("employee", people=10, ereq=200, acts=3)
    check("従業員10人・200件・3アクション（円）", r["seat_flex_yen"], 13200)
    check("従業員10人・200件・3アクション（USD）", usd(r["seat_flex_cents"]), "$110")
    check("アドオン10人（$125・$150）", (r["addon_usd_ja"], r["addon_usd_en"]), (1250, 1500))
    r = judge("customer", conv=100, acts=20)
    check("1件20アクションで2つは同じ額", (r["flex_yen"], r["conv_yen"]), (24000, 24000))
    check("1件20アクションの文", "2つの計算は同じ額です" in r["msg"], True)
    r = judge("customer", conv=300, acts=4, voice=True, cur="usd")
    check("例5 と同じ条件（300通話・4アクション・Voice）の月額", usd(r["flex_cents"]), "$180")
    r = judge("employee", people=100, ereq=6000, acts=3, cur="usd")
    check("例2 と同じ条件の Flex（月36万クレジット）", r["emp_credits"], 360000)
    check("例2 と同じ条件のライセンス＋Flex（$500 + $1,800）", usd(r["seat_flex_cents"]), "$2,300")
    r = judge("both", conv=600, people=10, ereq=200, acts=3)
    check("両方の合計クレジットと月数", (r["total_credits"], r["free_months"]), (48000, "2.1"))
    check("両方の併用不可の注記", "併用できません" in r["msg"], True)
    print("selftest:", "PASS" if ok else "FAIL")
    return 0 if ok else 1


def main():
    p = argparse.ArgumentParser(description="Agentforce の件数・アクション数・人数から月額を並べる（2026-11-26 取得の料金）")
    p.add_argument("--use", choices=list(USE_LABEL), default="customer", help="customer（顧客対応）／employee（従業員向け）／both（両方）")
    p.add_argument("--conv", type=int, default=600, help="顧客対応の月の会話（リクエスト）件数")
    p.add_argument("--acts", type=int, default=3, help="1件あたりのアクション数（公式の例2は3）")
    p.add_argument("--voice", action="store_true", help="顧客対応が音声（Agentforce Voice・1アクション30クレジット）")
    p.add_argument("--people", type=int, default=10, help="従業員向けに使う人数")
    p.add_argument("--ereq", type=int, default=200, help="従業員向けの月のリクエスト件数（全員の合計）")
    p.add_argument("--addon", action="store_true", help="使い放題のアドオン（$125/人・英語ページ $150）も並べる")
    p.add_argument("--cur", choices=["jpy", "usd"], default="jpy", help="表示の通貨")
    p.add_argument("--table", action="store_true", help="レートカードの乗数と円換算、公式の月額例を出す")
    p.add_argument("--selftest", action="store_true", help="記事の数字と一致するか自己検算する")
    a = p.parse_args()
    if a.selftest:
        return selftest()
    if a.table:
        print_table()
        return 0
    if a.conv < 0 or a.people < 0 or a.ereq < 0 or a.acts < 1:
        p.error("件数と人数は0以上、アクション数は1以上の整数で入れてください")
    r = judge(a.use, a.conv, a.acts, a.voice, a.people, a.ereq, a.addon, a.cur)
    print(r["msg"])
    print(f"（取得日 {FETCHED}・円は料金ページの円の表示による。手数料・税は含まない）")
    return 0


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