"""
GLAMWalk -- Volume 2: The Gauntlet
04_mia_real_production_pattern.py

The real, corrected MIA pattern: try the sanctioned REST API first for every object, and only fall back to the headless browser when the API's own image data comes up empty.

Source: Volume Two, Section 1.5 -- What This Actually Looked Like in Real Production
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.
Targets Python 3.11.4 -- see Volume One, Chapter 1.5/1.6.
"""

import re
import requests
from playwright.sync_api import sync_playwright

IMG_PATTERN = re.compile(r"https://img\.artsmia\.org/web_objects_cache/[^\s\"'<>]+\.jpg")


def fetch_images_via_browser(obj_id):
    """Same function as in 03_headless_browser_fetch.py — included
    here too so this file runs standalone. Requires:
    pip install playwright, then `playwright install chromium` once."""
    url = f"https://collections.artsmia.org/art/{obj_id}/"
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=True)
        page = browser.new_page()
        page.goto(url, wait_until="networkidle", timeout=30_000)
        rendered_html = page.content()
        browser.close()
    return list(dict.fromkeys(IMG_PATTERN.findall(rendered_html)))


def fetch_api_images(obj_id):
    """Step 1, tried first, for every object: the real, working REST API."""
    try:
        response = requests.get(f"https://api.artsmia.org/objects/{obj_id}", timeout=10)
        if response.status_code != 200:
            return []
        data = response.json()
        return [img.get("baseimageurl") for img in data.get("images", []) if img.get("baseimageurl")]
    except Exception:
        return []

def resolve_images(obj_id):
    """The real two-step fallback pattern: API first, browser only if needed."""
    images = fetch_api_images(obj_id)
    if not images:
        images = fetch_images_via_browser(obj_id)   # only reached when the API came up empty
    return images
