"""
GLAMWalk -- Volume 2: The Gauntlet
12_imslp_countdown_fetch.py

The real technique this project needed for IMSLP: a visible (not headless) browser that respects the site's real funding-mechanism wait, then reads page.url after the wait instead of listening for a download event that IMSLP's inline PDF viewer never fires. Requires: pip install playwright, then `playwright install chromium` once. Uses a real work page URL as input.

Source: Volume Two, Section 5.3 -- IMSLP: Why There's No API to Call
Targets Python 3.11.4 -- see Volume One, Chapter 1.5/1.6.

NOTE: This is a teaching example. Some names (e.g. a placeholder
value or object) stand in for something you'd supply yourself when
adapting the pattern to a real script.
"""

from playwright.sync_api import sync_playwright

def fetch_imslp_score(work_page_url, wait_seconds=20):
    """
    Opens a REAL, visible browser window (not headless — more on why
    in a moment), navigates to a work's IMSLP page, and waits through
    the real countdown before the real file becomes reachable. This
    is not working around IMSLP's funding mechanism; it's the same
    thing a person clicking through the site would do, just automated
    and rate-limited so it never runs unattended at any real scale.
    """
    with sync_playwright() as p:
        browser = p.chromium.launch_persistent_context(
            user_data_dir="./imslp_browser_profile",  # keeps you logged
            headless=False,                             # in and remembered
        )                                                # between runs
        page = browser.new_page()
        page.goto(work_page_url, timeout=30_000)

        # Click the actual download link a human would click.
        page.click("a.download-link")

        # The wait itself, honored rather than defeated.
        page.wait_for_timeout(wait_seconds * 1000)

        # The real breakthrough this project needed here: IMSLP's PDF
        # opens INSIDE the browser's own built-in PDF viewer rather than
        # triggering a "file download" event — so waiting for a download
        # event, the obvious-looking approach, waits forever for
        # something that was never going to happen. The fix is to check
        # where the browser actually navigated to once the wait is over.
        final_url = page.url
        pdf_bytes = page.request.get(final_url).body()
        return pdf_bytes
