"""
GLAMWalk -- Volume 1: Foundations
10_hathitrust_link_checker.py

A deliberately narrow cross-reference tool: confirms whether HathiTrust holds a matching copy of a book you already have from another source, and returns a link -- never bulk-downloads content.

Source: Volume One, Section 6.3 -- What This Project Actually Built
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.

UPDATE 2: found a real bug in the original request logic, not just the
missing __main__ block. The original built a request against the
*multi-id search-spec* form of the API
(/api/volumes/brief/json/oclc:<number>), which wraps its response in
an extra layer this code never accounted for -- HathiTrust returns
that form keyed on the search spec itself (e.g. "oclc:703523454"), and
only *inside* that key does the familiar {"records": ..., "items": ...}
structure appear. So `data.get("records", {})` on the top level always
came back empty, and the function reported "no match" even for books
HathiTrust genuinely holds -- confirmed directly against HathiTrust's
own Bibliographic API documentation.

Fixed by switching to HathiTrust's *simple single-identifier* form
instead (/api/volumes/brief/oclc/<number>.json), which returns the
flat {"records": ..., "items": ...} shape the parsing code already
expected -- and which HathiTrust's own docs recommend specifically for
one-item-at-a-time lookups, which is exactly this tool's job.

Also worth noting: this script uses the `requests` library rather than
urllib, specifically because `requests` ships its own bundled `certifi`
trust store and uses it by default -- it doesn't lean on the operating
system's certificate store the way urllib does. That sidesteps the
exact Windows trust-store problem Section 5.3's robots.txt checker ran
into; it's part of why this project reaches for `requests` over urllib
in general, not just a style preference.
"""

import requests


def hathitrust_check_link(oclc_number=None, title=None, author=None):
    """
    Cross-check-link-only: ask HathiTrust's catalog whether a matching
    record exists, and return a URL a human can visit — never attempt
    to bulk-fetch full text through this function.
    """
    url = "https://catalog.hathitrust.org/api/volumes/brief/oclc/"
    if not oclc_number:
        # A title/author search is a weaker match and worth flagging
        # to a human reviewer rather than trusting automatically.
        return None

    try:
        response = requests.get(f"{url}{oclc_number}.json", timeout=15)
        response.raise_for_status()
        data = response.json()
    except requests.exceptions.RequestException as e:
        print(f"Could not reach HathiTrust's catalog API: {e}")
        return None

    for record_id, record in data.get("records", {}).items():
        return record.get("recordURL")

    return None


if __name__ == "__main__":
    # A real, verifiable example, straight from HathiTrust's own API
    # documentation: OCLC 703523454 is a Full View, public-domain 1922
    # edition of Melville's "Moby Dick" digitized by the University of
    # Virginia and confirmed present in HathiTrust's catalog.
    test_oclc = "703523454"
    result = hathitrust_check_link(oclc_number=test_oclc)

    if result:
        print(f"HathiTrust holds a matching record for OCLC {test_oclc}:")
        print(f"  {result}")
    else:
        print(f"No matching HathiTrust record found for OCLC {test_oclc}.")
