"""
GLAMWalk -- Volume 5: From Data to Product
01_new_grammar_examples.py

Runnable examples for this volume's new concepts: finally, pathlib.Path, zipfile as a context manager, set/sorted/enumerate, and generator expressions.

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

def do_something_that_might_fail():
    """Stand-in for real code that might raise an error."""
    pass

try:
    do_something_that_might_fail()
except ValueError:
    print("Handled a specific problem.")
finally:
    print("This always runs — success, handled failure, or not.")


from pathlib import Path

p = Path("MetObjects.csv")

print(p.exists())        # True or False — does this file actually exist?
if p.exists():
    print(p.stat().st_size)  # the file's size, in bytes -- only safe if it exists
else:
    print("(skipping .stat() -- MetObjects.csv isn't in this folder)")
print(p.suffix)          # ".csv" — the file extension, pulled out automatically


import zipfile

with zipfile.ZipFile("mybook.epub", "w") as zf:   # build one so this runs
    zf.writestr("mimetype", "application/epub+zip")
    zf.writestr("book.opf", "<package/>")

with zipfile.ZipFile("mybook.epub") as zf:
    names = zf.namelist()          # every file path stored inside the archive
    print("mimetype" in names)     # does a specific required file exist inside it?
    content = zf.read("book.opf")  # read one specific file's contents, as raw bytes


tags_a = {"landscape", "oil", "winter"}
tags_b = {"winter", "portrait"}

combined = tags_a | set(tags_b)   # the | operator means "union" — everything from both, no duplicates
print(combined)   # {"landscape", "oil", "winter", "portrait"} — order not guaranteed


print(sorted(["banana", "apple", "cherry"]))   # ["apple", "banana", "cherry"]


titles = ["Sunflowers", "The Starry Night", "Irises"]

for position, title in enumerate(titles, start=1):
    print(f"{position}. {title}")
# 1. Sunflowers
# 2. The Starry Night
# 3. Irises


words = ["the", "sky", "at", "night"]
STOPWORDS = {"the", "at"}

result = sorted(set(w for w in words if len(w) > 2 and w not in STOPWORDS))
print(result)   # ["night", "sky"]
