#!/usr/bin/env python3
"""Build isolated manual programs from the exact displayed source.

LaTeX diagrams execute through PGF's codeexample environment in the manual.
Plain TeX, MkIV and texlua require their own engines. Their PDFs are test
artifacts only and are never imported into the manual. Reference-state setup
also needs a fresh process. Installation commands and explicitly incomplete
syntax templates are instructional text.
"""

import os
from pathlib import Path
import re
import subprocess
import sys


def main():
    root = Path(__file__).resolve().parent.parent
    logs = root / 'build-logs/manual-examples'
    logs.mkdir(parents=True, exist_ok=True)
    environment = os.environ.copy()
    environment["TEXINPUTS"] = str(root) + os.pathsep + environment.get("TEXINPUTS", "") + os.pathsep
    # The marker names the required engine without changing PGF's native
    # listing syntax. The body extracted here is exactly the displayed code.
    pattern = re.compile(
        r"% lcp-manual-program: (texlua|luatex|context|lualatex) \| ([^\n]+)\n"
        r"\\begin\{codeexample\}\[([^\n]*)\]\n(.*?)\\end\{codeexample\}", re.S)
    count = 0
    for source in sorted((root / "doc/luatex/luacoolprop").glob("*.tex")):
        text = source.read_text()
        matches = list(pattern.finditer(text))
        markers = re.findall(r"^% lcp-manual-program:.*$", text, re.M)
        if len(matches) != len(markers):
            sys.exit(f"error: malformed isolated-program marker or listing in {source.name}")
        for match in matches:
            engine, title, options, code = match.groups()
            if "code only" not in [option.strip() for option in options.split(",")]:
                sys.exit(f"error: isolated program must use code only: {title}")
            standalone_program = engine == "lualatex" and "\\documentclass" in code
            extension = "lua" if engine == "texlua" else "tex"
            if engine == "lualatex" and not standalone_program:
                # Reference-state selection must happen in a fresh process,
                # before any diagrams can lock the fluid's reference state.
                code = ("\\documentclass{article}\n\\usepackage{luacoolprop}\n"
                        "\\begin{document}\n" + code + "\\end{document}\n")
            count += 1
            stem = f"example-{count:02d}"
            path = logs / f"{stem}.{extension}"
            path.write_text(code)
            if engine == "texlua":
                command = [engine, str(path)]
                cwd = root
            elif standalone_program:
                command = [engine, "--shell-escape", "--interaction=nonstopmode",
                           "--halt-on-error", path.name]
                cwd = logs
            elif engine == "context":
                runner = subprocess.check_output(
                    ["kpsewhich", "--format=texmfscripts", "mtxrun.lua"], text=True).strip()
                script = subprocess.check_output(
                    ["kpsewhich", "--format=texmfscripts", "mtx-context.lua"], text=True).strip()
                dependency_tex = subprocess.check_output(
                    ["kpsewhich", "pgflibrarypgfplots.autonode.code.tex"], text=True).strip()
                dependency_lua = subprocess.check_output(
                    ["kpsewhich", "--format=lua", "pgfplots-autonode.lua"], text=True).strip()
                search = [root / "tex/luatex/luacoolprop", root / "tex/luatex/luacoolprop/lua",
                          Path(dependency_tex).parent, Path(dependency_lua).parent]
                command = ["luatex", "--luaonly", runner, "--script", script,
                           "--luatex", "--once", "--batchmode", "--shell-escape",
                           "--path=" + ",".join(map(str, search)), str(path)]
                cwd = logs
            else:
                command = [engine, "--shell-escape", "--interaction=nonstopmode", "--halt-on-error", "--output-directory=" + str(logs), str(path)]
                cwd = root
            log = logs / f"{stem}-console.log"
            engine_environment = environment.copy()
            # MkIV owns its resolver cache; luaotfload's cache is unrelated.
            if engine != "context" and environment.get("LUACOOLPROP_TEX_CACHE"):
                engine_environment["TEXMFCACHE"] = environment["LUACOOLPROP_TEX_CACHE"]
            if engine == "context":
                engine_environment.pop("TEXINPUTS", None)
                engine_environment.pop("LUAINPUTS", None)
                subprocess.run(["luatex", "--luaonly", runner, "--generate"],
                               cwd=cwd, env=engine_environment, check=True,
                               stdout=subprocess.DEVNULL)
            with log.open("w") as output:
                result = subprocess.run(command, cwd=cwd, env=engine_environment,
                                        stdout=output, stderr=subprocess.STDOUT, check=False)
            transcript = log.read_text(errors="replace")
            if result.returncode or "tex error" in transcript.lower():
                sys.exit(f"error: {source.name}: {title} ({log})")
            print(f"Manual example passed ({engine}): {title}", flush=True)
    if count == 0:
        sys.exit("error: no independently executable manual examples found")
    print(f"Checked {count} isolated displayed examples.")


if __name__ == "__main__":
    main()
