#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""
Core Playwright browser interactions for the Embodiment feature.
"""
from __future__ import annotations
import logging
from playwright.sync_api import sync_playwright, Page, Browser

# A global browser instance to avoid re-launching on every tool call
_browser: Browser | None = None
_page: Page | None = None

def _get_page() -> Page:
    """Get or create a global Playwright page."""
    global _browser, _page
    if _page and _page.is_closed():
        _page = None
    if _page is None:
        p = sync_playwright().start()
        # Use firefox for its lenient sandboxing in headless mode
        _browser = p.firefox.launch(headless=True)
        _page = _browser.new_page()
    return _page

def browser_goto(url: str) -> str:
    """Navigate to a URL."""
    try:
        page = _get_page()
        page.goto(url, wait_until="domcontentloaded", timeout=15000)
        return f"Successfully navigated to {url}"
    except Exception as e:
        return f"Error navigating to {url}: {e}"

def browser_get_content(selector: str | None = None) -> str:
    """Get the text content of the page, optionally filtered by a CSS selector."""
    try:
        page = _get_page()
        if selector:
            elements = page.query_selector_all(selector)
            return "\n".join([el.inner_text() for el in elements])
        return page.content()
    except Exception as e:
        return f"Error getting content: {e}"

def browser_fill(selector: str, text: str) -> str:
    """Fill an input field."""
    try:
        page = _get_page()
        page.fill(selector, text)
        return f"Filled '{selector}' with '{text}'"
    except Exception as e:
        return f"Error filling '{selector}': {e}"

def browser_click(selector: str) -> str:
    """Click an element."""
    try:
        page = _get_page()
        page.click(selector)
        return f"Clicked '{selector}'"
    except Exception as e:
        return f"Error clicking '{selector}': {e}"

def shutdown_browser():
    """Cleanly shut down the global browser instance."""
    global _browser
    if _browser:
        _browser.close()
        _browser = None
