"""
GLAMWalk -- Volume 4: Libraries & Archives
01_new_grammar_examples.py

Runnable examples for this volume's new concepts: re.compile() with flags, subclassing HTMLParser, io.BytesIO, and reading XML with xml.etree.ElementTree.

Source: Volume Four, New Grammar for This Volume
Targets Python 3.11.4 -- see Volume One, Chapter 1.5/1.6.
"""

import re

CHAPTER_PATTERN = re.compile(
    r'^\s*(CHAPTER|Chapter)\s+([IVXLCDM]+|\d+)\.?\s*$',
    re.MULTILINE,
)

# A tiny stand-in book, short enough to read at a glance, with two
# real chapter headings in the exact shape CHAPTER_PATTERN looks for.
full_text = "CHAPTER I.\n\nIt was a dark night.\n\nCHAPTER II.\n\nThen it rained."

matches = list(CHAPTER_PATTERN.finditer(full_text))
print(f"Found {len(matches)} chapter headings.")


class Greeter:
    def say_hello(self):
        print("Hello!")

class LoudGreeter(Greeter):        # the (Greeter) means "build on top of Greeter"
    def say_hello(self):            # override just this one method
        print("HELLO!!!")

g = LoudGreeter()
g.say_hello()   # "HELLO!!!" — the overridden version runs, not the original


import io
import zipfile

_buf = io.BytesIO()
with zipfile.ZipFile(_buf, "w") as _zf:
    _zf.writestr("mimetype", "application/epub+zip")
    _zf.writestr("META-INF/container.xml", "<container/>")
epub_bytes = _buf.getvalue()   # a real tiny EPUB, so this runs standalone
with zipfile.ZipFile(io.BytesIO(epub_bytes)) as zf:
    print(zf.namelist())


import xml.etree.ElementTree as ET

xml_text = "<items><item id='a' href='chapter1.xhtml'/></items>"
root = ET.fromstring(xml_text)

for el in root.iter():
    print(el.tag, el.attrib)
