"""
Pytest fixtures for browser-hybrid tests.
"""

from __future__ import annotations

from unittest.mock import patch

import pytest


def pytest_configure(config):
    """Register custom markers."""
    config.addinivalue_line("markers", "real_connection_check: skip mock_check_connection")


@pytest.fixture(autouse=True)
def mock_check_connection(request):
    """Mock _check_connection for unit tests (Chrome not running in CI).

    Most tests don't have Chrome running, so we mock _check_connection
    to return True. Tests that test connection behavior should use
    @pytest.mark.real_connection_check to skip this mock.
    """
    # Skip mock if test has 'real_connection_check' marker
    if request.node.get_closest_marker("real_connection_check"):
        yield
        return

    # All other tests: mock _check_connection to avoid requiring Chrome
    with patch("browser_hybrid.browser.Browser._check_connection", return_value=True):
        yield


@pytest.fixture
def chrome():
    """
    Provide a Browser connected to real Chrome.

    Skips tests if Chrome is not running with debug port.
    Use this for live integration tests.
    """
    from browser_hybrid import Browser
    from browser_hybrid.errors import ConnectionError

    browser = None
    try:
        browser = Browser()
        yield browser
    except ConnectionError:
        pytest.skip("Chrome not running with --remote-debugging-port=9222")
    finally:
        if browser:
            try:
                browser.close()
            except Exception:
                pass


@pytest.fixture
def tab(chrome):
    """
    Provide a fresh tab for each test.

    Automatically closes the tab after the test.
    """
    tab = chrome.new_tab("about:blank")
    yield tab
    try:
        chrome.close_tab(tab.id)
    except Exception:
        pass


@pytest.fixture
def example_tab(chrome):
    """
    Provide a tab navigated to example.com.

    Automatically closes the tab after the test.
    """
    tab = chrome.goto("https://example.com", wait=1.0)
    yield tab
    try:
        chrome.close_tab(tab.id)
    except Exception:
        pass
