from playwright.sync_api import sync_playwright

class BrowserAutomation:
    """Real implementation for browser automation using Playwright."""
    def __init__(self):
        self.playwright = sync_playwright().start()
        # Launching in headless=False so the user can see what the agent is doing
        self.browser = self.playwright.chromium.launch(headless=False)
        self.page = self.browser.new_page()

    def navigate(self, url: str) -> bool:
        """Navigates to the specified URL."""
        try:
            self.page.goto(url, timeout=30000)
            return True
        except Exception:
            return False

    def click_element(self, selector: str) -> bool:
        """Clicks an element based on the CSS selector."""
        try:
            self.page.click(selector, timeout=5000)
            return True
        except Exception:
            return False

    def extract_text(self) -> str:
        """Extracts text from the current page."""
        try:
            return self.page.evaluate('document.body.innerText')
        except Exception:
            return ""

    def close(self):
        try:
            self.browser.close()
            self.playwright.stop()
        except:
            pass

    def __del__(self):
        self.close()
