#!/usr/bin/env python3
"""
Normalise a PDF so the free FPDI parser (PHP) can import it.

Modern supplier-invoice PDFs (v1.5+) use compressed cross-reference /
object streams that the free FPDI parser cannot read, which makes the
"Build combined PDF" step fail. Re-saving the file through PyMuPDF
(MuPDF) rewrites it with a classic, uncompressed structure that FPDI
handles.

Usage:  normalize_pdf.py <input.pdf> <output.pdf>
Exit 0 on success, non-zero on failure.
"""
import sys

def main() -> int:
    if len(sys.argv) < 3:
        sys.stderr.write("usage: normalize_pdf.py <input.pdf> <output.pdf>\n")
        return 2

    src, dst = sys.argv[1], sys.argv[2]

    try:
        import fitz  # PyMuPDF
    except Exception as e:  # noqa: BLE001
        sys.stderr.write("PyMuPDF not available: %s\n" % e)
        return 3

    try:
        doc = fitz.open(src)
        # garbage=4 + clean rewrites the whole file; expand=255 decompresses
        # streams and pretty=False keeps a plain classic xref table, which is
        # what the free FPDI parser needs.
        doc.save(
            dst,
            garbage=4,
            clean=True,
            deflate=True,
            expand=255,
            pretty=False,
        )
        doc.close()
    except Exception as e:  # noqa: BLE001
        sys.stderr.write("normalise failed: %s\n" % e)
        return 1

    return 0


if __name__ == "__main__":
    raise SystemExit(main())
