"""
GLAMWalk -- Volume 2: The Gauntlet
01_new_grammar_examples.py

Runnable examples for this volume's new Python concepts: try/except, class + subclassing basics, the context-manager (__enter__/__exit__) protocol, and isinstance().

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

import requests

try:
    response = requests.get("https://collections.artsmia.org/api/some-endpoint", timeout=15)
    response.raise_for_status()
except requests.exceptions.SSLError:
    print("An SSL/transport problem — see Chapter 1 for what this usually means.")
except requests.exceptions.Timeout:
    print("The server didn't answer in time.")
except Exception as e:
    print(f"Something else went wrong: {e}")


class Counter:
    def __init__(self, start=0):
        self.count = start   # self.count is THIS Counter's own private value

    def increment(self):
        self.count += 1

    def show(self):
        print(f"Count is now {self.count}")

c1 = Counter()          # make one Counter, starting at 0
c2 = Counter(start=100)  # make a completely separate Counter, starting at 100

c1.increment()
c1.increment()
c1.show()   # "Count is now 2"
c2.show()   # "Count is now 100" — c2 was never touched, it's a separate object


class Loud:
    def __enter__(self):
        print("Entering the block.")
        return self   # whatever this returns becomes the "as x" value

    def __exit__(self, exc_type, exc_val, exc_tb):
        print("Leaving the block — this runs even if something went wrong inside it.")

with Loud() as x:
    print("Inside the block.")


value = ["a", "b", "c"]

if isinstance(value, list):
    first_item = value[0]
else:
    first_item = value   # it wasn't a list at all — treat the bare value as the only item

print(first_item)
