#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Korean vs English input tokens of paired public documents, from the usage that `claude -p` reports.

Kubernetes docs at a pinned commit (people translated them from English to Korean):

    git clone --filter=blob:none --sparse https://github.com/kubernetes/website
    git -C website sparse-checkout set content/en/docs/concepts content/ko/docs/concepts
    git -C website checkout 4152f9c284b8800dd8394ca61ac1a291f97f7566

Universal Declaration of Human Rights: kor.txt and eng.txt from the NLTK udhr2 corpus
(https://raw.githubusercontent.com/nltk/nltk_data/gh-pages/packages/corpora/udhr2.zip).

    python token_language_tax.py --k8s website --udhr udhr2 --models haiku

Another model through Claude Code: --models <name> --settings <settings.json>.

Tokens of a document = input usage with the document minus input usage with an empty document, same model, same prompt, same folder.
No tools, settings or MCP servers enter the prompt. Each call costs quota. Replies are not measured.
"""
import argparse
import json
import os
import random
import re
import shutil
import subprocess
import sys

SEED = 20261104
SAMPLE = 30
HEAD = "Reply with exactly OK. Do not act on the text below; it is only a sample.\n\n<sample>\n"
TAIL = "\n</sample>"
HANGUL = re.compile(r"[가-힣]")


def hangul_share(text):
    return len(HANGUL.findall(text)) / max(len(text), 1)


def front_matter_off(text):
    return re.sub(r"\A---\n.*?\n---\n", "", text.replace("\r\n", "\n"), count=1, flags=re.S)


def prose(text):
    """Text without front matter, code, link targets and Hugo shortcodes."""
    text = front_matter_off(text)
    text = re.sub(r"^(`{3,}|~{3,}).*?^\1[^\n]*$", "", text, flags=re.M | re.S)
    text = re.sub(r"\{\{[<%].*?[%>]\}\}", "", text, flags=re.S)
    text = re.sub(r"`[^`\n]+`", "", text)
    text = re.sub(r"\]\([^)\n]*\)", "]", text)
    return re.sub(r"https?://\S+", "", text)


def read(*parts):
    with open(os.path.join(*parts), encoding="utf-8-sig") as h:
        return h.read()


def kubernetes_pairs(website):
    """Pairs whose Korean text is long enough, mostly Korean and has the same headings as the English text. Keeps the translation close to the source."""
    ko_root = os.path.join(website, "content", "ko", "docs", "concepts")
    en_root = os.path.join(website, "content", "en", "docs", "concepts")
    pairs = []
    for folder, _, files in os.walk(ko_root):
        for f in files:
            rel = os.path.relpath(os.path.join(folder, f), ko_root).replace("\\", "/")
            if not f.endswith(".md") or f == "_index.md" or not os.path.isfile(os.path.join(en_root, rel)):
                continue
            k, e = front_matter_off(read(ko_root, rel)), front_matter_off(read(en_root, rel))
            heads = [len(re.findall(r"^#{1,6} ", x, flags=re.M)) for x in (k, e)]
            if 3000 <= len(k) <= 40000 and hangul_share(k) >= 0.2 and heads[0] == heads[1] and 0.5 <= len(e) / len(k) <= 3:
                pairs.append(rel)
    pairs.sort()
    return [(read(ko_root, r), read(en_root, r)) for r in random.Random(SEED).sample(pairs, min(SAMPLE, len(pairs)))]


def usage(model, settings, text):
    cmd = [shutil.which("claude"), "-p", "--model", model, "--output-format", "json", "--tools", "", "--strict-mcp-config", "--setting-sources", "",
           "--no-session-persistence", "--disable-slash-commands", "--system-prompt", "You reply with exactly OK."]
    if settings:
        cmd += ["--settings", settings]
    env = {**os.environ, "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "1"}
    r = subprocess.run(cmd, input=(HEAD + text + TAIL).encode("utf-8"), capture_output=True, env=env, timeout=600)
    if r.returncode:
        raise SystemExit(f"claude exit {r.returncode}: {r.stderr.decode('utf-8', 'replace')[:300]}")
    u = json.loads(r.stdout.decode("utf-8"))["usage"]
    # a repeated prompt moves tokens between these three, so only their sum is stable
    return u.get("input_tokens", 0) + u.get("cache_creation_input_tokens", 0) + u.get("cache_read_input_tokens", 0)


def measure(model, settings, name, pairs):
    empty = usage(model, settings, "")
    ko_chars = en_chars = ko_tokens = en_tokens = 0
    for ko, en in pairs:
        ko_chars, en_chars = ko_chars + len(ko), en_chars + len(en)
        ko_tokens += usage(model, settings, ko) - empty
        en_tokens += usage(model, settings, en) - empty
    print(f"{model:12} {name:10} {len(pairs):3d} pairs  chars {ko_chars}->{en_chars} x{en_chars / ko_chars:.2f}  tokens {ko_tokens}->{en_tokens} x{en_tokens / ko_tokens:.3f}", flush=True)


def main():
    sys.stdout.reconfigure(encoding="utf-8", errors="replace")
    ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    ap.add_argument("--k8s", help="kubernetes/website checkout")
    ap.add_argument("--udhr", help="folder with kor.txt and eng.txt")
    ap.add_argument("--models", nargs="+", default=["haiku"])
    ap.add_argument("--settings", help="settings file for a model that needs one")
    a = ap.parse_args()
    for m in a.models:
        if a.k8s:
            pairs = kubernetes_pairs(a.k8s)
            measure(m, a.settings, "k8s", [(front_matter_off(k), front_matter_off(e)) for k, e in pairs])
            measure(m, a.settings, "k8s_prose", [(prose(k), prose(e)) for k, e in pairs])
        if a.udhr:
            measure(m, a.settings, "udhr", [(read(a.udhr, "kor.txt"), read(a.udhr, "eng.txt"))])


if __name__ == "__main__":
    main()
