"""
Network interception example for browser-hybrid.
Demonstrates request/response monitoring, logging API calls,
and intercepting failed requests.

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. Get connection to tab (used for registering handlers)
            logger.info("Opening GitHub...")
            browser.goto("https://github.com")

            # 3. Create interception callbacks
            # Monitor all outgoing requests
            def on_request(request):
                logger.info(f"Outgoing request: {request.get('url')}")

            # Monitor all incoming responses
            def on_response(response):
                logger.info(f"Incoming response from: {response.get('url')}")

            # 4. Register interception handlers via browser.py methods
            # Note: These will log all network activity to stdout.
            logger.info("Registering network interception handlers...")
            browser.on_request(on_request)
            browser.on_response(on_response)

            # 5. Trigger some network activity
            # Navigating back and forth will cause several requests to fire.
            logger.info("Reloading GitHub to trigger intercepted events...")
            browser.current_tab.reload()

            # 6. Success!
            logger.info("Network interception 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()
