import platform

import pytest

from gsearch_mcp_cli.core.browser import build_chrome_args, find_browser, parse_port_from_stderr
from gsearch_mcp_cli.exceptions import BrowserNotFoundError


def test_parse_port_from_stderr_standard():
    line = "DevTools listening on ws://127.0.0.1:9345/devtools/browser/abc-123"
    assert parse_port_from_stderr(line) == 9345


def test_parse_port_from_stderr_different_port():
    line = "DevTools listening on ws://127.0.0.1:12345/devtools/browser/xyz"
    assert parse_port_from_stderr(line) == 12345


def test_parse_port_from_stderr_no_match():
    assert parse_port_from_stderr("some other output") is None
    assert parse_port_from_stderr("") is None
    assert parse_port_from_stderr("Starting Chrome...") is None


def test_build_chrome_args_includes_headless():
    args = build_chrome_args("/usr/bin/chrome", "/tmp/profile")
    assert "--headless=new" in args
    assert "--remote-debugging-port=0" in args
    assert "--remote-allow-origins=http://localhost" in args
    assert args[0] == "/usr/bin/chrome"
    assert "--user-data-dir=/tmp/profile" in args


def test_build_chrome_args_includes_platform_flags():
    args = build_chrome_args("/usr/bin/chrome", "/tmp/profile")
    assert "--disable-gpu" in args
    if platform.system() == "Linux":
        assert "--disable-dev-shm-usage" in args
        assert "--no-sandbox" in args


def test_find_browser_auto():
    """Should find at least one browser on the test system."""
    try:
        path = find_browser("auto")
        assert path and len(path) > 0
    except BrowserNotFoundError:
        pytest.skip("No Chromium browser installed on this system")


def test_find_browser_invalid():
    with pytest.raises(BrowserNotFoundError):
        find_browser("nonexistent_browser_xyz")
