"""Slack の有料プランを、請求対象人数・プラン・支払い周期・新規割引の有無から12か月の支払額に直す。

使い方:
    python calculator.py input.json            # 1条件を計算
    python calculator.py --table annual.csv    # 10・50・100人の一覧を CSV に書く

単価は 2026年11月11日に slack.com/intl/ja-jp/pricing（日本語・ブラウザ描画）で確認した表示額（税別）。
日割り・途中追加のクレジット調整・営業経由の契約条件は含まない。
標準ライブラリだけで動き、外部送信はしない。単価が変わったら PRICES を書き換える。

billing の値:
    annual               通常の年払い（年払い換算の月額 × 人数 × 12）
    monthly              月払い12か月（promo=true で最初の3か月が50%オフ）
    promo_then_annual    割引の3か月を月払いで受け、4か月目から年払いへ切り替えた場合の12か月換算
                         （月払い × 1.5か月分 ＋ 年払い換算 × 9か月分）。切替時の日割り・残額の扱いは
                         公式に記載が無く未確認。年払いへ切り替えた時点で12か月分を前払いするので、
                         最初の12か月の現金支出は cash_first_12m（15か月分）になる
"""
import csv
import json
import sys

PRICES = {
    # プラン: (月払いの1人月額, 年払いの1人月額換算, 月払いに新規割引を適用できるか)
    "pro": (1050, 925, True),
    "business_plus": (2160, 1920, True),
    # Enterprise+ は年払いの表示額のみ。月払いは公式に表示なし（None）。新規割引の対象外。
    "enterprise_plus": (None, 5760, False),
}
PROMO_MONTHS, PROMO_RATE = 3, 0.5  # 新規契約の3か月間50%オフ（料金ページの利用規約・2026-11-11）
TAX_RATE = 0.10  # 消費税の標準税率（国税庁 No.6303・2026-11-11）


def _check(plan: str, people: int) -> tuple:
    if plan not in PRICES:
        raise ValueError("plan は pro / business_plus / enterprise_plus")
    if not isinstance(people, int) or people < 1:
        raise ValueError("people は1以上の整数（契約の請求対象人数）")
    return PRICES[plan]


def yearly(plan: str, people: int, billing: str, promo: bool = False) -> int:
    monthly, annual, promo_ok = _check(plan, people)
    if billing == "annual":
        if promo:
            raise ValueError("年払いに新規割引は適用されない（利用規約）")
        return annual * people * 12
    if billing == "monthly":
        if monthly is None:
            raise ValueError("このプランの月払い額は公式に表示が無い")
        if promo and not promo_ok:
            raise ValueError("このプランは新規割引の対象外")
        months = PROMO_MONTHS * PROMO_RATE + (12 - PROMO_MONTHS) if promo else 12
        return int(round(monthly * people * months))
    if billing == "promo_then_annual":
        if monthly is None or not promo_ok:
            raise ValueError("このプランは新規割引の対象外")
        return int(round(monthly * people * PROMO_MONTHS * PROMO_RATE + annual * people * (12 - PROMO_MONTHS)))
    raise ValueError("billing は annual / monthly / promo_then_annual")


def cash_first_12m(plan: str, people: int) -> int:
    """promo_then_annual で、割引3か月のあと年払い12か月分を前払いした場合の最初の12か月の現金支出（15か月分）。"""
    monthly, annual, promo_ok = _check(plan, people)
    if monthly is None or not promo_ok:
        raise ValueError("このプランは新規割引の対象外")
    return int(round(monthly * people * PROMO_MONTHS * PROMO_RATE + annual * people * 12))


def table(path: str) -> None:
    rows = []
    for plan in ("pro", "business_plus", "enterprise_plus"):
        for people in (10, 50, 100):
            annual = yearly(plan, people, "annual")
            has_monthly = PRICES[plan][0] is not None
            monthly = yearly(plan, people, "monthly") if has_monthly else ""
            promo = yearly(plan, people, "monthly", True) if PRICES[plan][2] else ""
            switch = yearly(plan, people, "promo_then_annual") if PRICES[plan][2] else ""
            rows.append([plan, people, annual, monthly, promo, (annual - promo) if promo != "" else "",
                         switch, int(round(annual * (1 + TAX_RATE)))])
    with open(path, "w", newline="", encoding="utf-8-sig") as fh:
        w = csv.writer(fh)
        w.writerow(["plan", "people", "annual_12m", "monthly_12m", "monthly_promo_first_year",
                    "annual_minus_promo", "promo_then_annual_12m_equiv", "annual_12m_tax_included"])
        w.writerows(rows)
    print("wrote", path, len(rows), "rows")


def main() -> int:
    if len(sys.argv) >= 3 and sys.argv[1] == "--table":
        table(sys.argv[2])
        return 0
    if len(sys.argv) < 2:
        print(__doc__)
        return 1
    with open(sys.argv[1], encoding="utf-8") as fh:
        cfg = json.load(fh)
    total = yearly(cfg["plan"], cfg["people"], cfg["billing"], cfg.get("promo", False))
    out = dict(cfg, yearly_jpy=total, yearly_jpy_tax_included=int(round(total * (1 + TAX_RATE))))
    if cfg["billing"] == "promo_then_annual":
        out["cash_first_12m_jpy"] = cash_first_12m(cfg["plan"], cfg["people"])
    print(json.dumps(out, ensure_ascii=False, indent=2))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
