# -*- coding: utf-8 -*-
"""LLMOツール（AIの回答に自社が出るかを計測するツール）12本の月額を、公式の課金単位と自社の条件から出し直す。
出力は ツール名・プラン・月額（表示通貨）・円換算・支払い・契約の条件（月払い／年払い／契約期間）・注記 の表。

使い方:
    python llmo_tool_cost.py input.json expected.json   # 配布条件の検算（期待値と一致すれば exit 0、違えば exit 1）
    python llmo_tool_cost.py input.json                 # 自社の値に書き換えたとき（expected.json は付けない）
    python llmo_tool_cost.py input.json --json          # 結果を表ではなく JSON で出す

input.json:
    prompts         追いたいプロンプト（質問文）の本数
    models          追うAI（モデル・エンジン）の数。include_claude が true なら Claude を含めた数
    days_per_month  1か月の計測日数（毎日なら30）
    include_claude  Claude を追うか（Ahrefs は1更新8 checks、Rankscale は1回2クレジットで計算が変わる）
    fx_jpy_per_usd  円換算の為替（目安。消費税・カード会社の手数料は含まない）

単価は 2026-10-20 に各社の公式料金ページで確認した値（下の「単価」）。公式ページが変わったらここを書き換える。
単位のルールは README.md に公式ページの文言つきで書いてある。
標準ライブラリのみ（Python 3.10 以上）。ネットワーク接続・外部送信なし。
"""
import json
import math
import sys
from decimal import Decimal as D, ROUND_HALF_UP
from pathlib import Path

VERIFIED_ON = "2026-10-20"

# ---------------------------------------------------------------- 単価（2026-10-20 公式確認）
ZIPTIE_PER_CHECK = D("0.01")            # 1プロンプト×1エンジン×1回
ZIPTIE_PER_CHECK_ALL7 = D("0.0087")     # 7エンジン全部
ZIPTIE_ENGINES = 7
AHREFS_PACKAGES = (                     # 単体 Custom prompts（名前, 月額円, 込みの checks, 超過1 checkの円）
    ("Custom prompts Basic", D("7700"), 2500, D("3.08")),
    ("Custom prompts Growth", D("15420"), 7000, D("2.31")),
    ("Custom prompts Scale", D("38500"), 25000, D("1.54")),
)
AHREFS_CLAUDE_CHECKS = 8                # Claude は1更新で8 checks
RANKSCALE_CREDIT = D("0.25")            # 1回の問い合わせ（AI Mode・ChatGPT・Perplexity・Gemini）
RANKSCALE_CREDIT_CLAUDE = D("2")        # Claude は1回2クレジット
RANKSCALE_PLANS = (("Pro", 1200, D("99")), ("Pro+", 3000, D("229")), ("Growth", 5500, D("385")),
                   ("Enterprise", 12000, D("780")))
PEEC_PLANS = (("Starter", 50, D("95"), D("30")), ("Pro", 150, D("245"), D("70")),
              ("Advanced", 350, D("495"), D("140")))   # 名前, プロンプト数, 月額ドル, 追加モデル1つの月額ドル
PEEC_MODELS_INCLUDED = 3
WRITESONIC_PLANS = (("Starter", 50, 50, D("79"), 240), ("Basic", 100, 300, D("199"), 600),
                    ("Growth", 200, 600, D("399"), 1200))  # 名前, プロンプト数, 1日の回答数, 年払いの月額, 月払いとの年の差
SEMRUSH_PLANS = (("Starter", 50, D("199"), D("165.17")), ("Pro+", 100, D("299"), D("248.17")))
SCRUNCH_CORE_PROMPTS = 125
SCRUNCH_CORE_RESPONSES = 5000
SCRUNCH_CORE = D("250")
SCRUNCH_CORE_LLMS = 4
SERANKING_PLANS = (("Core", 100, D("17455"), D("21819")), ("Growth", 250, D("37752"), D("47190")))  # 年払いの月額, 月払い
SERANKING_LLMS = 5                      # Core／Growth の『LLMs to track 5』（名前の列挙なし）
BRANDUP_BASIC, BRANDUP_BASIC_PROMPTS, BRANDUP_BASIC_ADD10 = D("7980"), 10, D("5500")
BRANDUP_PRO, BRANDUP_PRO_PROMPTS, BRANDUP_PRO_ADD10 = D("50000"), 50, D("10000")
HUBSPOT_AEO = D("50")
HUBSPOT_ENGINES = 3
DOLPHINX_PLANS = (("ライト", 20, D("30000"), D("27000")), ("プロ", 50, D("50000"), D("45000")),
                  ("ビジネス", 80, D("100000"), D("85000")))  # 名前, 日次計測プロンプト, 6ヶ月契約の月額, 12ヶ月契約の月額（税別）
SEARCHWRITE_STANDARD = D("100000")      # スタンダードプラン 月額（税抜）
SEARCHWRITE_INITIAL = D("100000")       # 初期費用（月額には含めない）


def n(x):
    """数の表示（3桁区切り・末尾の0を落とす）。"""
    s = format(x, ",f") if isinstance(x, D) else format(x, ",")
    if "." in s:
        s = s.rstrip("0").rstrip(".")
    return s


def money(cur, amt, lower=False):
    q = amt.quantize(D("0.01"), ROUND_HALF_UP)
    s = format(q, ",f") if q != q.to_integral_value() else format(int(q), ",")
    return ("$" if cur == "USD" else "¥") + s + ("〜" if lower else "")


def make(tool, plan, cur, amt, c, basis, notes, terms, lower=False, status=None, detail=None):
    jpy = None
    if amt is not None:
        v = amt * c["fx"] if cur == "USD" else amt
        jpy = int(v.quantize(D("1"), ROUND_HALF_UP))
    return {
        "tool": tool,
        "plan": plan,
        "currency": cur,
        "amount": None if amt is None else str(amt.quantize(D("0.01"), ROUND_HALF_UP)),
        "amount_label": status if amt is None else money(cur, amt, lower),
        "jpy": jpy,
        "jpy_label": None if jpy is None else "¥" + format(jpy, ",") + ("〜" if lower else ""),
        "lower_bound": lower,
        "terms": terms,
        "basis": basis,
        "note": "。".join(x for x in notes if x),
        "detail": detail or {},
    }


def ziptie(c):
    p, m, d = c["prompts"], c["models"], c["days"]
    checks = p * m * d
    rate = ZIPTIE_PER_CHECK_ALL7 if m == ZIPTIE_ENGINES else ZIPTIE_PER_CHECK
    notes = ["7エンジン全部（models=7）なら $0.0087/check", "Listed prices exclude tax."]
    if m > ZIPTIE_ENGINES:
        notes.append("料金ページのエンジンは7つまで")
    if c["claude"]:
        notes.append("Claude が7エンジンに入るかは料金ページに無い")
    basis = "%d×%d×%d＝%s check × $%s" % (p, m, d, n(checks), n(rate))
    return make("ZipTie", "従量", "USD", rate * checks, c, basis, notes, "月払い", detail={"checks": checks})


def hubspot(c):
    notes = ["プロンプト数の枠は料金ページに記載なし（枠に収まるかは判別できない）",
             "監視は week over week（週次）なので「毎日」の条件には合わない"]
    if c["models"] > HUBSPOT_ENGINES or c["claude"]:
        notes.append("AEO の対象は ChatGPT・Perplexity・Gemini の3つ")
    return make("HubSpot AEO", "HubSpot AEO", "USD", HUBSPOT_AEO, c, "固定月額", notes, "月")


def peec(c):
    p, m = c["prompts"], c["models"]
    notes_c = []
    if c["claude"]:
        notes_c.append("Claude が選べるかは料金ページに無い")
    for name, lim, price, extra in PEEC_PLANS:
        if p <= lim:
            add = max(0, m - PEEC_MODELS_INCLUDED)
            basis = "%d prompts ≤ %d・%d models" % (p, lim, m)
            basis += ("（3を超える %d モデル × $%s を加算）" % (add, n(extra))) if add else "（Choose 3 models の枠内）"
            notes = ["追加モデルは月 $%s（年払い）" % n(extra),
                     "選べるのは ChatGPT・AI Mode・AI Overviews・Microsoft Copilot・Gemini・Naver AI。Perplexity は追加モデルか Enterprise"] + notes_c
            return make("Peec AI", name, "USD", price + extra * add, c, basis, notes, "月払い。年払いは15%割引",
                        detail={"extra_models": add})
    return make("Peec AI", "Enterprise", "USD", None, c, "%d prompts > 350（Advanced の枠）" % p, ["Enterprise は要問合せ"] + notes_c,
                "年払い（Annual）", status="要問合せ")


def rankscale(c):
    p, m, d = c["prompts"], c["models"], c["days"]
    if c["claude"]:
        per = RANKSCALE_CREDIT * (m - 1) + RANKSCALE_CREDIT_CLAUDE
        expr = "%d×%d×(0.25×%d＋2)" % (p, d, m - 1)
    else:
        per = RANKSCALE_CREDIT * m
        expr = "%d×%d×0.25×%d" % (p, d, m)
    credits = p * d * per
    notes = ["Claude は1回2クレジット", "Essentials（年払いのみ・月あたり $17）はクレジット数の記載が無いので判定に入れていない"]
    terms = "月払い。年払いは15%割引"
    for name, allow, price in RANKSCALE_PLANS:
        if credits <= allow:
            basis = "%s＝%s クレジット ≤ %s" % (expr, n(credits), n(allow))
            return make("Rankscale", name, "USD", price, c, basis, notes, terms, detail={"credits": n(credits)})
    basis = "%s＝%s クレジット > 12,000（Enterprise）" % (expr, n(credits))
    return make("Rankscale", "枠超過", "USD", None, c, basis, notes, terms, status="枠超過", detail={"credits": n(credits)})


def writesonic(c):
    p, m = c["prompts"], c["models"]
    answers = p * m
    notes = []
    if m > 3 or c["claude"]:
        notes.append("Starter〜Growth の対象は ChatGPT・Gemini・Google AI Overviews（Enterprise は9プラットフォーム）")
    for name, lim_p, lim_a, price, save in WRITESONIC_PLANS:
        if p <= lim_p and answers <= lim_a:
            basis = "%d prompts・%d×%d＝%s answers/日 ≤ %d prompts・%d answers" % (p, p, m, n(answers), lim_p, lim_a)
            monthly = price + D(save) / 12
            terms = "年払いの月あたり。月払いは年 $%s 高い（約 $%s）" % (n(save), n(monthly.quantize(D("0.01"), ROUND_HALF_UP)))
            notes2 = ["約 $%s は $%s ＋ $%s÷12 の計算値（月払い額そのものは料金ページに無い）" % (
                n(monthly.quantize(D("0.01"), ROUND_HALF_UP)), n(price), n(save))] + notes
            return make("Writesonic", name, "USD", price, c, basis, notes2, terms, detail={"answers_per_day": answers})
    basis = "%d prompts・%s answers/日 が Growth（200 prompts・600 answers）を超える" % (p, n(answers))
    return make("Writesonic", "Enterprise", "USD", None, c, basis, notes, "要問合せ", status="要問合せ",
                detail={"answers_per_day": answers})


def semrush(c):
    p = c["prompts"]
    notes = ["models は判定に使わない（料金ページにモデル名の列挙なし）"]
    for name, lim, price, annual in SEMRUSH_PLANS:
        if p <= lim:
            basis = "%d prompts ≤ %d prompts to track daily" % (p, lim)
            return make("Semrush One", name, "USD", price, c, basis, notes, "月払い。年払いは $%s" % n(annual))
    return make("Semrush One", "Advanced", "USD", None, c, "%d prompts > 100（Pro+）" % p,
                ["Advanced は Unlimited prompts・要問合せ"] + notes, "要問合せ", status="要問合せ")


def scrunch(c):
    p, m, d = c["prompts"], c["models"], c["days"]
    resp = p * m * d
    notes = ["Core は 4 LLMs（ChatGPT・Perplexity・Google AIO・Copilot）"]
    if c["claude"] or m > SCRUNCH_CORE_LLMS:
        notes.append("Claude と5つ目以降のモデルは Enterprise（9 LLMs）の対象。Core で足りるかは要確認")
    terms = "支払い周期の記載なし"
    if p <= SCRUNCH_CORE_PROMPTS and resp <= SCRUNCH_CORE_RESPONSES:
        basis = "%d ≤ 125 prompts・%d×%d×%d＝%s ≤ 5,000 responses/月" % (p, p, m, d, n(resp))
        return make("Scrunch AI", "Core", "USD", SCRUNCH_CORE, c, basis, notes, terms, detail={"responses": resp})
    basis = "%d prompts・%s responses/月 が Core（125 prompts・5,000 responses）を超える" % (p, n(resp))
    return make("Scrunch AI", "Enterprise", "USD", None, c, basis, notes, terms, status="要問合せ", detail={"responses": resp})


def ahrefs(c):
    p, m, d = c["prompts"], c["models"], c["days"]
    if c["claude"]:
        checks = p * d * (m - 1) + p * d * AHREFS_CLAUDE_CHECKS
        expr = "%d×%d×%d ＋ Claude %d×%d×8" % (p, m - 1, d, p, d)
    else:
        checks = p * m * d
        expr = "%d×%d×%d" % (p, m, d)
    totals = []
    for name, base, incl, over in AHREFS_PACKAGES:
        extra = max(0, checks - incl)
        totals.append((base + over * extra, name, base, incl, over, extra))
    best = min(totals, key=lambda t: t[0])
    total, name, base, incl, over, extra = best
    if extra:
        basis = "%s＝%s check − %s（込み）＝%s × ¥%s ＝ ¥%s を ¥%s に加算" % (
            expr, n(checks), n(incl), n(extra), n(over), n(over * extra), n(base))
    else:
        basis = "%s＝%s check ≤ %s（込み）" % (expr, n(checks), n(incl))
    others = ["%s なら %s" % (t[1].replace("Custom prompts ", ""), money("JPY", t[0])) for t in totals if t[1] != name]
    notes = ["ほかのパッケージ: " + "・".join(others), "Claude は1更新で8 checks"]
    detail = {"checks": checks, "packages": {t[1]: str(t[0].quantize(D("0.01"))) for t in totals}}
    return make("Ahrefs Brand Radar（単体）", name, "JPY", total, c, basis, notes, "月払い・税抜", detail=detail)


def seranking(c):
    p, m = c["prompts"], c["models"]
    notes = []
    if m > SERANKING_LLMS:
        notes.append("Core／Growth の LLMs to track は5")
    if c["claude"]:
        notes.append("LLM の名前の列挙が無く、Claude が入るかは料金ページで判別できない")
    for name, lim, annual, monthly in SERANKING_PLANS:
        if p <= lim:
            basis = "%d ≤ %d prompts to track daily（LLMs to track 5）" % (p, lim)
            return make("SE Ranking", name, "JPY", annual, c, basis, notes, "年払いの月あたり。月払い ¥%s" % n(monthly))
    basis = "%d prompts > 250（Growth）" % p
    notes.insert(0, "250 を超える分は AI Search アドオン（200 prompts・+¥10,478 年払い／450・1,000 の段階あり）。足し方は料金ページで確認")
    return make("SE Ranking", "Growth＋AI Search アドオン", "JPY", None, c, basis, notes, "年払いの月あたり（アドオンの足し方は要確認）",
                status="要確認")


def brandup(c):
    p = c["prompts"]
    notes = ["models は使わない（プロンプト数とプラットフォーム数の掛け算になるかは料金ページに無い）"]
    terms = "1ヶ月契約"
    if p <= BRANDUP_BASIC_PROMPTS:
        return make("Brand UP", "ベーシック", "JPY", BRANDUP_BASIC, c, "%d ≤ 10 プロンプト" % p, notes, terms)
    if p <= BRANDUP_PRO_PROMPTS:
        k = math.ceil((p - BRANDUP_BASIC_PROMPTS) / 10)
        basic = BRANDUP_BASIC + BRANDUP_BASIC_ADD10 * k
        if basic < BRANDUP_PRO:
            basis = "ベーシック ¥7,980 ＋ プロンプト追加 ¥5,500×%d ＝ ¥%s（プロ ¥50,000 は50件込み）" % (k, n(basic))
            return make("Brand UP", "ベーシック＋プロンプト追加×%d" % k, "JPY", basic, c, basis, notes, terms)
        basis = "ベーシック＋追加 ¥%s ≥ プロ ¥50,000（50件込み）" % n(basic)
        return make("Brand UP", "プロ", "JPY", BRANDUP_PRO, c, basis, notes, terms)
    k = math.ceil((p - BRANDUP_PRO_PROMPTS) / 10)
    total = BRANDUP_PRO + BRANDUP_PRO_ADD10 * k
    basis = "プロ ¥50,000 ＋ プロンプト追加 ¥10,000×%d ＝ ¥%s" % (k, n(total))
    return make("Brand UP", "プロ＋プロンプト追加×%d" % k, "JPY", total, c, basis, notes, terms)


def dolphinx(c):
    p = c["prompts"]
    notes = ["models は判定に使わない（日次計測はライト4種・プロ以上5種、オプションで Claude・Perplexity を足し最大7種）"]
    for name, lim, price, price12 in DOLPHINX_PLANS:
        if p <= lim:
            basis = "%d ≤ %d 本（日次計測プロンプト）" % (p, lim)
            return make("DolphinX AIO", name, "JPY", price, c, basis, notes, "6ヶ月契約・税別。12ヶ月契約なら ¥%s" % n(price12))
    name, lim, price, price12 = DOLPHINX_PLANS[-1]
    basis = "%d 本 > 80 本（ビジネス）。超える分は10本単位で追加（追加の単価は料金ページに無い）" % p
    return make("DolphinX AIO", "ビジネス＋プロンプト追加", "JPY", price, c, basis, notes,
                "6ヶ月契約・税別。12ヶ月契約なら ¥%s（追加分は別）" % n(price12), lower=True)


def searchwrite(c):
    notes = ["LLMOダッシュボード + SEOエージェント・月次レポートを含む", "初期費用 ¥%s は月額に含めていない" % n(SEARCHWRITE_INITIAL)]
    return make("SEARCH WRITE", "スタンダードプラン", "JPY", SEARCHWRITE_STANDARD, c, "固定月額（プロンプト数の記載なし）", notes,
                "12ヶ月契約・初期費用 ¥%s・税抜" % n(SEARCHWRITE_INITIAL))


TOOLS = (ziptie, hubspot, peec, rankscale, writesonic, semrush, scrunch, ahrefs, seranking, brandup, dolphinx, searchwrite)


def load(path):
    inp = json.loads(Path(path).read_text(encoding="utf-8"))

    def need_int(k, lo, hi):
        v = inp.get(k)
        if isinstance(v, bool) or not isinstance(v, int) or not lo <= v <= hi:
            raise SystemExit("input.json: %s must be an integer in %d..%d" % (k, lo, hi))
        return v

    c = {"prompts": need_int("prompts", 1, 100000), "models": need_int("models", 1, 50),
         "days": need_int("days_per_month", 1, 31)}
    if not isinstance(inp.get("include_claude"), bool):
        raise SystemExit("input.json: include_claude must be true or false")
    fx = inp.get("fx_jpy_per_usd")
    if isinstance(fx, bool) or not isinstance(fx, (int, float)) or fx <= 0:
        raise SystemExit("input.json: fx_jpy_per_usd must be a positive number")
    c["claude"] = inp["include_claude"]
    c["fx"] = D(str(fx))
    c["fx_raw"] = fx
    return c


def calc(c):
    cond = {"prompts": c["prompts"], "models": c["models"], "days_per_month": c["days"],
            "include_claude": c["claude"], "fx_jpy_per_usd": c["fx_raw"]}
    return {"verified_on": VERIFIED_ON, "conditions": cond, "rows": [f(c) for f in TOOLS]}


def print_table(res):
    cd = res["conditions"]
    print("条件: %d プロンプト × %d モデル × %d 日／月・Claude %s・1ドル %s 円（単価は %s 公式確認。円換算は目安で消費税・カード手数料を含まない）" % (
        cd["prompts"], cd["models"], cd["days_per_month"], "あり" if cd["include_claude"] else "なし",
        cd["fx_jpy_per_usd"], res["verified_on"]))
    print("| ツール名 | プラン | 月額（通貨） | 円換算 | 支払い・契約の条件 | 注記 |")
    print("|---|---|---:|---:|---|---|")
    for r in res["rows"]:
        note = r["basis"] + ("。" + r["note"] if r["note"] else "")
        print("| %s | %s | %s | %s | %s | %s |" % (r["tool"], r["plan"], r["amount_label"], r["jpy_label"] or "—", r["terms"], note))


def main():
    try:
        sys.stdout.reconfigure(errors="replace")
    except Exception:
        pass
    args = sys.argv[1:]
    files = [a for a in args if not a.startswith("--")]
    if not files:
        raise SystemExit("usage: python llmo_tool_cost.py input.json [expected.json] [--json]")
    res = calc(load(files[0]))
    if "--json" in args:
        print(json.dumps(res, ensure_ascii=False, indent=1))
    else:
        print_table(res)
    if len(files) >= 2:
        exp = json.loads(Path(files[1]).read_text(encoding="utf-8"))
        if exp != res:
            diff = [r["tool"] for r, e in zip(res["rows"], exp.get("rows", [])) if r != e]
            if exp.get("conditions") != res["conditions"]:
                diff.insert(0, "conditions")
            print("MISMATCH with expected.json: " + ", ".join(diff or ["rows"]), file=sys.stderr)
            raise SystemExit(1)
        print("OK: matches expected.json", file=sys.stderr)


if __name__ == "__main__":
    main()
