"""Form fill benchmark."""

from .base import BaseScenario


class FormFillScenario(BaseScenario):
    """Benchmark form filling operations.
    
    Navigate to a form page, fill fields, measure time.
    
    Test: Fill https://www.w3schools.com/html/tryit.asp?filename=tryhtml_form_submit
    with name and email fields (using a simpler form).
    """

    name = "form_fill"
    description = "Fill form fields and submit"
    runs = 15

    TARGET_URL = "https://www.w3schools.com/html/tryit.asp?filename=tryhtml_form_text"

    def setup(self) -> None:
        pass

    def run_browser_hybrid(self):
        """browser-hybrid: fill form by label."""
        browser = self._bh_browser()
        browser.navigate(self.TARGET_URL)
        # Switch to the iframe that has the form
        try:
            browser.switch_frame("iframeResult")
        except Exception:
            pass  # iframe switch may vary
        browser.fill_form({"Name": "Test User", "Email": "test@example.com"})
        browser.close()
        return True

    def run_playwright(self):
        """Playwright: fill form."""
        from playwright.sync_api import sync_playwright
        with sync_playwright() as p:
            browser = p.chromium.launch()
            page = browser.new_page()
            page.goto(self.TARGET_URL)
            frame = page.frame_locator("iframe#iframeResult")
            frame.get_by_placeholder("Name").fill("Test User")
            frame.get_by_placeholder("Email").fill("test@example.com")
            browser.close()
        return True

    def run_selenium(self):
        """Selenium: fill form."""
        from selenium import webdriver
        from selenium.webdriver.chrome.options import Options
        from selenium.webdriver.common.by import By
        from selenium.webdriver.support.ui import WebDriverWait
        from selenium.webdriver.support import expected_conditions as EC

        opts = Options()
        opts.add_argument("--headless")
        driver = webdriver.Chrome(options=opts)
        driver.get(self.TARGET_URL)
        wait = WebDriverWait(driver, 10)
        wait.until(EC.frame_to_be_available_and_switch_to_it("iframeResult"))
        driver.find_element(By.NAME, "fname").send_keys("Test User")
        driver.find_element(By.NAME, "email").send_keys("test@example.com")
        driver.quit()
        return True

    def run_agent_browser(self):
        """agent-browser: fill form."""
        try:
            from agent_browser import Browser
            browser = Browser()
            browser.navigate(self.TARGET_URL)
            browser.fill_form({"Name": "Test User", "Email": "test@example.com"})
            browser.close()
            return True
        except ImportError:
            return False

    def _bh_browser(self):
        from browser_hybrid import Browser
        return Browser()
