#!/usr/bin/env python3
"""Compile translated LaTeX files twice and report what a reader would see.

For each file:
  as-is      compile exactly what the model returned
  with-ctex  make sure the preamble loads ctex with the Fandol fonts that ship
             with TeX (\\usepackage[UTF8,fontset=fandol]{ctex}), then compile

For every successful PDF it counts unresolved references (??), unresolved
citations ([?]) and missing glyphs reported in the log.

Usage:
    python3 compile_check.py out-*.tex
Needs tectonic (https://tectonic-typesetting.github.io) and pdftotext (Poppler).

Written by BookTranslator (https://www.booktranslator.app). Free to reuse.
"""

import re
import shutil
import subprocess
import sys
from pathlib import Path

BUILD = Path(__file__).parent / "build"
CTEX = r"\usepackage[UTF8,fontset=fandol]{ctex}"


def with_ctex(tex):
    if re.search(r"\\usepackage(\[[^\]]*\])?\{ctex\}", tex):
        return re.sub(r"\\usepackage(\[[^\]]*\])?\{ctex\}", lambda m: CTEX, tex, count=1)
    return re.sub(r"(\\documentclass(\[[^\]]*\])?\{[^}]*\}\n)", lambda m: m.group(1) + CTEX + "\n", tex, count=1)


def compile_one(name, tex):
    path = BUILD / f"{name}.tex"
    path.write_text(tex, encoding="utf-8")
    run = subprocess.run(["tectonic", "-X", "compile", "--keep-logs", path.name],
                         cwd=BUILD, capture_output=True, text=True)
    if run.returncode != 0:
        first = next((l for l in run.stderr.splitlines() if l.startswith("error:")), "error")
        return f"fails: {first.removeprefix('error: ')[:90]}"
    text = subprocess.run(["pdftotext", "-layout", f"{name}.pdf", "-"], cwd=BUILD,
                          capture_output=True, text=True).stdout
    log = (BUILD / f"{name}.log").read_text(encoding="utf-8", errors="replace")
    return (f"ok; ?? refs {text.count('??')}, [?] cites {text.count('[?]')}, "
            f"missing glyphs {log.count('Missing character')}")


def main():
    if not shutil.which("tectonic"):
        sys.exit("tectonic not found")
    BUILD.mkdir(exist_ok=True)
    for f in sys.argv[1:]:
        tex = Path(f).read_text(encoding="utf-8")
        stem = Path(f).stem
        print(f"{Path(f).name}\n  as-is:     {compile_one(stem + '.asis', tex)}"
              f"\n  with-ctex: {compile_one(stem + '.ctex', with_ctex(tex))}")


if __name__ == "__main__":
    main()
