"""
Scraping example for browser-hybrid.
Demonstrates extracting data from a page via the accessibility tree, which
is often much more consistent than the HTML DOM for scraping tasks.

NOTE: Requires Chrome running with --remote-debugging-port=9222
"""

import logging

from browser_hybrid import Browser

# Configure logging to see what's happening
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


def main():
    # 1. Initialize Browser
    try:
        with Browser() as browser:
            # 2. Open login page
            logger.info("Opening GitHub login page...")
            browser.goto("https://github.com/login")

            # 3. Access current page's documentation site link by role/name
            # browser-hybrid parses the AX tree directly for precise data extraction.
            logger.info("Fetching accessibility tree...")
            tree = browser.accessibility_tree()

            # 4. Filter for specific roles like 'link', 'heading', etc.
            # We can easily find all links on the page.
            logger.info("Filtering for all links on the page...")
            links = tree.find_by_role("link")
            print(f"\nFound {len(links)} links on the GitHub login page:")
            for link in links[:10]: # Print first 10
                print(f"- {link.name} (ref: {link.ref}, url: {link.url})")

            # 5. Extract specific data points by name or role
            # Let's find any text that matches a specific pattern.
            logger.info("Looking for a specific link by visible name...")
            search_query = "Terms"
            matches = tree.find_by_name(search_query)

            if matches:
                # Get the link with name "Terms"
                terms_link = matches[0]
                logger.info(f"Successfully found the {search_query} link!")
                # Get its URL for the scraper
                logger.info(f"Target URL for Terms: {terms_link.url}")
            else:
                logger.warning(f"Could not find a link with name '{search_query}'.")

            # 6. Success!
            logger.info("Scraping example completed successfully.")

    except ConnectionError as e:
        logger.error(f"Failed to connect to Chrome: {e}")
        logger.error("Is Chrome running with --remote-debugging-port=9222?")
    except Exception as e:
        logger.error(f"An unexpected error occurred: {e}")


if __name__ == "__main__":
    main()
