# retoor <retoor@molodetz.nl>

import httpx

from devplacepy import stealth
from devplacepy.curl_transport import CurlTransport
from tests.conftest import run_async


def test_factory_returns_async_client():
    client = stealth.stealth_async_client(timeout=5.0)
    assert isinstance(client, httpx.AsyncClient)
    run_async(client.aclose())


def test_curl_active_true():
    assert stealth.curl_active() is True


def test_stealth_transport_is_curl_when_active():
    transport = stealth.stealth_transport()
    assert isinstance(transport, CurlTransport)
    run_async(transport.aclose())


def test_curl_mode_forwards_headers_without_chrome_base():
    client = stealth.stealth_async_client(headers={"Authorization": "Bearer k"})
    assert client.headers.get("authorization") == "Bearer k"
    assert client.headers.get("sec-ch-ua") is None
    run_async(client.aclose())


def test_chrome_base_headers_match_chrome_146():
    headers = stealth.chrome_base_headers()
    assert "Chrome/146.0.0.0" in headers["user-agent"]
    assert headers["sec-ch-ua"] == (
        '"Google Chrome";v="146", "Chromium";v="146", "Not)A;Brand";v="24"'
    )
    assert headers["accept-encoding"] == "gzip, deflate, br, zstd"


def test_fallback_path_injects_chrome_headers(monkeypatch):
    monkeypatch.setattr(stealth, "CURL_AVAILABLE", False)
    transport = stealth.stealth_transport()
    assert isinstance(transport, httpx.AsyncHTTPTransport)
    client = stealth.stealth_async_client()
    assert client.headers.get("sec-ch-ua") is not None
    assert "Chrome/146.0.0.0" in client.headers.get("user-agent", "")
    run_async(client.aclose())
    run_async(transport.aclose())


def test_detect_consent_gate_extracts_accept_url():
    html = """
    <title>DPG Media Privacy Gate</title>
    <script>
        const callbackUrl = new URL(decodeURIComponent('https%3A%2F%2Fnu.nl%2Fprivacy-gate%2Faccept%3FredirectUri%3D%252F'))
    </script>
    <script src="https://myprivacy-static.dpgmedia.net/consent.js"></script>
    """
    gate_url = stealth.detect_consent_gate(html)
    assert gate_url == "https://nu.nl/privacy-gate/accept?redirectUri=%2F"


def test_detect_consent_gate_ignores_ordinary_pages():
    assert stealth.detect_consent_gate("<html><body>hello</body></html>") is None


def test_proxy_threaded_into_curl_transport():
    transport = stealth.stealth_transport(proxy="http://127.0.0.1:8080")
    assert isinstance(transport, CurlTransport)
    assert transport._proxy == "http://127.0.0.1:8080"
    run_async(transport.aclose())
