#!/usr/bin/env python3
"""Estimate what translating one book through Claude or ChatGPT involves.

Usage: python3 book_plan.py WORDS [limits.json] [--output-ratio R] [--chunk-words N]
   or: python3 book_plan.py book.txt [limits.json] ...

WORDS is the source word count (or a .txt file whose words are counted).
Token counts use each vendor's own English words-per-token rule of thumb from
limits.json, so they are estimates. --output-ratio is how many output tokens
the translation needs per source token (default 1.0; many target languages
need more, so measure a sample chapter). --chunk-words sets the size of each
API request (default 5000 words), which keeps every request far below the
output cap and below OpenAI's long-context threshold.

Costs are standard list prices for the source and translation tokens only.
They leave out the prompt, the glossary you repeat in every request, retries,
discounts (Batch, caching) and taxes, so treat them as a floor.
"""
import json, math, os, sys

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

def main():
    words, L, ratio, chunk = args()
    print(f"Source: {words:,} words. Limits checked {L['checked']}. Output ratio {ratio}.")
    print("\nChat apps: does the whole source fit the working context?")
    for name, c in L["chat_apps"].items():
        tok = round(words / c["words_per_token"])
        fits = "fits" if tok <= c["context_tokens"] else "does not fit"
        epub = "EPUB upload listed" if c["epub_upload"] else "EPUB not on upload list"
        print(f"  {name}: ~{tok:,} tokens vs {c['context_tokens']:,} -> {fits}; {epub}")
    print(f"\nAPI: {chunk:,}-word requests")
    for name, m in L["api_models"].items():
        tin = words / m["words_per_token"]
        tout = tin * ratio
        floor_responses = math.ceil(tout / m["max_output_tokens"])
        reqs = math.ceil(words / chunk)
        chunk_in = min(chunk, words) / m["words_per_token"]
        pin, pout = m["input_usd_per_mtok"], m["output_usd_per_mtok"]
        r = m.get("long_context_rule")
        surcharge = bool(r and chunk_in > r["above_input_tokens"])
        if surcharge:
            pin *= r["input_multiplier"]; pout *= r["output_multiplier"]
        cost = tin / 1e6 * pin + tout / 1e6 * pout
        note = " (long-context rate)" if surcharge else ""
        if chunk_in * ratio > m["max_output_tokens"]:
            note += "; WARNING: one request's translation exceeds the output cap and would be cut off"
        print(f"  {name}: ~{tin:,.0f} in + ~{tout:,.0f} out tokens; at least {floor_responses} response(s) at the "
              f"{m['max_output_tokens']:,}-token cap; {reqs} requests; ~${cost:,.2f}{note}")

if __name__ == "__main__":
    main()
