"""Each app's own Gotenberg request, replayed unchanged against three servers; every answer and PDF kept.

Start the three servers, then run:  python3 replay.py OUTDIR
    docker run -d --name g8 -p 3008:3000 gotenberg/gotenberg:8.40.0
    docker run -d --name g9 -p 3009:3000 gotenberg/gotenberg:9.11.1
    docker run -d --name kern -p 3010:3000 marqius/kern:latest
It waits up to two minutes for all three to answer /health. Needs Python 3 and curl.
Each entry in REQUESTS names the file in the app's own source that the request was copied from."""
import json, os, subprocess, sys, time, zipfile, zlib

OUT = sys.argv[1]
SERVERS = {"g8": "http://127.0.0.1:3008", "g9": "http://127.0.0.1:3009", "kern": "http://127.0.0.1:3010"}
os.makedirs(OUT, exist_ok=True)
F = os.path.join(OUT, "in")
os.makedirs(F, exist_ok=True)

# Inputs: a real Word file (made here, stdlib only), an HTML page, a footer, a page that signals ready, two PDFs.
def docx(path, text):
    parts = {
        "[Content_Types].xml": '<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/></Types>',
        "_rels/.rels": '<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>',
        "word/document.xml": '<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body><w:p><w:r><w:t>' + text + '</w:t></w:r></w:p></w:body></w:document>',
    }
    with zipfile.ZipFile(path, "w", zipfile.ZIP_DEFLATED) as z:
        for name, body in parts.items():
            z.writestr(name, body)

docx(f"{F}/document.docx", "A Word document, converted as the app converts it.")
open(f"{F}/index.html", "w").write("<!doctype html><meta charset=utf-8><h1>Invoice 1001</h1><p>An HTML page, converted as the app converts it.</p>")
open(f"{F}/footer.html", "w").write("<!doctype html><html><body style='font-size:8px'><span class='pageNumber'></span></body></html>")
open(f"{F}/ready.html", "w").write("<!doctype html><meta charset=utf-8><h1>Report</h1><script>window.status='ready'</script>")
open(f"{F}/outfit.ttf", "wb").write(b"")  # stands in for the app's font asset; the pages do not reference it
import struct
def png(path, w=120, h=40):
    raw = b"".join(b"\x00" + b"\x12\x3f\x2f" * w for _ in range(h))
    chunk = lambda t, d: struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d) & 0xffffffff)
    open(path, "wb").write(b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0)) + chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b""))
png(f"{F}/lago-logo-invoice.png")
open(f"{F}/lago.html", "w").write("<!doctype html><meta charset=utf-8><img src='lago-logo-invoice.png' alt='logo'><h1>Invoice LAG-0001</h1><p>A one-off invoice, printed as Lago prints it.</p>")

def wait_for_servers(seconds=120):
    deadline = time.time() + seconds
    for name, base in SERVERS.items():
        while subprocess.run(["curl", "-fsS", "-o", "/dev/null", base + "/health"], capture_output=True).returncode:
            if time.time() > deadline:
                sys.exit(f"{name} did not answer {base}/health within {seconds} seconds")
            time.sleep(1)

wait_for_servers()

def make_pdf(name):
    r = subprocess.run(["curl", "-sS", "-o", f"{F}/{name}", "-w", "%{http_code}", "-F", f"files=@{F}/index.html",
                        SERVERS["g8"] + "/forms/chromium/convert/html"], capture_output=True, text=True)
    assert r.stdout == "200", r
make_pdf("a.pdf"); make_pdf("b.pdf")

A4 = [("paperWidth", "8.27"), ("paperHeight", "11.7")]
MARGINS = [("marginTop", "0.39"), ("marginBottom", "0.78"), ("marginLeft", "0.39"), ("marginRight", "0.39")]

REQUESTS = [
    # app, case, source, route, files, fields[, headers]
    ("paperless-ngx", "Office file, PDF/A on (Paperless's default output type)",
     "src/paperless/parsers/tika.py (gotenberg-client ~=1.0): libre_office.to_pdf, update_indexes(False), pdf_format(A2b)",
     "/forms/libreoffice/convert", [("files", "document.docx")], [("updateIndexes", "false"), ("pdfa", "PDF/A-2b")]),
    ("paperless-ngx", "E-mail, the text part to PDF/A",
     "src/paperless/parsers/mail.py: chromium HTML, A4, margins, pdf_format(A2b)",
     "/forms/chromium/convert/html", [("files", "index.html")], A4 + MARGINS + [("pdfa", "PDF/A-2b")]),
    ("paperless-ngx", "E-mail with HTML: the two PDFs merged",
     "src/paperless/parsers/mail.py: client.merge.merge(), pdf_format; gotenberg-client posts to /forms/pdfengines/merge",
     "/forms/pdfengines/merge", [("files", "a.pdf"), ("files", "b.pdf")], [("pdfa", "PDF/A-2b")]),
    ("documenso", "Word upload to PDF",
     "packages/lib/server-only/document-conversion/gotenberg.ts: files, exportFormFields=false",
     "/forms/libreoffice/convert", [("files", "document.docx")], [("exportFormFields", "false")]),
    ("huly", "DOCX preview",
     "services/print/pod-print/src/preview.ts: files=document.docx",
     "/forms/libreoffice/convert", [("files", "document.docx")], []),
    ("solidtime", "Time-entry report",
     "app/Http/Controllers/Api/V1/TimeEntryController.php (gotenberg-php ^2.8): chromium html, asset, margins, A4, footer",
     "/forms/chromium/convert/html", [("files", "index.html"), ("files", "footer.html"), ("files", "outfit.ttf")], MARGINS + A4),
    ("solidtime", "Chart report, waits for the page",
     "TimeEntryController.php: waitForExpression(\"window.status === 'ready'\"), margins, A4, footer",
     "/forms/chromium/convert/html", [("files", "ready.html:index.html"), ("files", "footer.html")], [("waitForExpression", "window.status === 'ready'")] + MARGINS + A4),
    ("invoiceninja", "Invoice PDF",
     "app/Utils/Gotenberg/GotenbergPdf.php: chromium html",
     "/forms/chromium/convert/html", [("files", "index.html")], []),
    ("invoiceninja", "E-invoice (PDF/A-3b, when an e-invoice type is set)",
     "app/Services/Pdf/PdfService.php + GotenbergPdf.php: options['pdfa'] = PDF/A-3b",
     "/forms/chromium/convert/html", [("files", "index.html")], [("pdfa", "PDF/A-3b")]),
    ("lago", "Invoice PDF",
     "app/services/utils/pdf_generator.rb (getlago/lago-api): file1 index.html, file2 the logo, file3 footer.html, scale 1.28, margins",
     "/forms/chromium/convert/html", [("file1", "lago.html:index.html"), ("file2", "lago-logo-invoice.png"), ("file3", "footer.html")],
     [("scale", "1.28"), ("marginTop", "0.42"), ("marginBottom", "0.6"), ("marginLeft", "0.42"), ("marginRight", "0.42")]),
    ("pimcore", "Asset preview: an Office file to PDF",
     "lib/Document/Adapter/Gotenberg.php (pimcore/pimcore v2026.3.8): libreOffice()->convert(the file)",
     "/forms/libreoffice/convert", [("files", "document.docx")], []),
    ("pimcore", "Page preview: a screenshot of a page",
     "lib/Image/HtmlToImage.php (pimcore/pimcore v2026.3.8): chromium()->screenshot()->width(1280)->height(1024)->png()->url(...)",
     "/forms/chromium/screenshot/url", [], [("url", "https://example.com/"), ("width", "1280"), ("height", "1024"), ("format", "png")]),
    ("pimcore-w2p", "Web-to-Print with the default settings (Pimcore 11's bundle)",
     "src/Processor/Gotenberg.php (pimcore/web-to-print-bundle v1.4.0, gotenberg-php 2): with no settings, getDefaultOptions() turns printBackground on (landscape stays off); margins 0.39, outputFilename, html",
     "/forms/chromium/convert/html", [("files", "index.html")],
     [("printBackground", "true"), ("marginTop", "0.39"), ("marginBottom", "0.39"), ("marginLeft", "0.39"), ("marginRight", "0.39")],
     [("Gotenberg-Output-Filename", "web2print_check")]),
    ("pimcore-w2p", "Web-to-Print with metadata set",
     "src/Processor/Gotenberg.php (pimcore/web-to-print-bundle v1.4.0, gotenberg-php 2): ->metadata([...]) when the settings carry metadata (settings replace the defaults, so printBackground is off)",
     "/forms/chromium/convert/html", [("files", "index.html")],
     [("marginTop", "0.39"), ("marginBottom", "0.39"), ("marginLeft", "0.39"), ("marginRight", "0.39"), ("metadata", '{"Title":"Catalogue","Author":"Pimcore"}')],
     [("Gotenberg-Output-Filename", "web2print_check")]),
    ("pimcore-w2p", "Web-to-Print with page ranges set",
     "src/Processor/Gotenberg.php (pimcore/web-to-print-bundle v1.4.0, gotenberg-php 2): ->nativePageRanges('1') when the settings carry nativePageRanges (settings replace the defaults, so printBackground is off)",
     "/forms/chromium/convert/html", [("files", "index.html")],
     [("marginTop", "0.39"), ("marginBottom", "0.39"), ("marginLeft", "0.39"), ("marginRight", "0.39"), ("nativePageRanges", "1")],
     [("Gotenberg-Output-Filename", "web2print_check")]),
]

results = []
for i, (app, case, source, route, files, fields, *rest) in enumerate(REQUESTS):
    headers = rest[0] if rest else []
    row = {"app": app, "case": case, "source": source, "route": route, "fields": fields, "headers": headers, "servers": {}}
    for sname, base in SERVERS.items():
        kind = "png" if "/screenshot/" in route else "pdf"
        out = f"{OUT}/{i:02d}-{app}-{sname}.{kind}"
        cmd = ["curl", "-sS", "-o", out, "-w", "%{http_code}", "--max-time", "120"]
        for k, f in files:
            src, _, as_name = f.partition(":")
            cmd += ["-F", f"{k}=@{F}/{src}" + (f";filename={as_name}" if as_name else "")]
        for k, v in fields:
            cmd += ["--form-string", f"{k}={v}"]
        for k, v in headers:
            cmd += ["-H", f"{k}: {v}"]
        cmd.append(base + route)
        r = subprocess.run(cmd, capture_output=True, text=True)
        code = r.stdout.strip()
        body = open(out, "rb").read() if os.path.exists(out) else b""
        ok = code == "200" and body[:5] == (b"\x89PNG\r" if kind == "png" else b"%PDF-")
        msg = "" if ok else body[:400].decode("utf-8", "replace")
        if not ok and os.path.exists(out):
            os.rename(out, out.rsplit(".", 1)[0] + ".txt")
        row["servers"][sname] = {"status": code, "made": ok, "kind": kind, "bytes": len(body), "answer": msg}
    results.append(row)
    print(app, "|", case, "|", {s: v["status"] for s, v in row["servers"].items()}, flush=True)

json.dump(results, open(f"{OUT}/results.json", "w"), indent=1)
