"""
GLAMWalk -- Volume 1: Foundations
06_wikidata_sparql.py

A real, working SPARQL query against Wikidata's public endpoint -- every painting by Van Gogh with an attached image. Requires internet.

Source: Volume One, Section 3.4 -- Running a SPARQL Query From Python
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 requests

ENDPOINT = "https://query.wikidata.org/sparql"

QUERY = """
SELECT ?work ?workLabel ?image ?inception WHERE {
  ?work wdt:P170 wd:Q5582 .
  ?work wdt:P18  ?image .
  OPTIONAL { ?work wdt:P571 ?inception . }
  SERVICE wikibase:label {
    bd:serviceParam wikibase:language "en" .
  }
}
"""

# Being a polite API citizen starts with an honest User-Agent —
# Wikidata's own etiquette guidance asks for this, and Wikimedia's
# servers will reject the plain default requests User-Agent outright.
headers = {
    "User-Agent": "GLAMWalkTeachingExample/1.0 (https://soretruth.com; teaching example)",
    "Accept": "application/sparql-results+json",
}

response = requests.get(ENDPOINT, params={"query": QUERY}, headers=headers, timeout=30)
response.raise_for_status()
results = response.json()

for row in results["results"]["bindings"]:
    title = row["workLabel"]["value"]
    image = row["image"]["value"]
    year  = row.get("inception", {}).get("value", "unknown date")
    print(f"{title} ({year}) — {image}")
