"""Compare a source text and its translation paragraph by paragraph.

Usage: python3 check_translation.py source.txt translation.txt [--low 0.85 --high 1.35]
       [--term "Prokurist=chief clerk" ...]

Paragraphs are separated by blank lines. The script prints the paragraph counts
and every paragraph whose word ratio (translation / source) falls outside the
range. With --term, it also reports every paragraph where a source term
appears but its required translation does not, or appears a different number of times. A flagged paragraph is not proof of an error; it is the place to read
first. The default range was set for German to English prose; adjust it for
your language pair after checking a few paragraphs you trust.
"""
import argparse, re

ap = argparse.ArgumentParser()
ap.add_argument("source")
ap.add_argument("translation")
ap.add_argument("--low", type=float, default=0.85)
ap.add_argument("--high", type=float, default=1.35)
ap.add_argument("--term", action="append", default=[], help="SOURCE=TARGET, case-insensitive")
a = ap.parse_args()


def paragraphs(path):
    text = open(path, encoding="utf-8").read()
    return [re.sub(r"\s+", " ", p).strip() for p in re.split(r"\n\s*\n", text) if p.strip()]


src, out = paragraphs(a.source), paragraphs(a.translation)
print(f"source paragraphs: {len(src)}  translation paragraphs: {len(out)}")
if len(src) != len(out):
    print("MISMATCH: paragraphs were merged, split, added, or dropped. Align them before trusting the ratios below.")
for i, (s, t) in enumerate(zip(src, out), 1):
    r = len(t.split()) / max(len(s.split()), 1)
    if not a.low <= r <= a.high:
        print(f"paragraph {i}: ratio {r:.2f} ({len(s.split())} -> {len(t.split())} words)")
        print("  source starts:", s[:90])
        print("  output starts:", t[:90])
    for term in a.term:
        source_term, target_term = term.split("=", 1)
        n_src = s.lower().count(source_term.lower())
        n_out = t.lower().count(target_term.lower())
        if n_src != n_out:
            print(f"paragraph {i}: '{source_term}' x{n_src} in source, '{target_term}' x{n_out} in translation")
