"""Recreate a cropped source image of NASA Figure 1 from its public report PDF."""
import argparse
import hashlib
from pathlib import Path

import pymupdf

EXPECTED_SHA256 = "12867527b3417f5f99a39c2bae26b663a2d297157c565ccf3f6d4a1402f41bdf"
PDF_PAGE_INDEX = 8  # physical PDF page 9; printed page 3
CROP_POINTS = (90, 267, 565, 725)  # includes title, figure and full caption; excludes surrounding prose/page number
SCALE = 3
OUTPUT = Path(__file__).with_name("nasa2000-figure1-source-crop.png")


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--source", required=True, type=Path, help="NASA/TP-2000-210387 PDF")
    args = parser.parse_args()
    source_bytes = args.source.read_bytes()
    actual_hash = hashlib.sha256(source_bytes).hexdigest()
    if actual_hash != EXPECTED_SHA256:
        raise SystemExit(f"Unexpected source PDF SHA-256: {actual_hash}")

    with pymupdf.open(stream=source_bytes, filetype="pdf") as document:
        page = document[PDF_PAGE_INDEX]
        clip = pymupdf.Rect(*CROP_POINTS)
        if not page.rect.contains(clip):
            raise SystemExit("Crop rectangle lies outside the source page")
        pixmap = page.get_pixmap(matrix=pymupdf.Matrix(SCALE, SCALE), clip=clip, alpha=False)
        pixmap.save(OUTPUT)

    print({"output": str(OUTPUT), "sha256": hashlib.sha256(OUTPUT.read_bytes()).hexdigest(),
           "source_sha256": actual_hash, "source_pdf_page": PDF_PAGE_INDEX + 1,
           "printed_page": 3, "crop_points": CROP_POINTS, "scale": SCALE})


if __name__ == "__main__":
    main()
