"""
Cookie management example for browser-hybrid.
Demonstrates getting, setting, and deleting cookies.

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 GitHub for demonstration
            logger.info("Opening GitHub...")
            browser.goto("https://github.com")

            # 3. Get all cookies for the current page
            # browser-hybrid can retrieve all cookies associated with the current URL.
            logger.info("Fetching all cookies for GitHub...")
            cookies = browser.get_cookies()
            print(f"\nFound {len(cookies)} cookies for GitHub:")
            for cookie in cookies[:5]: # Print first 5
                print(f"- {cookie.get('name')}: {cookie.get('value')}")

            # 4. Set a custom cookie
            # Great for session management or persistent state.
            new_cookie = {"name": "browser_hybrid_test", "value": "123"}
            logger.info("Setting a new test cookie...")
            browser.set_cookies([new_cookie])

            # 5. Verify the cookie was set
            all_cookies = browser.get_cookies()
            found = any(c.get("name") == "browser_hybrid_test" for c in all_cookies)
            if found:
                logger.info("Test cookie successfully verified!")
            else:
                logger.warning("Test cookie was not found after setting.")

            # 6. Delete the test cookie
            # Always clean up after yourself.
            logger.info("Deleting the test cookie...")
            browser.delete_cookies(name="browser_hybrid_test")

            # 7. Success!
            logger.info("Cookie management demonstration 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()
