#!/usr/bin/env python3
"""How far Immersive Translate's BabelDOC token quota goes for one book.

Usage: python3 page_budget.py PAGES [--plan free|pro|max] [--terms] [--limits FILE]

PAGES is the PDF's page count. --terms models automatic term extraction,
which Immersive Translate says roughly doubles the up-front deduction and
raises average use. The script uses only figures Immersive Translate
publishes on its BabelDOC page (see limits.json for sources and the check
date): the monthly token quota, the per-job page cap, the up-front deduction
per page, and the measured P25, mean and P75 tokens per page.

It answers three questions:
  1. Does the book fit in one job, or how many page ranges do you need?
  2. Does the up-front deduction fit in the monthly quota?
  3. How many months of quota does the book use at typical consumption?
These are planning estimates, not a quote. Real use depends on the PDF;
table-dense pages cost more. Scanned PDFs are not supported by BabelDOC.
"""
import json, math, os, sys

def main():
    a = sys.argv[1:]
    if not a or not a[0].isdigit():
        sys.exit(__doc__)
    pages, plan, terms, lim = int(a[0]), "free", False, None
    i = 1
    while i < len(a):
        if a[i] == "--plan" and i + 1 < len(a):
            plan = a[i + 1]; i += 2
        elif a[i] == "--terms":
            terms = True; i += 1
        elif a[i] == "--limits" and i + 1 < len(a):
            lim = a[i + 1]; i += 2
        else:
            sys.exit(f"unknown argument: {a[i]}")
    lim = lim or os.path.join(os.path.dirname(os.path.abspath(__file__)), "limits.json")
    b = json.load(open(lim))["babeldoc"]
    if plan not in b["monthly_tokens"]:
        sys.exit("plan must be free, pro or max")
    key = "terms_on" if terms else "terms_off"
    quota = b["monthly_tokens"][plan]
    caps = b["pages_per_job"]
    cap = caps[plan] if caps.get(plan) else caps["pro"]
    if plan == "max" and not caps.get("max"):
        print("Note: no published per-job cap for Max; using the Pro cap.")
    jobs = math.ceil(pages / cap)
    pre = b["pre_deduct_tokens_per_page"][key]
    m = b["measured_tokens_per_page"][key]
    print(f"{pages} pages, plan={plan}, term extraction={'on' if terms else 'off'}")
    print(f"Per-job page cap {cap}: {jobs} job(s)" + ("" if jobs == 1 else f" of up to {cap} pages each"))
    largest = min(pages, cap)
    print(f"Up-front deduction for the largest job: {largest * pre:,} tokens of {quota:,} monthly"
          + (" (fits)" if largest * pre <= quota else " (does NOT fit)"))
    for label in ("p25", "mean", "p75"):
        need = pages * m[label]
        print(f"  {label:>4}: {need:,.0f} tokens = {need / quota:.2f} months of quota; "
              f"quota covers about {quota / m[label]:,.0f} such pages")

if __name__ == "__main__":
    main()
