#!/usr/bin/env python3
"""Plan translating one document with Gemini or Claude, from vendor-published limits.

Usage: python3 pair_plan.py WORDS [--pages N] [--output-ratio R] [--chunk-words N] [--limits FILE]
   or: python3 pair_plan.py book.txt [...]

WORDS is the source word count (or a .txt file whose words are counted).
--pages N also estimates what it costs each API to read the source as an N-page
PDF, using each vendor's published per-page token figures.
--output-ratio is output tokens per source token (default 1.0; many target
languages need more, so measure a sample chapter).
--chunk-words is the size of each translation request (default 5000 words).

Token counts use each vendor's own English words-per-token rule of thumb, so
they are estimates; Google gives a range (60-80 words per 100 tokens), so
Gemini figures are shown as a range. Costs are standard list prices for the
source and translation tokens only. They leave out the prompt and glossary
repeated in every request, thinking tokens (both vendors count them inside
the output limit and bill them as output), retries, Batch discounts and taxes,
so treat them as a floor.
"""
import json, math, os, sys

def parse():
    a = sys.argv[1:]
    opts = {"--pages": 0, "--output-ratio": 1.0, "--chunk-words": 5000, "--limits": None}
    pos, i = [], 0
    while i < len(a):
        if a[i] in opts:
            if i + 1 >= len(a):
                sys.exit(f"{a[i]} needs a value")
            opts[a[i]] = a[i + 1]; i += 2
        else:
            pos.append(a[i]); i += 1
    if not pos:
        sys.exit(__doc__)
    src = pos[0]
    words = int(src) if src.isdigit() else len(open(src, encoding="utf-8", errors="replace").read().split())
    lim = opts["--limits"] or os.path.join(os.path.dirname(os.path.abspath(__file__)), "limits.json")
    return words, json.load(open(lim)), int(opts["--pages"]), float(opts["--output-ratio"]), int(opts["--chunk-words"])

def rng(lo, hi, fmt="{:,.0f}"):
    a, b = fmt.format(lo), fmt.format(hi)
    return a if a == b else f"{a}-{b}"

def main():
    words, L, pages, ratio, chunk = parse()
    print(f"Source: {words:,} words. Limits checked {L['checked']}. Output ratio {ratio}.")
    print("\nChat apps: does the source alone fit the context window?")
    for name, c in L["chat_apps"].items():
        hi_wpt, lo_wpt = max(c["words_per_token"]), min(c["words_per_token"])
        t_lo, t_hi = words / hi_wpt, words / lo_wpt
        if t_hi <= c["context_tokens"]:
            fit = "fits"
        elif t_lo <= c["context_tokens"]:
            fit = "borderline"
        else:
            fit = "does not fit"
        print(f"  {name}: ~{rng(t_lo, t_hi)} tokens vs {c['context_tokens']:,} -> {fit}; EPUB upload {c['epub_upload']}")
    print(f"\nAPI: translating in {chunk:,}-word requests")
    for name, m in L["api_models"].items():
        hi_wpt, lo_wpt = max(m["words_per_token"]), min(m["words_per_token"])
        tin_lo, tin_hi = words / hi_wpt, words / lo_wpt
        out_lo, out_hi = tin_lo * ratio, tin_hi * ratio
        floor_lo = math.ceil(out_lo / m["max_output_tokens"])
        floor_hi = math.ceil(out_hi / m["max_output_tokens"])
        pin, pout = m["input_usd_per_mtok"], m["output_usd_per_mtok"]
        c_lo = tin_lo / 1e6 * pin + out_lo / 1e6 * pout
        c_hi = tin_hi / 1e6 * pin + out_hi / 1e6 * pout
        line = (f"  {name}: ~{rng(tin_lo, tin_hi)} in + ~{rng(out_lo, out_hi)} out tokens; "
                f"at least {rng(floor_lo, floor_hi, '{}')} response(s) at the {m['max_output_tokens']:,}-token cap; "
                f"{math.ceil(words / chunk)} requests; ~${rng(c_lo, c_hi, '{:,.2f}')}")
        if min(chunk, words) / lo_wpt * ratio > m["max_output_tokens"]:
            line += "; WARNING: one request's translation can exceed the output cap"
        print(line)
    if pages:
        print(f"\nReading the source as a {pages:,}-page PDF (input tokens for one full read)")
        for name, m in L["api_models"].items():
            lo, hi = (pages * p for p in m["pdf_tokens_per_page"])
            note = "" if pages <= m["max_pdf_pages"] else f"; over the {m['max_pdf_pages']:,}-page limit per request"
            if hi > 1_000_000:
                note += "; can exceed a 1M-token context"
            cost = rng(lo / 1e6 * m["input_usd_per_mtok"], hi / 1e6 * m["input_usd_per_mtok"], "{:,.2f}")
            print(f"  {name}: ~{rng(lo, hi)} tokens, ~${cost} per read{note}")

if __name__ == "__main__":
    main()
