"""
Test 3: Form Filling

Demonstrates:
- Complex form filling (registration, checkout, survey)
- Multiple field types (text, checkbox, radio, select)
- File upload
- Form validation
- Multi-step forms
"""

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_registration_form():
    """Test filling a registration form"""
    
    browser = BrowserTool(
        agent_id="sofiia-test",
        headless=False,
        stealth=True
    )
    
    print("=== Starting browser session ===")
    session = browser.start_session()
    print(f"Session: {session['session_id']}")
    
    # Navigate to registration form
    print("\n=== Navigating to registration form ===")
    browser.goto("https://www.w3schools.com/html/html_forms.asp")
    
    # Take initial screenshot
    browser.screenshot("/tmp/form_initial.png")
    
    # Observe form fields
    print("\n=== Observing form ===")
    actions = browser.observe("What form fields are available?")
    print(f"Found {len(actions)} interactable elements")
    
    # Fill text fields
    print("\n=== Filling form fields ===")
    result = browser.fill_form([
        {"name": "firstname", "value": "John", "type": "text"},
        {"name": "lastname", "value": "Doe", "type": "text"},
        {"name": "email", "value": "john.doe@example.com", "type": "email"}
    ])
    print(f"Text fields filled: {result}")
    
    # Fill password fields
    browser.fill_form([
        {"name": "password", "value": "SecurePass123!", "type": "password"},
        {"name": "confirm_password", "value": "SecurePass123!", "type": "password"}
    ])
    
    # Fill checkboxes
    browser.fill_form([
        {"name": "terms", "value": "on", "type": "checkbox", "checked": True},
        {"name": "newsletter", "value": "on", "type": "checkbox", "checked": False}
    ])
    
    # Fill select dropdown
    browser.fill_form([
        {"name": "country", "value": "US", "type": "select"},
        {"name": "language", "value": "en", "type": "select"}
    ])
    
    # Screenshot after filling
    browser.screenshot("/tmp/form_filled.png")
    
    # Submit form using act
    print("\n=== Submitting form ===")
    try:
        result = browser.act("Click the Submit button")
        print(f"Submit result: {result}")
    except Exception as e:
        print(f"Act failed: {e}")
    
    # Wait for response
    import time
    time.sleep(2)
    
    # Check result
    print(f"Current URL: {browser.get_current_url()}")
    browser.screenshot("/tmp/form_submitted.png")
    
    # Extract success message
    result = browser.extract("Extract any success or error message")
    print(f"Result message: {result}")
    
    # Close
    print("\n=== Closing session ===")
    browser.close_session()
    
    return True


def test_checkout_form():
    """Test filling a checkout form"""
    
    browser = BrowserTool(agent_id="sofiia-test", headless=False)
    session = browser.start_session()
    
    # Navigate to checkout
    print("\n=== Navigating to checkout ===")
    browser.goto("https://demo.hook.agency/checkout")
    
    # Fill shipping info
    print("\n=== Filling shipping info ===")
    browser.fill_form([
        {"name": "shipping_first_name", "value": "Jane", "type": "text"},
        {"name": "shipping_last_name", "value": "Smith", "type": "text"},
        {"name": "shipping_address", "value": "123 Main Street", "type": "text"},
        {"name": "shipping_city", "value": "New York", "type": "text"},
        {"name": "shipping_state", "value": "NY", "type": "text"},
        {"name": "shipping_zip", "value": "10001", "type": "text"},
        {"name": "shipping_country", "value": "US", "type": "select"},
        {"name": "shipping_phone", "value": "+1-555-123-4567", "type": "tel"}
    ])
    
    # Fill payment info (demo only!)
    print("\n=== Filling payment info ===")
    browser.fill_form([
        {"name": "card_number", "value": "4111111111111111", "type": "text"},
        {"name": "card_expiry", "value": "12/25", "type": "text"},
        {"name": "card_cvv", "value": "123", "type": "text"}
    ])
    
    # Click place order
    browser.act("Click the Place Order button")
    
    import time
    time.sleep(3)
    
    # Check order confirmation
    browser.screenshot("/tmp/checkout_complete.png")
    result = browser.extract("Extract order confirmation number")
    print(f"Order result: {result}")
    
    browser.close_session()
    
    return True


def test_survey_form():
    """Test filling a survey form"""
    
    browser = BrowserTool(agent_id="sofiia-test", headless=False)
    session = browser.start_session()
    
    # Navigate to survey
    browser.goto("https://www.surveymonkey.com/r/2VDKLVC")
    
    # Get page info
    print(f"Page title: {browser.get_page_text()[:200]}...")
    
    # Fill survey questions using act (natural language)
    questions = [
        "Select Very Satisfied for question about satisfaction",
        "Select Yes for question about recommendation",
        "Select 3-5 years for question about experience"
    ]
    
    for q in questions:
        try:
            result = browser.act(q)
            print(f"  {q}: {result.get('success', False)}")
        except Exception as e:
            print(f"  {q}: skipped")
    
    browser.screenshot("/tmp/survey_complete.png")
    browser.close_session()
    
    return True


if __name__ == "__main__":
    test_registration_form()
