#!/usr/bin/env python3
"""Build test-comic.cbz, the sample archive used in the article.

It reproduces problems commonly found in comic archives: unpadded page
numbers, an unnumbered cover, a two-page spread, an AVIF page, macOS junk
entries, and a ComicInfo.xml with a right-to-left flag and a page table.
The pages are blank grey PNGs; only names, sizes and structure matter.

Usage: python3 make_test_comic.py   (writes test-comic.cbz next to it)
"""

import os
import struct
import zipfile
import zlib


def png(width, height, grey=200):
    def chunk(kind, data):
        return (struct.pack(">I", len(data)) + kind + data
                + struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF))
    row = b"\x00" + bytes([grey]) * width
    return (b"\x89PNG\r\n\x1a\n"
            + chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 0, 0, 0, 0))
            + chunk(b"IDAT", zlib.compress(row * height, 9))
            + chunk(b"IEND", b""))


COMICINFO = """<?xml version="1.0" encoding="utf-8"?>
<ComicInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Series>Test Comic</Series>
  <LanguageISO>ja</LanguageISO>
  <Manga>YesAndRightToLeft</Manga>
  <Pages>
{rows}
  </Pages>
</ComicInfo>
"""


def main():
    pages = {"cover.png": png(400, 600)}
    for n in range(1, 13):
        pages[f"{n}.png"] = png(800, 600) if n == 7 else png(400, 600)
    rows = "\n".join(f'    <Page Image="{i}" ImageSize="{len(b)}" />'
                     for i, b in enumerate(pages.values()))
    out = os.path.join(os.path.dirname(os.path.abspath(__file__)), "test-comic.cbz")
    with zipfile.ZipFile(out, "w", zipfile.ZIP_STORED) as z:
        def add(name, data):
            # A fixed timestamp keeps the archive byte-identical between runs.
            z.writestr(zipfile.ZipInfo(name, (2026, 10, 30, 0, 0, 0)), data)
        for name, data in pages.items():
            add(name, data)
        # An AVIF page: only the file-type box, enough to show how it is classified.
        add("13.avif", b"\x00\x00\x00\x1cftypavif\x00\x00\x00\x00avifmif1miaf")
        add("__MACOSX/._1.png", b"\x00\x05\x16\x07")
        add(".DS_Store", b"\x00\x00\x00\x01Bud1")
        add("ComicInfo.xml", COMICINFO.format(rows=rows))
    print(f"Wrote {out}")


if __name__ == "__main__":
    main()
