"""
Test 1: Gmail Login Flow

Demonstrates:
- Starting a browser session with stealth mode
- Navigating to Gmail
- Filling login credentials
- Handling 2FA
- Taking screenshot at each step
"""

import os
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from browser_tool import BrowserTool


def test_gmail_login():
    """Test Gmail login flow"""
    
    # Initialize browser with stealth mode
    browser = BrowserTool(
        agent_id="sofiia-test",
        headless=False,  # Set to True for production
        stealth=True,
        proxy=None  # Optional: "http://proxy:8080"
    )
    
    print("=== Starting browser session ===")
    session = browser.start_session()
    print(f"Session: {session['session_id']}, Provider: {session['provider']}")
    
    # Navigate to Gmail
    print("\n=== Navigating to Gmail ===")
    browser.goto("https://mail.google.com/mail/u/0/")
    
    # Take screenshot
    screenshot = browser.screenshot("/tmp/gmail_login.png")
    print(f"Screenshot: {screenshot}")
    
    # Observe page
    print("\n=== Observing page ===")
    actions = browser.observe("What login fields are available?")
    print(f"Found {len(actions)} interactable elements")
    
    # Fill email
    print("\n=== Filling email ===")
    result = browser.fill_form([
        {"name": "identifier", "value": "your-email@gmail.com", "type": "email"}
    ])
    print(f"Form fill result: {result}")
    
    # Click next
    browser.act("Click the Next button")
    
    import time
    time.sleep(2)
    
    # Take screenshot after email
    browser.screenshot("/tmp/gmail_email_filled.png")
    
    # Fill password (use act for natural language)
    print("\n=== Filling password ===")
    try:
        result = browser.act("Type your-password-here into the password field")
    except:
        # Fallback to fill_form
        result = browser.fill_form([
            {"name": "password", "value": "your-password-here", "type": "password"}
        ])
    print(f"Password filled: {result}")
    
    # Click next to login
    browser.act("Click the Next button")
    
    time.sleep(3)
    
    # Check if logged in
    print(f"\nCurrent URL: {browser.get_current_url()}")
    
    # Take screenshot after login attempt
    browser.screenshot("/tmp/gmail_after_login.png")
    
    # If 2FA required, observe and handle
    if "verify" in browser.get_current_url().lower() or "consent" in browser.get_current_url().lower():
        print("\n=== 2FA/CONSENT detected ===")
        actions = browser.observe("What verification options are available?")
        print(f"Available: {actions}")
    
    # Extract inbox info if logged in
    if "inbox" in browser.get_current_url().lower():
        print("\n=== Extracting inbox info ===")
        inbox_data = browser.extract("Extract email subjects from inbox")
        print(f"Found {inbox_data.get('count', 0)} emails")
    
    # Close session
    print("\n=== Closing session ===")
    result = browser.close_session()
    print(f"Status: {result['status']}")
    
    return True


def test_gmail_with_otp():
    """Test Gmail login with OTP handling"""
    
    browser = BrowserTool(agent_id="sofiia-test", headless=False)
    session = browser.start_session()
    
    # Navigate to Gmail
    browser.goto("https://mail.google.com/mail/u/0/")
    
    # Fill email
    browser.fill_form([{"name": "identifier", "value": "your-email@gmail.com"}])
    browser.act("Click Next")
    
    import time
    time.sleep(2)
    
    # Fill password
    browser.fill_form([{"name": "password", "value": "your-password"}])
    browser.act("Click Next")
    
    time.sleep(3)
    
    # Wait for OTP input
    print("\n=== Waiting for OTP ===")
    browser.wait_for("input[type='tel']", timeout=30)
    
    # Observe OTP field
    actions = browser.observe("What OTP input is available?")
    print(f"OTP fields: {actions}")
    
    # Note: You'd need to get OTP from email/Authenticator app
    # Then fill it:
    # browser.fill_form([{"name": "code", "value": "123456", "type": "text"}])
    
    browser.close_session()
    
    return True


if __name__ == "__main__":
    test_gmail_login()
