"""
GLAMWalk -- Volume 1: Foundations
07_batching_and_idempotent_writes.py

Two small, reusable patterns: chunk() for batching a long list into polite-sized pieces, and an idempotent SQLite writer using INSERT OR IGNORE so running the script twice never creates duplicates.

Source: Volume One, Section 3.5 -- The Two Functions That Do Most of the Real Work
Targets Python 3.11.4 -- see Volume One, Chapter 1.5/1.6.
"""

def chunk(items, size=50):
    """Split a list into size-N pieces — the shape every batched pipeline needs."""
    for i in range(0, len(items), size):
        yield items[i:i + size]

print("Batching demo:")
artist_qids = ["Q5582", "Q762", "Q296"]  # a small example list

for i, batch in enumerate(chunk(artist_qids, size=50), 1):
    print(f"  batch {i}: {batch}")
    # In real use, build one SPARQL query per batch using a VALUES clause
    # to ask about all of them at once instead of one query per artist


import sqlite3

conn = sqlite3.connect("art_catalog.db")
conn.execute("""
    CREATE TABLE IF NOT EXISTS artworks (
        wikidata_id TEXT PRIMARY KEY,
        title TEXT,
        image_url TEXT,
        year TEXT
    )
""")

def save_artwork(wikidata_id, title, image_url, year):
    conn.execute(
        "INSERT OR IGNORE INTO artworks (wikidata_id, title, image_url, year) "
        "VALUES (?, ?, ?, ?)",
        (wikidata_id, title, image_url, year),
    )
    conn.commit()


print("\nIdempotent-write demo:")
# Call save_artwork() twice with the same data
print("  called save_artwork() 2 times (first pass)")
save_artwork("Q123", "Starry Night", "https://example.com/img.jpg", "1889")
save_artwork("Q124", "The Persistence of Memory", "https://example.com/img2.jpg", "1931")

print("  called save_artwork() 2 more times with the same rows (second pass)")
save_artwork("Q123", "Starry Night", "https://example.com/img.jpg", "1889")
save_artwork("Q124", "The Persistence of Memory", "https://example.com/img2.jpg", "1931")

# Verify no duplicates were created
rows = conn.execute("SELECT COUNT(*) FROM artworks").fetchone()[0]
print(f"  rows actually in the table: {rows} <-- proves the second pass created no duplicates")
