"""MIT-licensed synthetic PDF experiment. Python 3.10+, standard library only.

python reproduce.py generate OUTPUT
python reproduce.py check OUTPUT
python reproduce.py run OUTPUT --java PATH --tools DIRECTORY
Reads case.json beside this script. Never overwrites an existing output folder.
Does not download tools, edit an original or repair arbitrary files.
"""
import argparse
import base64
import hashlib
import json
import os
from pathlib import Path
import re
import subprocess


def digest(data):
    return hashlib.sha256(data).hexdigest()


def generate():
    parts = [b"%PDF-1.4\n"]
    offsets = []
    bodies = [
        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 72 72] /Resources << >> >>",
    ]
    for number, body in enumerate(bodies, 1):
        offsets.append(sum(map(len, parts)))
        parts.append(f"{number} 0 obj\n".encode() + body + b"\nendobj\n")
    xref = sum(map(len, parts))
    parts.append(b"xref\n0 4\n0000000000 65535 f \n")
    parts.extend(f"{offset:010d} 00000 n \n".encode() for offset in offsets)
    rows_end = sum(map(len, parts))
    trailer = b"trailer\n<< /Size 4 /Root 1 0 R >>\n"
    parts.append(trailer + f"startxref\n{xref}\n%%EOF\n".encode())
    original = b"".join(parts)
    # The final two padding spaces are separated by one 20-byte row.
    last = rows_end - 2
    previous = last - 20
    assert original[last] == original[previous] == 0x20
    return {
        "control-sp-lf.pdf": original,
        "control-sp-cr.pdf": original[:last + 1] + b"\r" + original[last + 2:],
        "control-cr-lf.pdf": original[:last] + b"\r" + original[last + 1:],
        "short-row-lf.pdf": original[:last] + original[last + 1:],
        "two-short-rows.pdf": original[:previous] + original[previous + 1:last] + original[last + 1:],
        "missing-trailer.pdf": original[:rows_end] + original[rows_end + len(trailer):],
    }


def check(folder, case):
    generated = generate()
    for item in case["files"]:
        name = item["filename"]
        assert Path(name).name == name
        actual = (folder / name).read_bytes()
        assert actual == generated[name] == base64.b64decode(item["base64"]), name
        assert len(actual) == item["bytes"] and digest(actual) == item["sha256"], name
    print("PASS: six generated fixtures match the published bytes and hashes.")


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("action", choices=["generate", "check", "run"])
    parser.add_argument("output", type=Path)
    parser.add_argument("--java", default="java")
    parser.add_argument("--tools", type=Path, default=Path("tools"))
    args = parser.parse_args()
    case = json.loads(Path(__file__).with_name("case.json").read_text(encoding="utf-8"))
    if args.action == "generate":
        args.output.mkdir(parents=False, exist_ok=False)
        for name, data in generate().items():
            (args.output / name).write_bytes(data)
    check(args.output, case)
    if args.action != "run":
        return
    # Pin only the two required publisher JARs. No wildcard classpath.
    jars = []
    for item in case["toolDownloads"]:
        if item["file"].endswith(".jar"):
            jar = (args.tools / item["file"]).resolve()
            assert digest(jar.read_bytes()) == item["sha256"], f"Tool hash mismatch: {jar.name}"
            jars.append(str(jar))
    assert len(jars) == 2
    config = Path(__file__).with_name("jhove.conf").resolve()
    assert digest(config.read_bytes()) == case["configurationSha256"], "Configuration hash mismatch"
    reports = args.output / "reports"
    reports.mkdir(exist_ok=False)
    failed = []
    for item in case["files"]:
        command = [args.java, "-Duser.home=.", "-cp", os.pathsep.join(jars), "edu.harvard.hul.ois.jhove.Jhove", "-c", str(config), "-m", "PDF-hul", item["filename"]]
        result = subprocess.run(command, cwd=args.output, capture_output=True, timeout=60)
        (reports / (item["id"] + ".txt")).write_bytes(result.stdout)
        (reports / (item["id"] + ".stderr.txt")).write_bytes(result.stderr)
        text = result.stdout.decode("utf-8", errors="replace")
        match = re.search(r"^\s*Status: (.+)", text, re.M)
        observed = match.group(1).strip() if match else None
        expected = item["reports"][0]["status"]
        expected_error = "PDF-HUL-71" if item["id"] in ("two-short-rows", "missing-trailer") else None
        ids = re.findall(r"^\s*ID: (.+)", text, re.M)
        ids = [value.strip() for value in ids]
        ok = result.returncode == 0 and not result.stderr and observed == expected and ids == ([expected_error] if expected_error else [])
        print(("PASS" if ok else "DIFFERENT RESULT"), item["filename"], observed)
        if not ok:
            failed.append(item["filename"])
    if failed:
        raise SystemExit("Recorded results did not reproduce: " + ", ".join(failed))
    print("PASS: all six statuses and diagnostic identifiers match. This is not a preservation-safety certification.")


if __name__ == "__main__":
    main()
