# -*- coding: utf-8 -*-
"""DeepL の年額を自社の条件で出す計算スクリプト（AIディア配布物・2026-10-23 版）

単価は 2026年10月23日に deepl.com/ja/pro（国を「日本 (JPY ¥)」に切り替えた表示）で確認した値。
翻訳ツール・API とも料金ページの注記は「価格には消費税が含まれています」なので、出す額はそのまま税込。
比較用の Google Cloud Translation は cloud.google.com/translate/pricing（2026-10-23）の米ドル・税抜。
単価が変わったら input.json の値だけ直せばよい。

使い方:
  python calculator.py                 # input.json を読んで結果を表示
  python calculator.py --json          # JSON で出力（expected.json と同じ形）
  python calculator.py --input my.json # 自社の条件ファイルを指定
"""
import json
import sys
import math
import argparse
from pathlib import Path

HERE = Path(__file__).resolve().parent


def load(path):
    return json.loads(Path(path).read_text(encoding="utf-8"))


def translator_plan(users, chars_per_user_month, files_per_user_month, prices):
    """翻訳ツール（Web・アプリ）のプランを人数・文字数・ファイル数から選ぶ。
    無料版 50,000字・1ファイル／Individual 300,000字・3ファイル（1人用）／Team 1,000,000字・20ファイル／Business 文字数制限なし・100ファイル。
    返り値: (plan, 年額（年払い・税込）, 年額（月払い・税込）, 理由)"""
    p = prices["translator"]
    reasons = []
    if users <= 1 and chars_per_user_month <= 50000 and files_per_user_month <= 1:
        return ("Free", 0, 0, "1人・月5万字・月1ファイル以内なら無料版の枠に収まる")
    if users <= 1 and chars_per_user_month <= 300000 and files_per_user_month <= 3:
        plan = "Individual"
    elif chars_per_user_month <= 1000000 and files_per_user_month <= 20:
        plan = "Team"
        if users <= 1:
            reasons.append("1人でも月30万字または月3ファイルを超えるので Team の枠が要る（Individual は1人用で上限 30万字・3ファイル）")
    elif files_per_user_month <= 100:
        plan = "Business"
    else:
        plan = "Business"
        reasons.append("月100ファイルを超える分は Enterprise（個別見積もり）か、Team／Business 向けのファイル追加アドオンの検討が要る")
    seats = max(users, 1)
    yearly = p[plan]["yearly_per_user_month"] * seats * 12
    monthly = p[plan]["monthly_per_user_month"] * seats * 12
    if plan in ("Team", "Business") and users < 2:
        reasons.append("料金ページの比較表ではチーム管理は『2名以上のユーザー』の表記")
    return (plan, yearly, monthly, "／".join(reasons) if reasons else "人数・文字数・ファイル数が枠に収まる最小のプラン")


def api_growth(chars_per_month, prices):
    """DeepL API Growth の年額（税込）。年払いは年1,200万字・月払いは月100万字が含まれ、超過は 100万字あたり ¥2,750。
    Growth の上限は月5,000万字（超えるなら Enterprise API）。"""
    a = prices["api_growth"]
    over_unit = a["overage_per_million_chars"]
    yearly_chars = chars_per_month * 12
    # 年払い: 年間プール 1,200万字
    over_y = max(0, yearly_chars - a["yearly_included_chars"])
    cost_y = a["yearly_total"] + math.ceil(over_y / 1_000_000) * over_unit
    # 月払い: 月100万字
    over_m = max(0, chars_per_month - a["monthly_included_chars"])
    cost_m = (a["monthly_fee"] + math.ceil(over_m / 1_000_000) * over_unit) * 12
    note = ""
    if chars_per_month > a["monthly_cap_chars"]:
        note = "月5,000万字を超えるので Growth の上限外。Enterprise API（個別見積もり）"
    return cost_y, cost_m, note


def google_translate(chars_per_month, prices, fx):
    """Google Cloud Translation（NMT のテキスト翻訳）の年額。月50万字まで無料（$10 クレジット）、超過 $20／100万字。米ドル・税抜。"""
    g = prices["google_cloud_translation"]
    over = max(0, chars_per_month - g["free_chars_per_month"])
    usd_month = over / 1_000_000 * g["usd_per_million_chars"]
    usd_year = usd_month * 12
    jpy_year_ex_tax = usd_year * fx
    return round(usd_year, 2), round(jpy_year_ex_tax), round(jpy_year_ex_tax * 1.10)


def run(inp):
    prices = inp["prices"]
    fx = inp.get("fx_jpy_per_usd", 150)
    out = {"confirmed_on": prices["confirmed_on"], "fx_jpy_per_usd": fx, "translator": [], "api": []}
    for s in inp["translator_scenarios"]:
        plan, y, m, why = translator_plan(s["users"], s["chars_per_user_month"], s["files_per_user_month"], prices)
        out["translator"].append({
            "name": s["name"], "users": s["users"], "chars_per_user_month": s["chars_per_user_month"],
            "files_per_user_month": s["files_per_user_month"], "plan": plan,
            "yearly_billing_jpy_incl_tax": y, "monthly_billing_jpy_incl_tax": m,
            "saving_yearly_vs_monthly_jpy": m - y, "why": why,
        })
    for s in inp["api_scenarios"]:
        cy, cm, note = api_growth(s["chars_per_month"], prices)
        gu, gj, gjt = google_translate(s["chars_per_month"], prices, fx)
        out["api"].append({
            "name": s["name"], "chars_per_month": s["chars_per_month"],
            "deepl_growth_yearly_billing_jpy_incl_tax": cy, "deepl_growth_monthly_billing_jpy_incl_tax": cm,
            "deepl_note": note,
            "google_cloud_translation_usd_per_year_ex_tax": gu,
            "google_cloud_translation_jpy_per_year_ex_tax_at_fx": gj,
            "google_cloud_translation_jpy_per_year_incl_10pct_tax_at_fx": gjt,
        })
    return out


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--input", default=str(HERE / "input.json"))
    ap.add_argument("--json", action="store_true")
    a = ap.parse_args()
    inp = load(a.input)
    out = run(inp)
    if a.json:
        print(json.dumps(out, ensure_ascii=False, indent=1))
        return
    print(f"単価の確認日 {out['confirmed_on']} / 為替の前提 1ドル {out['fx_jpy_per_usd']} 円（Google の円換算にだけ使う）")
    print("\n■ 翻訳ツール（Web・アプリ）年額・税込")
    for r in out["translator"]:
        print(f"- {r['name']}: {r['users']}人・1人あたり月{r['chars_per_user_month']:,}字・月{r['files_per_user_month']}ファイル → {r['plan']}"
              f" 年払い {r['yearly_billing_jpy_incl_tax']:,}円 / 月払い {r['monthly_billing_jpy_incl_tax']:,}円（差 {r['saving_yearly_vs_monthly_jpy']:,}円）")
        print(f"    理由: {r['why']}")
    print("\n■ API（DeepL API Growth・税込）と Google Cloud Translation（米ドル・税抜）")
    for r in out["api"]:
        print(f"- {r['name']}: 月{r['chars_per_month']:,}字 → DeepL Growth 年払い {r['deepl_growth_yearly_billing_jpy_incl_tax']:,}円 / 月払い {r['deepl_growth_monthly_billing_jpy_incl_tax']:,}円"
              f" ｜ Google ${r['google_cloud_translation_usd_per_year_ex_tax']:,}/年（税抜）＝約{r['google_cloud_translation_jpy_per_year_ex_tax_at_fx']:,}円（税抜）・税込換算 約{r['google_cloud_translation_jpy_per_year_incl_10pct_tax_at_fx']:,}円")
        if r["deepl_note"]:
            print(f"    注: {r['deepl_note']}")


if __name__ == "__main__":
    main()
