"""
Demonstrate all form detection strategies in browser-hybrid.
Includes support for labels, placeholders, and ARIA labels.

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

import logging

from browser_hybrid import Browser

# Configure logging for demonstration
logging.basicConfig(level=logging.VERBOSE)
logger = logging.getLogger(__name__)


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

            # 3. Type into fields by label (explicit association)
            # No need for IDs or names. Just use the label text.
            logger.info("Filling username form element...")
            success = browser.type_by_name("Username", "test-user")

            if success:
                logger.info("Successfully filled username!")
            else:
                logger.warning("Could not find the username label.")

            # 4. Same for passwords or any other field
            logger.info("Filling password form element...")
            success = browser.type_by_name("Password", "test-password")

            if success:
                logger.info("Successfully filled password!")
            else:
                logger.warning("Could not find the password label.")

            # 5. For search boxes and other fields with placeholders
            # Go to Google Search
            logger.info("Opening Google Search...")
            browser.goto("https://google.com")

            # 6. Type based on placeholder or aria-label
            # Note: Google's search input often has aria-label="Search" or similar.
            logger.info("Searching based on placeholder or aria-label...")
            success = browser.type_by_name("Search", "python browser automation")

            if success:
                logger.info("Successfully typed search query!")
                # Click the search button by its text or aria-label
                browser.click_by_text("Google Search")
                browser.wait_for_load_state()
                logger.info("Search results loaded!")
            else:
                logger.warning("Could not find the search field.")

            # 7. Success!
            logger.info("Form-filling 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()
