from pathlib import Path
import struct
import zlib

import fitz


OUTPUT = Path(__file__).with_name("image-before-table-order.pdf")
PAGE = fitz.paper_rect("a4")
IMAGE_WIDTH, IMAGE_HEIGHT = 160, 90
LEFT, TABLE_TOP = 54, 270
COL_WIDTHS = [95, 190, 70, 95]
ROW_HEIGHT = 30
ROWS = [
    ["Code", "Service", "Qty", "Amount"],
    ["IO-101", "Archive", "2", "$80.00"],
    ["IO-102", "Restore", "1", "$45.00"],
    ["IO-103", "Review", "3", "$120.00"],
]


def png_chunk(kind: bytes, data: bytes) -> bytes:
    return (
        struct.pack(">I", len(data))
        + kind
        + data
        + struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF)
    )


def build_png() -> bytes:
    rows = []
    for y in range(IMAGE_HEIGHT):
        row = bytearray([0])
        for x in range(IMAGE_WIDTH):
            if 12 <= x < 148 and 12 <= y < 78:
                red, green, blue = (16, 185, 129)
            else:
                red, green, blue = (236, 253, 245)
            if 45 <= x < 115 and 32 <= y < 58:
                red, green, blue = (30, 64, 175)
            row.extend((red, green, blue))
        rows.append(bytes(row))
    header = struct.pack(">IIBBBBB", IMAGE_WIDTH, IMAGE_HEIGHT, 8, 2, 0, 0, 0)
    return (
        b"\x89PNG\r\n\x1a\n"
        + png_chunk(b"IHDR", header)
        + png_chunk(b"IDAT", zlib.compress(b"".join(rows), level=9))
        + png_chunk(b"IEND", b"")
    )


document = fitz.open()
page = document.new_page(width=PAGE.width, height=PAGE.height)
page.insert_text((LEFT, 42), "Image Before Table Order", fontsize=16)
page.insert_text((LEFT, 64), "The picture belongs before the service table.", fontsize=9)
page.insert_image(fitz.Rect(90, 100, 330, 220), stream=build_png())

x_positions = [LEFT]
for width in COL_WIDTHS:
    x_positions.append(x_positions[-1] + width)
y_positions = [TABLE_TOP + index * ROW_HEIGHT for index in range(len(ROWS) + 1)]

for x in x_positions:
    page.draw_line((x, y_positions[0]), (x, y_positions[-1]), width=1.0, color=(0, 0, 0))
for y in y_positions:
    page.draw_line((x_positions[0], y), (x_positions[-1], y), width=1.0, color=(0, 0, 0))

for row_index, row in enumerate(ROWS):
    baseline = TABLE_TOP + row_index * ROW_HEIGHT + 20
    for column_index, text in enumerate(row):
        page.insert_text((x_positions[column_index] + 7, baseline), text, fontsize=9)

page.insert_text(
    (LEFT, y_positions[-1] + 30),
    "Order contract: picture, then editable table, then this paragraph.",
    fontsize=9,
)
document.set_metadata(
    {
        "title": "Image Before Table Order",
        "author": "DocBig synthetic regression fixture",
        "subject": "Independent image followed by a bordered table",
    }
)
document.save(OUTPUT, garbage=4, deflate=True)
document.close()
print(f"WROTE={OUTPUT.name} bytes={OUTPUT.stat().st_size}")
