# -*- coding: utf-8 -*-
"""Box AI の年額（税込）と、月の AI ユニットの過不足を同じ条件で出す計算スクリプト（配布物の元・2026-10-25）。
価格は 2026-10-25 に box.com/ja-jp/pricing、含まれるユニットは docs.box.com、消費量は Box の共有リンク cloud.app.box.com/v/box-ai-units-consumption-jp の消費量表 PDF（2026-09-23 版）で確認した値。
出典は README.md。標準ライブラリのみ・外部送信なし・Python 3.8 以上。
usage: python calculator.py input.json [--json]
       python calculator.py --grid-csv monthly.csv
"""
import csv
import json
import sys
import unicodedata
from pathlib import Path

if sys.stdout.encoding and sys.stdout.encoding.lower() != "utf-8":
    sys.stdout.reconfigure(encoding="utf-8")

PRICES_CHECKED = "2026-10-25"
CONSUMPTION_TABLE = "2026-09-23"
ASK = "要問合せ"
MIN_SEATS = 3  # 最低購入ユーザー数

# 1ユーザー/月の税込価格（オンライン購入の価格）。年払いは公式の表示額をそのまま使う（月払いから5%引きを自分で計算しない）。
# None は金額の表示が無いもの。年額は「要問合せ」で返す。
# included_units は「プランに含まれる1か月あたりの AI ユニット」。未使用分は翌月に繰り越されない。
PLANS = {
    "Business": {
        "月払い": 2085, "年払い": 1980, "included_units": 0,
        "price_note": {}, "units_note": "含まれるユニットは0（購入可能）",
    },
    "Business Plus": {
        "月払い": 3474, "年払い": 3300, "included_units": 0,
        "price_note": {}, "units_note": "含まれるユニットは0（購入可能）",
    },
    "Enterprise": {
        "月払い": 4864, "年払い": 4620, "included_units": 1000,
        "price_note": {}, "units_note": "",
    },
    "Enterprise Plus": {
        "月払い": None, "年払い": 6600, "included_units": 2000,
        "price_note": {"月払い": "Enterprise Plus の月払いは料金ページに価格の表示が無い"}, "units_note": "",
    },
    "Enterprise Advanced": {
        "月払い": None, "年払い": None, "included_units": 20000,
        "price_note": {
            "月払い": "Enterprise Advanced は料金ページに金額の表示が無い",
            "年払い": "Enterprise Advanced は料金ページに金額の表示が無い",
        },
        "units_note": "",
    },
}

BILLING = {"月払い": "月払い", "monthly": "月払い", "年払い": "年払い", "annual": "年払い", "yearly": "年払い"}

# 1アクションあたりの消費ユニット（消費量表 2026-09-23 版）。per_tokens があるものはトークン数をその単位で切り上げて数える。
CONSUMPTION = {
    "qa_calls": {
        "label": "Q&A API", "unit": "コール", "per_tokens": None,
        "models": {"standard": 1, "premium": 3},
    },
    "text_gen_calls": {
        "label": "テキスト生成 API", "unit": "コール", "per_tokens": None,
        "models": {"standard": 1, "premium": 3},
    },
    "extract_standard_pages": {
        "label": "抽出エージェント（標準）", "unit": "ページ", "per_tokens": None,
        "models": {"standard": 1, "premium": 3},
    },
    "extract_enhanced_pages": {
        "label": "抽出エージェント（強化）", "unit": "ページ", "per_tokens": None,
        "models": {"premium": 3},
    },
    "enhanced_mode_tokens": {
        "label": "拡張モードのエージェント", "unit": "トークン", "per_tokens": 5000,
        "models": {"standard": 1, "premium": 5, "ultra": 10},
    },
    "automate_tokens": {
        "label": "Automate の Box Agent・カスタムエージェント", "unit": "トークン", "per_tokens": 5000,
        "models": {"standard": 1, "premium": 5, "ultra": 10},
    },
    "metadata_template_tokens": {
        "label": "AI生成メタデータテンプレート", "unit": "トークン", "per_tokens": 5000,
        "models": {"premium": 5},
    },
}
MODEL_LABEL = {"standard": "標準", "premium": "プレミアム", "ultra": "ウルトラ"}

# monthly.csv の早見表
GRID_SEATS = [3, 5, 10, 30, 100]
GRID_PLANS = ["Business", "Business Plus", "Enterprise", "Enterprise Plus"]
GRID_KEYS = ["plan", "billing", "seats", "per_user_month_jpy", "annual_jpy", "included_units_per_month"]


class InputError(ValueError):
    pass


def to_count(v, where, minimum=0):
    if isinstance(v, bool) or not isinstance(v, (int, float)) or int(v) != v or v < minimum:
        raise InputError("{} は {} 以上の整数で入れてください（入力: {!r}）".format(where, minimum, v))
    return int(v)


def units_breakdown(usage):
    if not isinstance(usage, dict):
        raise InputError("usage は {\"qa_calls\": {\"standard\": 600}} のような形で入れてください")
    unknown = [k for k in usage if not k.startswith("_") and k not in CONSUMPTION]
    if unknown:
        raise InputError("usage に知らないキーがあります: {}（使えるキー: {}）".format(", ".join(unknown), ", ".join(CONSUMPTION)))
    rows = []
    for key, spec in CONSUMPTION.items():
        given = usage.get(key) or {}
        if not isinstance(given, dict):
            raise InputError("usage.{} はモデルごとの数（例: {{\"standard\": 100}}）で入れてください".format(key))
        bad = [m for m in given if not m.startswith("_") and m not in spec["models"]]
        if bad:
            raise InputError("usage.{} に使えないモデルがあります: {}（使えるモデル: {}）".format(key, ", ".join(bad), ", ".join(spec["models"])))
        for model, per_unit in spec["models"].items():
            qty = to_count(given.get(model, 0), "usage.{}.{}".format(key, model))
            if qty == 0:
                continue
            per_tokens = spec["per_tokens"]
            if per_tokens:
                blocks = -(-qty // per_tokens)  # 切り上げ
                per = "{:,}{}".format(per_tokens, spec["unit"])
            else:
                blocks = qty
                per = "1{}".format(spec["unit"])
            rows.append({
                "key": key, "item": spec["label"], "model": model, "model_label": MODEL_LABEL[model],
                "quantity": qty, "quantity_unit": spec["unit"], "per": per, "units_per": per_unit,
                "blocks": blocks, "units": blocks * per_unit,
            })
    return rows


def calc(cond):
    plan = cond.get("plan")
    if plan not in PLANS:
        raise InputError("plan は {} のどれかで入れてください（入力: {!r}）".format(" / ".join(PLANS), plan))
    billing = BILLING.get(cond.get("billing"))
    if billing is None:
        raise InputError("billing は 月払い / 年払い（monthly / annual）で入れてください（入力: {!r}）".format(cond.get("billing")))
    seats = to_count(cond.get("seats"), "seats", minimum=1)
    seats_billed = max(MIN_SEATS, seats)
    p = PLANS[plan]
    price = p[billing]
    notes = []
    if seats_billed != seats:
        notes.append("最低購入ユーザー数が{}名のため、{}名でも{}名分で計算".format(MIN_SEATS, seats, MIN_SEATS))
    if price is None:
        per_user_month = annual = per_user_annual = ASK
        notes.append(p["price_note"][billing] + "（年額は要問合せ）")
    else:
        per_user_month = price
        annual = price * seats_billed * 12
        per_user_annual = annual // seats if annual % seats == 0 else round(annual / seats)
    if p["units_note"]:
        notes.append(p["units_note"])

    rows = units_breakdown(cond.get("usage") or {})
    required = sum(r["units"] for r in rows)
    included = p["included_units"]
    diff = included - required
    if diff < 0:
        status = "不足"
        units_note = "{:,}ユニット不足。追加購入が要る（単価は要問合せ）".format(-diff)
    elif diff > 0:
        status = "余剰"
        units_note = "{:,}ユニット余る（未使用分は翌月に繰り越されない）".format(diff)
    else:
        status = "過不足なし"
        units_note = "過不足なし"

    label = cond.get("label") or "{}席 {} {}".format(seats, plan, billing)
    return {
        "label": label,
        "plan": plan,
        "billing": billing,
        "seats": seats,
        "seats_billed": seats_billed,
        "per_user_month_jpy": per_user_month,
        "annual_jpy": annual,
        "per_user_annual_jpy": per_user_annual,
        "included_units_per_month": included,
        "required_units_per_month": required,
        "units_diff": diff,
        "shortfall_units": max(0, -diff),
        "surplus_units": max(0, diff),
        "units_status": status,
        "units_note": units_note,
        "breakdown": rows,
        "notes": notes,
    }


def run(cfg):
    conds = cfg.get("conditions")
    if not isinstance(conds, list) or not conds:
        raise InputError("input.json に conditions（条件のリスト）を入れてください")
    results = []
    for i, c in enumerate(conds, 1):
        try:
            results.append(calc(c))
        except InputError as e:
            raise InputError("条件{}: {}".format(i, e))
    return {
        "prices_checked": PRICES_CHECKED,
        "consumption_table": CONSUMPTION_TABLE,
        "tax": "税込",
        "results": results,
    }


def text_width(s):
    return sum(2 if unicodedata.east_asian_width(ch) in "WF" else 1 for ch in str(s))


def pad(s, w, right=False):
    s = str(s)
    gap = " " * max(0, w - text_width(s))
    return gap + s if right else s + gap


def yen(v):
    return "{:,}円".format(v) if isinstance(v, int) else v


def print_table(out):
    print("Box AI の料金計算（価格 {} 確認・消費量表 {} 版・{}）".format(out["prices_checked"], out["consumption_table"], out["tax"]))
    for i, r in enumerate(out["results"], 1):
        print()
        print("[{}] {}".format(i, r["label"]))
        head = [
            ("プラン", "{}（{}）".format(r["plan"], r["billing"])),
            ("席数", "{}名（課金 {}名分）".format(r["seats"], r["seats_billed"])),
            ("1人あたり月額", yen(r["per_user_month_jpy"])),
            ("年額", yen(r["annual_jpy"])),
            ("1人あたり年額", yen(r["per_user_annual_jpy"])),
        ]
        for k, v in head:
            print("  " + pad(k, 16) + v)
        print("  AI ユニット（1か月）")
        cols = ["項目", "モデル", "数量", "消費", "ユニット"]
        cells = [[b["item"], b["model_label"], "{:,}{}".format(b["quantity"], b["quantity_unit"]),
                  "{}／{}".format(b["units_per"], b["per"]), "{:,}".format(b["units"])] for b in r["breakdown"]]
        if cells:
            ws = [max(text_width(x) for x in [cols[j]] + [c[j] for c in cells]) for j in range(len(cols))]
            right = [False, False, True, True, True]
            print("    " + "  ".join(pad(cols[j], ws[j], right[j]) for j in range(len(cols))))
            print("    " + "-" * (sum(ws) + 2 * (len(cols) - 1)))
            for c in cells:
                print("    " + "  ".join(pad(c[j], ws[j], right[j]) for j in range(len(cols))))
        else:
            print("    （ユニットを消費する利用なし）")
        print("    " + pad("月の必要ユニット", 18) + "{:,}".format(r["required_units_per_month"]))
        print("    " + pad("プランに含まれる", 18) + "{:,}".format(r["included_units_per_month"]))
        print("    " + pad("差", 18) + "{:+,}  {}".format(r["units_diff"], r["units_note"]))
        for n in r["notes"]:
            print("  ※ " + n)
    print()
    print("※ 追加ユニットの単価は公式に公開されていない（要問合せ）ため、不足分は金額にしていない。")
    print("※ UI の Box Agent（標準・Pro）などユニットを消費しない操作は README.md を参照。")


def grid_rows():
    rows = []
    for plan in GRID_PLANS:
        for billing in ("月払い", "年払い"):
            for seats in GRID_SEATS:
                r = calc({"plan": plan, "billing": billing, "seats": seats})
                rows.append({
                    "plan": plan, "billing": billing, "seats": seats,
                    "per_user_month_jpy": r["per_user_month_jpy"], "annual_jpy": r["annual_jpy"],
                    "included_units_per_month": r["included_units_per_month"],
                })
    return rows


def main():
    args = sys.argv[1:]
    try:
        if "--grid-csv" in args:
            i = args.index("--grid-csv")
            if i + 1 >= len(args):
                raise InputError("--grid-csv の後に出力先のファイル名を入れてください")
            dst = Path(args[i + 1])
            rows = grid_rows()
            with dst.open("w", encoding="utf-8-sig", newline="") as f:
                w = csv.DictWriter(f, fieldnames=GRID_KEYS)
                w.writeheader()
                for r in rows:
                    w.writerow(r)
            print("{} に {} 行を書き出しました".format(dst, len(rows)))
            return 0
        files = [a for a in args if not a.startswith("--")]
        inp = Path(files[0]) if files else Path(__file__).with_name("input.json")
        cfg = json.loads(inp.read_text(encoding="utf-8"))
        out = run(cfg)
    except InputError as e:
        print("入力エラー: {}".format(e), file=sys.stderr)
        return 2
    except (OSError, json.JSONDecodeError) as e:
        print("入力ファイルを読めません: {}".format(e), file=sys.stderr)
        return 2
    if "--json" in args:
        print(json.dumps(out, ensure_ascii=False, indent=1))
    else:
        print_table(out)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
