#!/usr/bin/env python3
"""A stand-in for `latexmk`.

The engine needs a compiler to produce the two versions of a document that it
compares. A real paper needs a Te distribution, but the flow of the engine
itself does not: this program typesets a `.tex` file with a small PDF writer of
its own and writes a SyncTeX file next to it, so that the engine can be
exercised anywhere.

The PDF it writes holds one line of text per line of the source, in Helvetica
at twelve point, and the SyncTeX file records where every word of every line
was set. That is enough for the engine to find the source of a place on the
page.

Put the folder of this file at the front of `PATH` and the engine will use it
in place of `latexmk`.
"""

import gzip
import os
import sys


def escape(text):
    """Escape a string for a PDF literal."""
    return text.replace("\\", r"\\").replace("(", r"\(").replace(")", r"\)")


def write_pdf(path, lines):
    """Write a one page PDF with one line of text per line of the source."""
    content = []
    y = 700.0
    for line in lines:
        if line.strip():
            content.append(
                "BT /F1 12 Tf 72 %g Td (%s) Tj ET" % (y, escape(line))
            )
        y -= 14.0
    stream = "\n".join(content).encode("latin-1", "replace")

    objects = [
        b"<< /Type /Catalog /Pages 2 0 R >>",
        b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
        b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources "
        b"<< /Font << /F1 4 0 R >> >> /Contents 5 0 R >>",
        b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
        b"<< /Length " + str(len(stream)).encode() + b" >>\nstream\n" + stream
        + b"\nendstream",
    ]

    out = bytearray(b"%PDF-1.4\n")
    offsets = []
    for index, obj in enumerate(objects):
        offsets.append(len(out))
        out += str(index + 1).encode() + b" 0 obj\n" + obj + b"\nendobj\n"
    start = len(out)
    out += b"xref\n0 " + str(len(objects) + 1).encode() + b"\n"
    out += b"0000000000 65535 f \n"
    for offset in offsets:
        out += ("%010d 00000 n \n" % offset).encode()
    out += b"trailer\n<< /Size " + str(len(objects) + 1).encode() + b" /Root 1 0 R >>\nstartxref\n"
    out += str(start).encode() + b"\n%%EOF\n"
    with open(path, "wb") as f:
        f.write(bytes(out))


def write_synctex(path, source, lines):
    """Write the SyncTeX file that says where every word was set."""
    records = [
        "SyncTeX Version:1",
        "Input:1:" + os.path.abspath(source),
        "Magnification:1000",
        "Unit:1",
        "X Offset:0",
        "Y Offset:0",
        "Content:",
        "{1",
    ]
    y = 700.0
    for number, line in enumerate(lines, start=1):
        words = line.split()
        for index, word in enumerate(words):
            if index:
                records.append("g1,%d:%d,%d" % (number, int(72 * 65536), int(y * 65536)))
            records.append("x1,%d:%d,%d" % (number, int(72 * 65536), int(y * 65536)))
        y -= 14.0
    records.append("}")
    records.append("Postamble:")
    records.append("Count:%d" % len(records))
    with gzip.open(path, "wb") as f:
        f.write(("\n".join(records) + "\n").encode())


def main(argv):
    document = None
    for argument in argv:
        if argument.endswith(".tex"):
            document = argument
    if document is None:
        sys.stderr.write("fake-latexmk: no document to build\n")
        return 1
    with open(document, "r", encoding="utf-8") as f:
        lines = f.read().split("\n")
    stem = document[:-4]
    write_pdf(stem + ".pdf", lines)
    write_synctex(stem + ".synctex.gz", document, lines)
    print("fake-latexmk: built " + document)
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
