"""
GLAMWalk -- Volume 4: Libraries & Archives
15_google_books_pd_finder.py

The complete Google Books public-domain finder: normalizing a volume record (always keeping the country its PD verdict was scoped to), deciding PD from several disagreeing signals with a confidence level, and a real paginated PD-filtered search. The key lesson lives in is_public_domain(): free to read is NOT free to republish.

Source: Volume Four, Sections 8.3-8.5
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.
"""

def normalize_volume(item):
    access = item.get("accessInfo") or {}
    return {
        "title": (item.get("volumeInfo") or {}).get("title", ""),
        "is_public_domain": bool(access.get("publicDomain")),
        "pd_country": access.get("country", ""),   # never drop this
        "viewability": access.get("viewability", ""),
    }


def is_public_domain(access):
    """Returns (is_pd, confidence, why) — never a bare boolean."""
    if not access:
        # Not a Google eBook at all. NOT the same as "in copyright."
        return False, "unknown", "no accessInfo block"

    pd_flag = bool(access.get("publicDomain"))
    viewability = (access.get("viewability") or "").upper()
    status = (access.get("accessViewStatus") or "").upper()

    if pd_flag and viewability == "ALL_PAGES" and status == "FULL_PUBLIC_DOMAIN":
        return True, "high", "all three signals agree"

    if pd_flag and viewability == "ALL_PAGES":
        return True, "medium", "PD flag + full access, status silent"

    if pd_flag:
        # Genuinely contradictory — surface it, don't silently pick a side.
        return True, "low", f"PD flag but viewability={viewability}"

    if viewability == "ALL_PAGES":
        # The distinction that matters most in this whole function.
        return False, "unknown", "readable in full, but not public domain"

    return False, "high", "not public domain"


import requests

def search_public_domain(query, country="US", max_pages=2):
    results = []
    for page in range(max_pages):
        params = {
            "q": query,
            "maxResults": 40,
            "startIndex": page * 40,
            "filter": "free-ebooks",   # narrows, does NOT decide
            "country": country,        # pin it, don't let geography decide silently
        }
        response = requests.get(
            "https://www.googleapis.com/books/v1/volumes",
            params=params, timeout=20,
        )
        response.raise_for_status()
        items = response.json().get("items") or []
        if not items:
            break
        for item in items:
            row = normalize_volume(item)
            if row["is_public_domain"]:
                results.append(row)
    return results
