# This file was auto-generated by Fern from our API Definition.

import typing

if typing.TYPE_CHECKING:
    from ..client import Sandbox


import pydantic
from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel
from .sandbox_urls import SandboxUrls


class SandboxResponse(UniversalBaseModel):
    """
    Response containing sandbox details.
    """

    id: str
    type: str
    provider: str
    region: typing.Optional[str] = None
    status: str
    created_at: str
    expires_at: typing.Optional[str] = None
    urls: typing.Optional[SandboxUrls] = None
    timeout: typing.Optional[int] = None

    if IS_PYDANTIC_V2:
        model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True)  # type: ignore # Pydantic v2
    else:

        class Config:
            frozen = True
            smart_union = True
            extra = pydantic.Extra.allow

    # Private attribute to store client reference (not serialized)
    _client: typing.Optional["Sandbox"] = None

    # ========== Custom methods added for convenience ========== #

    def get_playwright(self, **kwargs):
        """
        Get a Playwright browser instance connected to this browser sandbox.

        This method connects to the browser sandbox via its WebSocket URL and returns
        a Playwright browser instance that can be used to control the remote browser.

        Parameters
        ----------
        **kwargs
            Additional keyword arguments to pass to the Playwright connect_over_cdp method

        Returns
        -------
        Browser
            A Playwright Browser instance connected to the sandbox

        Raises
        ------
        ValueError
            If this is not a browser sandbox or if the WSS URL is not available

        Examples
        --------
        >>> from universal_sandbox import Sandbox
        >>> sandbox = Sandbox(token="YOUR_TOKEN")
        >>> browser_sandbox = sandbox.browser.create(provider="alibaba")
        >>> browser = browser_sandbox.get_playwright()
        >>> page = browser.new_page()
        >>> page.goto("https://example.com")
        >>> browser.close()
        """
        if self.type != "browser":
            raise ValueError(f"get_playwright() is only available for browser sandboxes, but this is a '{self.type}' sandbox")

        if not self.urls or not self.urls.wss_url:
            raise ValueError("WebSocket URL (wss_url) is not available for this sandbox")

        try:
            from playwright.sync_api import sync_playwright
        except ImportError:
            raise ImportError(
                "Playwright is required to use get_playwright(). "
                "Install it with: pip install playwright && playwright install"
            )

        # Connect to the remote browser via WebSocket
        playwright = sync_playwright().start()
        browser = playwright.chromium.connect_over_cdp(self.urls.wss_url, **kwargs)
        return browser

    def delete(self, client: typing.Optional["Sandbox"] = None):
        """
        Delete this sandbox.

        This is a convenience method that calls sandbox.sandboxes.delete(sandbox_id).
        The client reference is automatically injected when the sandbox is created.

        Parameters
        ----------
        client : Sandbox, optional
            The Sandbox client instance to use for deletion. If not provided,
            uses the client reference that was automatically set during creation.

        Returns
        -------
        DeleteResponse
            Response from the delete operation

        Raises
        ------
        ValueError
            If no client reference is available

        Examples
        --------
        >>> from universal_sandbox import Sandbox
        >>> sandbox = Sandbox(token="YOUR_TOKEN")
        >>> browser_sandbox = sandbox.browser.create(provider="alibaba")
        >>> # Delete the sandbox (client reference is automatic)
        >>> browser_sandbox.delete()
        """
        # Use provided client or fall back to stored client reference
        _client = client or self._client

        if _client is None:
            raise ValueError(
                "No client reference available. Either pass the client explicitly: "
                "sandbox_obj.delete(client=sandbox) or ensure the sandbox was created "
                "via the SDK methods."
            )

        return _client.sandboxes.delete(self.id)

