"""Write returns.pdf: two pages of the shop's returns policy, no library needed."""

PAGES = [
    [("B", 20, 720, "Returns"),
     ("R", 11, 690, "A return must be posted within 30 days of delivery."),
     ("B", 14, 650, "What we refund"),
     ("R", 11, 626, "The price of the item and the original postage."),
     ("R", 11, 610, "Return postage is paid by the customer.")],
    [("B", 14, 720, "How long it takes"),
     ("R", 11, 696, "Refunds are paid within 5 working days of the parcel arriving."),
     ("B", 14, 656, "Damaged items"),
     ("R", 11, 632, "Send a photo to support before you post a damaged item."),
     ("R", 11, 616, "We pay the return postage for anything damaged.")],
]

FONT = {"B": "/F1", "R": "/F2"}
streams = ["".join(f"BT {FONT[f]} {s} Tf 72 {y} Td ({t}) Tj ET\n" for f, s, y, t in page)
           for page in PAGES]
kids = " ".join(f"{3 + i} 0 R" for i in range(len(PAGES)))
objects = [
    "<< /Type /Catalog /Pages 2 0 R >>",
    f"<< /Type /Pages /Kids [{kids}] /Count {len(PAGES)} >>",
]
for i in range(len(PAGES)):
    objects.append(
        "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources "
        "<< /Font << /F1 %d 0 R /F2 %d 0 R >> >> /Contents %d 0 R >>"
        % (3 + len(PAGES), 4 + len(PAGES), 5 + len(PAGES) + i))
objects.append("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold >>")
objects.append("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>")
for body in streams:
    objects.append(f"<< /Length {len(body)} >>\nstream\n{body}endstream")

out, offsets = "%PDF-1.4\n", []
for number, body in enumerate(objects, 1):
    offsets.append(len(out))
    out += f"{number} 0 obj\n{body}\nendobj\n"
start = len(out)
out += f"xref\n0 {len(objects) + 1}\n0000000000 65535 f \n"
out += "".join(f"{offset:010d} 00000 n \n" for offset in offsets)
out += f"trailer\n<< /Size {len(objects) + 1} /Root 1 0 R >>\nstartxref\n{start}\n%%EOF\n"

with open("returns.pdf", "w") as handle:
    handle.write(out)
print(len(out), "bytes, ascii:", out.isascii())
