#!/usr/bin/env python3
"""Check one document against Gemini's and DeepL's published limits.

Usage: python3 gemini_deepl_check.py SOURCE TARGET WORDS FORMAT [--chars N] [--output-ratio R]

SOURCE and TARGET are language codes from languages-2026-11-28.csv (DeepL's
codes, plus AM, KN, KM, LO and OR for languages only Gemini lists).
WORDS is the source word count. FORMAT is the file extension, e.g. docx or pdf.
The token and character estimates use Google's rules for English text, so
they are most reliable for an English source; for other sources, measure a
sample chapter and pass --chars and --output-ratio.

--chars  the file's character count, if you know it; it refines the DeepL
         estimate only (Gemini's token estimate uses WORDS). Otherwise the script
         estimates 5.0 to 6.7 characters per English word, derived from
         Google's rule that a token is about 4 characters and 100 tokens are
         about 60-80 English words. Word's own character count is better.
--output-ratio  output tokens per source token (default 1.0). Many target
         languages need more tokens than English; measure one chapter.

All limits were copied from the vendors' pages on 2026-11-28 and are listed
below with their sources. Standard library only.
"""
import csv, math, os, sys

# DeepL web plans, PDF/DOCX/PPTX/RTF/ODT limits per file and files per month.
# https://support.deepl.com/hc/en-us/articles/360020582359-File-formats
# https://www.deepl.com/en/pro
DEEPL_PLANS = [  # name, max characters per file, files per month, glossary entries per pair
    ("Free account", 100_000, 1, 5),
    ("Pro Individual", 1_000_000, 3, 5),
    ("Pro Team", 1_000_000, 20, 1_000),
    ("Pro Business", 1_000_000, 100, None),
]
DEEPL_FORMATS = {"docx", "doc", "pptx", "pdf", "rtf", "odt"}  # the rows the plan table above covers
DEEPL_OTHER = {"xlsx", "xlsm", "txt", "html", "xlf", "xliff", "srt", "vtt", "png", "jpg", "jpeg",
               "idml", "xml", "json", "mif", "dita", "yaml", "yml", "properties", "md", "markdown",
               "strings", "resx", "zip"}  # supported on paid plans with their own size limits

# Gemini: https://aistudio.google.com/docs/models/gemini-3.8-flash (65,536 output tokens),
# https://support.google.com/gemini/answer/16275805 (app context per plan),
# https://aistudio.google.com/docs/tokens (4 characters, 60-80 English words per 100 tokens),
# https://aistudio.google.com/docs/pricing (Gemini 3.8 Flash, paid tier, USD per 1M tokens).
GEMINI_OUTPUT_CAP = 65_536
GEMINI_APP = [("no AI plan", 32_000), ("Google AI Plus", 128_000), ("AI Pro or Ultra", 1_000_000)]
TOKENS_PER_WORD = (100 / 80, 100 / 60)
PRICES = [("through 2026-12-31", 0.75, 3.75), ("from 2027-01-01", 1.50, 7.50)]
OVERHEAD_TOKENS = 2_000  # instructions plus a short glossary repeated in every request


def load_languages():
    path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "languages-2026-11-28.csv")
    return {row["code"].upper(): row for row in csv.DictReader(open(path, encoding="utf-8"))}


def parse_args():
    a = sys.argv[1:]
    opts = {"--chars": None, "--output-ratio": 1.0}
    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.\n\n{__doc__}")
            opts[a[i]] = float(a[i + 1]); i += 2
        else:
            pos.append(a[i]); i += 1
    if len(pos) != 4 or not pos[2].isdigit():
        sys.exit(__doc__)
    return pos[0].upper(), pos[1].upper(), int(pos[2]), pos[3].lower().lstrip("."), opts


def yes(flag):
    return "yes" if flag else "no"


def span(a, b):
    return f"{a:,}" if a == b else f"{a:,}-{b:,}"


def main():
    src, tgt, words, fmt, opts = parse_args()
    langs = load_languages()
    for code in (src, tgt):
        if code not in langs:
            sys.exit(f"Unknown code {code}. Use a code from languages-2026-11-28.csv.")
    s, t = langs[src], langs[tgt]
    ratio = opts["--output-ratio"]

    print(f"{s['name']} ({src}) -> {t['name']} ({tgt}), {words:,} words, .{fmt}\n")

    print("Languages")
    deepl_pair = s["deepl"] == "yes" and t["deepl"] == "yes" and s["deepl_target_only"] == "no"
    print(f"  DeepL offers this pair:            {yes(deepl_pair)}")
    if s["deepl_target_only"] == "yes":
        print(f"  ({src} is target-only on DeepL; use the base code as the source)")
    print(f"  DeepL glossary on this pair:       {yes(deepl_pair and s['deepl_glossary'] == 'yes' and t['deepl_glossary'] == 'yes')}")
    formality = deepl_pair and t["deepl_formality"] == "yes"
    print(f"  DeepL formal/informal target:      {yes(formality)}{' (paid plans)' if formality else ''}")
    print(f"  Both on Gemini app language list:  {yes(s['gemini_app_listed'] == 'yes' and t['gemini_app_listed'] == 'yes')}")
    print("  Gemini glossary:                   instructions in the prompt, not enforced\n")

    if opts["--chars"]:
        chars = (int(opts["--chars"]),) * 2
        print(f"Characters: {chars[0]:,} (given)")
    else:
        chars = (round(words * 4 * TOKENS_PER_WORD[0]), round(words * 4 * TOKENS_PER_WORD[1]))
        print(f"Characters: about {chars[0]:,} to {chars[1]:,} (estimated from words)")

    print("\nDeepL file translation (returns the translated file)")
    if fmt == "epub" or fmt == "mobi":
        print(f"  .{fmt} is not on DeepL's file format list; convert it first")
    elif fmt in DEEPL_FORMATS:
        for name, limit, per_month, entries in DEEPL_PLANS:
            if not deepl_pair:
                break
            parts = (math.ceil(chars[0] / limit), math.ceil(chars[1] / limit))
            note = "fits in one file" if parts[1] == 1 else f"split into {span(*parts)} files"
            over = " (more files than the plan's monthly allowance)" if parts[1] > per_month else ""
            gl = "unlimited" if entries is None else f"{entries:,}"
            print(f"  {name:15} {note}; {per_month} file{'s' if per_month > 1 else ''}/month{over}; glossary entries per pair: {gl}")
        if not deepl_pair:
            print("  DeepL does not offer this pair")
    elif fmt in DEEPL_OTHER:
        print(f"  .{fmt} is supported on paid plans with its own size limits; see DeepL's file formats page")
    else:
        print(f"  .{fmt} is not on DeepL's file format list")

    print("\nGemini (returns text, not a file)")
    out_tokens = (words * TOKENS_PER_WORD[0] * ratio, words * TOKENS_PER_WORD[1] * ratio)
    in_tokens = (words * TOKENS_PER_WORD[0], words * TOKENS_PER_WORD[1])
    responses = (math.ceil(out_tokens[0] / GEMINI_OUTPUT_CAP), math.ceil(out_tokens[1] / GEMINI_OUTPUT_CAP))
    print(f"  Translation length: about {out_tokens[0]:,.0f} to {out_tokens[1]:,.0f} output tokens")
    print(f"  API responses at the {GEMINI_OUTPUT_CAP:,}-token output cap: at least {span(*responses)}")
    for name, ctx in GEMINI_APP:
        chunk = (ctx - OVERHEAD_TOKENS) / (TOKENS_PER_WORD[1] * (1 + ratio))
        print(f"  App context, {name:16} source plus translation fit for about {chunk:,.0f} source words per chat")
    print("  (Google does not publish the app's output limit per response; ask for one chapter at a time)")
    for label, p_in, p_out in PRICES:
        low = (in_tokens[0] * p_in + out_tokens[0] * p_out) / 1e6
        high = (in_tokens[1] * p_in + out_tokens[1] * p_out) / 1e6
        print(f"  API cost, Gemini 3.8 Flash {label}: about ${low:,.2f} to ${high:,.2f}")
    print("  (source and translation tokens only; thinking tokens, repeated glossaries and retries cost extra)")


if __name__ == "__main__":
    main()
