"""
Basic getting-started example for browser-hybrid.

Shows core capabilities: session management, accessibility tree,
text-based interaction, and screenshot capture.

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 (connects to localhost:9222 by default)
    # browser-hybrid works with your already-running Chrome.
    try:
        with Browser() as browser:
            # 2. Open a new tab and navigate
            logger.info("Navigating to example.com...")
            browser.goto("https://example.com")

            # 3. Access current page title and metadata
            tab = browser.current_tab
            logger.info(f"Page title: {tab.title}")
            logger.info(f"Current URL: {tab.url}")

            # 4. Get the accessibility tree (semantic snapshot)
            # This is how browser-hybrid 'sees' the page.
            logger.info("Fetching accessibility tree...")
            tree = browser.accessibility_tree()

            # 5. Print the tree in a human-readable format
            print("\nAccessibility Tree Overview:")
            print(tree.to_tree_str())

            # 6. Interact with elements by visible text
            # No CSS selectors or XPaths needed for common tasks.
            logger.info("Clicking the 'More information' link...")
            success = browser.click_by_text("More information")

            if success:
                logger.info("Successfully clicked the link!")
                # Wait for navigation to complete
                browser.wait_for_load_state()
                logger.info(f"New URL: {browser.current_tab.url}")
            else:
                logger.warning("Could not find the link with given text.")

            # 7. Take a screenshot
            screenshot_path = "example_basic.png"
            logger.info(f"Saving screenshot to {screenshot_path}...")
            browser.screenshot(screenshot_path)

            # 8. Success!
            logger.info("Basic usage 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()
