"""
GLAMWalk -- Volume 2: The Gauntlet
11_cpdl_api_search_and_resolve.py

CPDL's real, working MediaWiki API: a plain search, and the fix for its one real bug -- wiki-link file references that look fetchable but aren't, resolved the same way Volume Three's IIIF section resolves a reference into a real URL.

Source: Volume Two, Section 5.2 -- CPDL: A Real API, and One Real Bug
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

CPDL_API = "https://www.cpdl.org/wiki/api.php"

def cpdl_search(query, limit=10):
    params = {
        "action": "query",
        "list": "search",
        "srsearch": query,
        "srlimit": limit,
        "format": "json",
    }
    headers = {"User-Agent": "GLAMWalkTeachingExample/1.0 (https://soretruth.com)"}
    response = requests.get(CPDL_API, params=params, headers=headers, timeout=20)
    response.raise_for_status()
    return response.json()["query"]["search"]


def cpdl_resolve_media_url(filename):
    """Turn a bare MediaWiki filename (or a [[Media:...]] wikitext
    reference, stripped down to the filename) into a real, fetchable URL."""
    params = {
        "action": "query",
        "titles": f"File:{filename}",
        "prop": "imageinfo",
        "iiprop": "url",
        "format": "json",
    }
    headers = {"User-Agent": "GLAMWalkTeachingExample/1.0 (https://soretruth.com)"}
    response = requests.get(CPDL_API, params=params, headers=headers, timeout=20)
    response.raise_for_status()
    pages = response.json()["query"]["pages"]
    for page in pages.values():
        imageinfo = page.get("imageinfo")
        if imageinfo:
            return imageinfo[0]["url"]
    return None


if __name__ == "__main__":
    results = cpdl_search("Ave Maria")
    print(f"Found {len(results)} CPDL page(s) matching \"Ave Maria\":\n")
    for r in results[:5]:
        print(f"  {r['title']}")
