"""
Real-world login flow example for browser-hybrid.
Demonstrates navigating to a login page, filling credentials by label,
clicking the submit button, and verifying the transition to the next state.

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. Fill username/email by label
            # No need for ID, name, or XPath. Just use the label text.
            logger.info("Filling username by label...")
            success = browser.type_by_name("Username or email address", "test-user")

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

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

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

            # 5. Click the "Sign in" button by visible text
            logger.info("Clicking the 'Sign in' button by visible text...")
            success = browser.click_by_text("Sign in")

            if success:
                logger.info("Successfully clicked the button!")
                # Wait for navigation to complete
                browser.wait_for_load_state()
                # Verify logged-in state or error page
                logger.info(f"New URL: {browser.current_tab.url}")
                logger.info(f"Page title: {browser.current_tab.title}")
            else:
                logger.warning("Could not find the 'Sign in' button.")

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