"""Build a valid sample EPUB 3 and eleven damaged copies (stdlib only)."""
import io, os, sys, zipfile, struct
OUT = sys.argv[1] if len(sys.argv) > 1 else 'fixtures'
os.makedirs(OUT, exist_ok=True)
N = 6
def chapter(i, body=None):
    body = body if body is not None else ''.join(
        f'<p>Chapter {i}, paragraph {p}: the lighthouse keeper wrote the tide table by hand and checked it twice.</p>' for p in range(1, 6))
    return f'<?xml version="1.0" encoding="utf-8"?>\n<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"><head><title>Chapter {i}</title></head><body><h1>Chapter {i}</h1>{body}</body></html>\n'
CONTAINER = '<?xml version="1.0" encoding="UTF-8"?>\n<container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container"><rootfiles><rootfile full-path="{p}" media-type="application/oebps-package+xml"/></rootfiles></container>\n'
def opf(n=N, extra_item=''):
    items = ''.join(f'<item id="c{i}" href="c{i}.xhtml" media-type="application/xhtml+xml"/>' for i in range(1, n+1))
    refs = ''.join(f'<itemref idref="c{i}"/>' for i in range(1, n+1))
    return ('<?xml version="1.0" encoding="utf-8"?>\n<package version="3.0" unique-identifier="id" xmlns="http://www.idpf.org/2007/opf" xmlns:dc="http://purl.org/dc/elements/1.1/">'
            '<metadata><dc:identifier id="id">urn:uuid:3f0c8a52-0000-4000-8000-000000000001</dc:identifier><dc:title>The Tide Table</dc:title><dc:language>en</dc:language>'
            '<meta property="dcterms:modified">2026-11-24T00:00:00Z</meta></metadata>'
            f'<manifest><item id="nav" href="nav.xhtml" media-type="application/xhtml+xml" properties="nav"/>{items}{extra_item}</manifest><spine>{refs}</spine></package>\n')
NAV = '<?xml version="1.0" encoding="utf-8"?>\n<html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops"><head><title>Contents</title></head><body><nav epub:type="toc"><ol>' + ''.join(f'<li><a href="c{i}.xhtml">Chapter {i}</a></li>' for i in range(1, N+1)) + '</ol></nav></body></html>\n'

def build(name, entries, mimetype_mode='store-first'):
    """entries: list of (path, text). mimetype_mode: store-first | deflate | last | absent"""
    buf = io.BytesIO()
    with zipfile.ZipFile(buf, 'w') as z:
        def add(p, t, method=zipfile.ZIP_DEFLATED):
            zi = zipfile.ZipInfo(p, date_time=(2026, 11, 24, 0, 0, 0)); zi.compress_type = method
            z.writestr(zi, t)
        if mimetype_mode == 'store-first': add('mimetype', 'application/epub+zip', zipfile.ZIP_STORED)
        if mimetype_mode == 'deflate': add('mimetype', 'application/epub+zip', zipfile.ZIP_DEFLATED)
        for p, t in entries: add(p, t)
        if mimetype_mode == 'last': add('mimetype', 'application/epub+zip', zipfile.ZIP_STORED)
    data = buf.getvalue()
    open(os.path.join(OUT, name), 'wb').write(data)
    return data

def base_entries(opf_path='OEBPS/content.opf', container_path=None, opf_text=None, chapters=None, drop=None):
    e = [('META-INF/container.xml', CONTAINER.format(p=container_path or opf_path)), (opf_path, opf_text or opf()), ('OEBPS/nav.xhtml', NAV)]
    for i in range(1, N+1):
        p = f'OEBPS/c{i}.xhtml'
        if drop and p in drop: continue
        e.append((p, (chapters or {}).get(i, chapter(i))))
    return e

good = build('01-valid.epub', base_entries())
# 02 interrupted download: last 25% of bytes gone (central directory lost)
open(os.path.join(OUT, '02-truncated-download.epub'), 'wb').write(good[: int(len(good) * 0.75)])
# 03 mimetype compressed (common after re-zipping a folder with a normal zip tool)
build('03-mimetype-compressed.epub', base_entries(), 'deflate')
# 04 container.xml points to a file that does not exist
build('04-container-wrong-path.epub', base_entries(opf_path='OEBPS/package.opf', container_path='OEBPS/content.opf'))
# 05 no package document at all
build('05-no-opf.epub', [x for x in base_entries() if not x[0].endswith('.opf')])
# 06 manifest lists a chapter that is not in the archive
build('06-missing-chapter-file.epub', base_entries(drop={'OEBPS/c4.xhtml'}))
# 07 one chapter has an unescaped ampersand (not well-formed XHTML)
build('07-bad-ampersand.epub', base_entries(chapters={3: chapter(3, '<p>Salt & pepper, the keeper said.</p>')}))
# 08 one chapter is a store error page instead of XHTML
ERR = 'sorry something went wrong loading your content. Check the table of contents or try paging forward.'
build('08-one-damaged-chapter.epub', base_entries(chapters={5: ERR}))
# 09 three of six chapters empty or error text (half the book)
build('09-half-damaged.epub', base_entries(chapters={2: '', 4: ERR, 6: ''}))
# 10 wrong uncompressed size in one entry header (local and central)
d = bytearray(good)
name = b'OEBPS/c2.xhtml'
for sig, size_off in ((b'PK\x03\x04', 22), (b'PK\x01\x02', 24)):
    i = d.find(sig)
    while i >= 0:
        nlen_off = 26 if sig == b'PK\x03\x04' else 28
        nlen = struct.unpack_from('<H', d, i + nlen_off)[0]
        hdr = 30 if sig == b'PK\x03\x04' else 46
        if bytes(d[i + hdr:i + hdr + nlen]) == name:
            real = struct.unpack_from('<I', d, i + size_off)[0]
            struct.pack_into('<I', d, i + size_off, real + 4096)
        i = d.find(sig, i + 4)
open(os.path.join(OUT, '10-wrong-size-header.epub'), 'wb').write(bytes(d))
# 11 a web page saved with an .epub name
open(os.path.join(OUT, '11-html-not-zip.epub'), 'w').write('<!DOCTYPE html><html><head><title>Download</title></head><body>Your download will start shortly.</body></html>\n')
# 12 an Adobe ACSM ticket renamed to .epub (not a book, a DRM licence request)
open(os.path.join(OUT, '12-acsm-ticket.epub'), 'w').write('<fulfillmentToken fulfillmentType="buy" xmlns="http://ns.adobe.com/adept"><distributor>urn:uuid:00000000-0000-0000-0000-000000000000</distributor></fulfillmentToken>\n')
print(sorted(os.listdir(OUT)))
