"""
GLAMWalk -- Volume 2: The Gauntlet
05_rijksmuseum_decoy_and_real_api.py

Peeking inside a suspicious local .tar archive before trusting its filename, then the real Rijksmuseum Search API with its three-hop image-resolution chain (object -> VisualItem -> DigitalObject -> access point).

Source: Volume Two, Sections 2.1-2.3
Targets Python 3.11.4 -- see Volume One, Chapter 1.5/1.6.

NOTE: This script makes real network requests to a live public API.
It's safe to run as-is, but requires an internet connection.
"""

import tarfile

def peek_tar_contents(path, n_files=5):
    """Look inside a .tar archive before trusting what its filename implies."""
    with tarfile.open(path, "r") as tar:
        members = tar.getmembers()[:n_files]
        for member in members:
            print(member.name, "-", member.size, "bytes")
        # Actually read one file's content, not just its name:
        if members:
            f = tar.extractfile(members[0])
            if f:
                print("\n--- sample content ---")
                print(f.read(1000).decode("utf-8", errors="replace"))

peek_tar_contents("classification.tar")


import requests

def search_rijksmuseum(object_type, page=0, page_size=50):
    """Search the Rijksmuseum's real collection API by object type."""
    url = "https://data.rijksmuseum.nl/search/collection"
    params = {
        "type": object_type,   # e.g. "painting", "print", "drawing"
        "p": page,
        "ps": page_size,
    }
    response = requests.get(url, params=params, timeout=20)
    response.raise_for_status()
    return response.json()

results = search_rijksmuseum("painting")
print(f"Found {results.get('count', 0)} paintings.")


def resolve_rijksmuseum_image(object_record):
    """
    Walk the real three-hop chain the Rijksmuseum's API requires:
    object -> VisualItem -> DigitalObject -> access point (the actual URL).
    Returns None defensively at any missing hop rather than crashing —
    real records are frequently missing one or more of these links.
    """
    visual_items = object_record.get("hasVisualItem")
    if not visual_items:
        return None

    # Some records return a single dict, others a list — normalize defensively.
    visual_item = visual_items[0] if isinstance(visual_items, list) else visual_items

    digital_objects = visual_item.get("hasDigitalObject")
    if not digital_objects:
        return None
    digital_object = digital_objects[0] if isinstance(digital_objects, list) else digital_objects

    access_points = digital_object.get("hasAccessPoint")
    if not access_points:
        return None
    access_point = access_points[0] if isinstance(access_points, list) else access_points

    return access_point.get("id")   # the actual, loadable image URL
