from __future__ import annotations

import sys
from pathlib import Path

import pytest

from reddit_mcp import cookie_manager


def _candidate(
    *,
    profile_name: str = "Profile 1",
    rows: int = 0,
    mtime: float = 123.0,
    cookie_probe_error: str | None = None,
) -> cookie_manager.BrowserProfileCandidate:
    return cookie_manager.BrowserProfileCandidate(
        browser_label="Google Chrome",
        executable_path=Path("."),
        user_data_dir=Path("."),
        profile_name=profile_name,
        profile_dir=Path("."),
        cookies_db=Path("."),
        reddit_cookie_rows=rows,
        cookies_mtime=mtime,
        cookie_probe_error=cookie_probe_error,
    )


@pytest.mark.anyio
async def test_setup_cookies_uses_playwright_collector_and_persists_when_valid(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    called: dict[str, object] = {}

    async def fake_collect(*, silent: bool) -> dict[str, str]:
        called["silent"] = silent
        return {"reddit_session": "session-token", "csrf_token": "csrf-token"}

    async def fake_validate(_cookies: dict[str, str]) -> cookie_manager.CookieValidationResult:
        return cookie_manager.CookieValidationResult(
            valid=True,
            status_code=200,
            final_url="https://www.reddit.com/api/me.json",
            content_type="application/json",
            response_snippet=None,
            cookie_names=["csrf_token", "reddit_session"],
            error=None,
        )

    monkeypatch.setattr(cookie_manager, "_collect_reddit_cookies_via_playwright", fake_collect)
    monkeypatch.setattr(
        cookie_manager,
        "_shutdown_browser_processes_if_requested",
        lambda *, silent: called.setdefault("shutdown", silent),
    )
    monkeypatch.setattr(cookie_manager, "_validate_cookies", fake_validate)
    monkeypatch.setattr(cookie_manager, "_save_cookies", lambda cookies: called.setdefault("saved", cookies))
    monkeypatch.setattr(cookie_manager, "save_meta", lambda meta: called.setdefault("meta", meta))

    cookies = await cookie_manager.setup_cookies(silent=True, shutdown_browser=True)

    assert called.get("silent") is True
    assert called.get("shutdown") is True
    assert called.get("saved") == cookies
    assert isinstance(called.get("meta"), dict)
    assert "cookies_created_at" in called["meta"]
    assert cookies["reddit_session"] == "session-token"


@pytest.mark.anyio
async def test_setup_cookies_on_windows_uses_guided_browser_login_for_interactive_runs(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    called: dict[str, object] = {}

    async def fake_guided(*, silent: bool) -> dict[str, str]:
        called["guided"] = silent
        return {"reddit_session": "guided-session"}

    async def fake_playwright(*, silent: bool) -> dict[str, str]:
        called["playwright"] = silent
        return {"reddit_session": "playwright-session"}

    async def fake_validate(_cookies: dict[str, str]) -> cookie_manager.CookieValidationResult:
        return cookie_manager.CookieValidationResult(
            valid=True,
            status_code=200,
            final_url="https://www.reddit.com/api/me.json",
            content_type="application/json",
            response_snippet=None,
            cookie_names=["reddit_session"],
            error=None,
        )

    monkeypatch.setattr(cookie_manager.sys, "platform", "win32")
    monkeypatch.setattr(cookie_manager, "_collect_reddit_cookies_via_guided_browser_login", fake_guided)
    monkeypatch.setattr(cookie_manager, "_collect_reddit_cookies_via_playwright", fake_playwright)
    monkeypatch.setattr(cookie_manager, "_validate_cookies", fake_validate)
    monkeypatch.setattr(cookie_manager, "_save_cookies", lambda cookies: called.setdefault("saved", cookies))
    monkeypatch.setattr(cookie_manager, "save_meta", lambda meta: called.setdefault("meta", meta))

    cookies = await cookie_manager.setup_cookies(silent=False, shutdown_browser=False)

    assert called.get("guided") is False
    assert "playwright" not in called
    assert called.get("saved") == cookies
    assert cookies["reddit_session"] == "guided-session"


@pytest.mark.anyio
async def test_setup_cookies_on_windows_keeps_silent_mode_non_interactive(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    called: dict[str, object] = {}

    async def fake_guided(*, silent: bool) -> dict[str, str]:
        called["guided"] = silent
        return {"reddit_session": "guided-session"}

    async def fake_playwright(*, silent: bool) -> dict[str, str]:
        called["playwright"] = silent
        return {"reddit_session": "playwright-session"}

    async def fake_validate(_cookies: dict[str, str]) -> cookie_manager.CookieValidationResult:
        return cookie_manager.CookieValidationResult(
            valid=True,
            status_code=200,
            final_url="https://www.reddit.com/api/me.json",
            content_type="application/json",
            response_snippet=None,
            cookie_names=["reddit_session"],
            error=None,
        )

    monkeypatch.setattr(cookie_manager.sys, "platform", "win32")
    monkeypatch.setattr(cookie_manager, "_collect_reddit_cookies_via_guided_browser_login", fake_guided)
    monkeypatch.setattr(cookie_manager, "_collect_reddit_cookies_via_playwright", fake_playwright)
    monkeypatch.setattr(cookie_manager, "_validate_cookies", fake_validate)
    monkeypatch.setattr(cookie_manager, "_save_cookies", lambda cookies: called.setdefault("saved", cookies))
    monkeypatch.setattr(cookie_manager, "save_meta", lambda meta: called.setdefault("meta", meta))

    cookies = await cookie_manager.setup_cookies(silent=True, shutdown_browser=False)

    assert called.get("playwright") is True
    assert "guided" not in called
    assert called.get("saved") == cookies
    assert cookies["reddit_session"] == "playwright-session"


@pytest.mark.anyio
async def test_setup_cookies_does_not_persist_when_validation_fails(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    called: dict[str, object] = {}

    async def fake_collect(*, silent: bool) -> dict[str, str]:
        called["silent"] = silent
        return {"reddit_session": "invalid-token"}

    monkeypatch.setattr(cookie_manager, "_collect_reddit_cookies_via_playwright", fake_collect)
    monkeypatch.setattr(
        cookie_manager,
        "_shutdown_browser_processes_if_requested",
        lambda *, silent: called.setdefault("shutdown", silent),
    )
    async def fake_validate(_cookies: dict[str, str]) -> cookie_manager.CookieValidationResult:
        return cookie_manager.CookieValidationResult(
            valid=False,
            status_code=403,
            final_url="https://www.reddit.com/api/me.json",
            content_type="text/html; charset=utf-8",
            response_snippet="<html>blocked</html>",
            cookie_names=["reddit_session", "csrf_token"],
            error=None,
        )

    monkeypatch.setattr(cookie_manager, "_validate_cookies", fake_validate)
    monkeypatch.setattr(cookie_manager, "_save_cookies", lambda cookies: called.setdefault("saved", cookies))

    with pytest.raises(RuntimeError, match="validation failed") as exc_info:
        await cookie_manager.setup_cookies(silent=True, shutdown_browser=True)

    assert called.get("silent") is True
    assert "saved" not in called
    message = str(exc_info.value)
    assert "status 403" in message
    assert "text/html" in message
    assert "reddit_session" in message
    assert "csrf_token" in message
    assert "invalid-token" not in message


def test_shutdown_browser_processes_is_noop_off_windows(monkeypatch: pytest.MonkeyPatch) -> None:
    messages: list[str] = []

    monkeypatch.setattr(cookie_manager.sys, "platform", "darwin")
    monkeypatch.setattr(cookie_manager, "console_print", lambda message: messages.append(message))

    cookie_manager._shutdown_browser_processes_if_requested(silent=False)

    assert "Windows profile-lock issues" in messages[0]


def test_shutdown_browser_processes_raises_when_windows_shutdown_leaves_processes(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    monkeypatch.setattr(cookie_manager.sys, "platform", "win32")
    states = [["chrome"], ["chrome"]]
    monkeypatch.setattr(cookie_manager, "_list_running_windows_browser_processes", lambda: states.pop(0))
    monkeypatch.setattr(cookie_manager, "_run_windows_browser_shutdown", lambda: None)

    with pytest.raises(RuntimeError, match="Could not fully close browser processes automatically"):
        cookie_manager._shutdown_browser_processes_if_requested(silent=True)


def test_shutdown_browser_processes_only_targets_chrome_and_edge(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setattr(cookie_manager.sys, "platform", "win32")
    script_payload: dict[str, str] = {}

    def fake_run(args, **kwargs):  # type: ignore[no-untyped-def]
        script_payload["script"] = args[-1]

        class Result:
            returncode = 0
            stdout = "[]"

        return Result()

    monkeypatch.setattr(cookie_manager.subprocess, "run", fake_run)

    assert cookie_manager._list_running_windows_browser_processes() == []
    assert "'chrome'" in script_payload["script"]
    assert "'msedge'" in script_payload["script"]
    assert "chromium" not in script_payload["script"]


def test_windows_locked_profile_error_points_users_to_shutdown_browser_flag() -> None:
    candidate = _candidate()
    original_platform = cookie_manager.sys.platform
    cookie_manager.sys.platform = "win32"
    try:
        error = cookie_manager._copy_locked_profile_error(candidate, Path("Network/Cookies"))
    finally:
        cookie_manager.sys.platform = original_platform

    message = str(error)
    assert "--shutdown-browser" in message
    assert "save any unfinished work in Chrome or Edge" in message
    assert "AI assistant" in message


@pytest.mark.anyio
async def test_guided_login_message_mentions_cloud_desktop_openclaw(
    monkeypatch: pytest.MonkeyPatch,
    tmp_path: Path,
) -> None:
    import types

    messages: list[str] = []
    popen_calls: list[list[str]] = []

    async def fake_wait_for_guided_login_session(_context: object, _page: object) -> dict[str, str]:
        return {"reddit_session": "guided-session"}

    class FakePage:
        url = "https://www.reddit.com/login"

    class FakeContext:
        pages = [FakePage()]

        async def new_page(self) -> FakePage:
            return FakePage()

    class FakeBrowser:
        contexts = [FakeContext()]

        async def close(self) -> None:
            return None

    class FakeChromium:
        async def connect_over_cdp(self, endpoint: str) -> FakeBrowser:
            assert endpoint == "http://127.0.0.1:9333"
            return FakeBrowser()

    class FakePlaywright:
        chromium = FakeChromium()

        async def __aenter__(self) -> "FakePlaywright":
            return self

        async def __aexit__(self, exc_type, exc, tb) -> None:
            return None

    class FakeProcess:
        pid = 1234

        def poll(self) -> int | None:
            return None

        def terminate(self) -> None:
            return None

        def wait(self, timeout: float | None = None) -> int:
            del timeout
            return 0

    monkeypatch.setitem(
        sys.modules,
        "playwright.async_api",
        types.SimpleNamespace(async_playwright=lambda: FakePlaywright()),
    )
    monkeypatch.setattr(cookie_manager, "console_print", lambda message: messages.append(message))
    monkeypatch.setattr(cookie_manager, "_wait_for_guided_login_session", fake_wait_for_guided_login_session)
    monkeypatch.setattr(cookie_manager, "ensure_config_dir", lambda: None)
    monkeypatch.setattr(cookie_manager, "BROWSER_PROFILE", tmp_path / "browser-profile")
    monkeypatch.setattr(
        cookie_manager,
        "_select_guided_login_browser_installation",
        lambda: ("Google Chrome", tmp_path / "chrome.exe"),
    )
    monkeypatch.setattr(cookie_manager, "_allocate_debug_port", lambda: 9333)
    async def fake_wait_for_cdp_ready(_port: int) -> None:
        return None

    monkeypatch.setattr(cookie_manager, "_wait_for_cdp_ready", fake_wait_for_cdp_ready)
    monkeypatch.setattr(cookie_manager, "_terminate_process", lambda _process: None)
    monkeypatch.setattr(
        cookie_manager.subprocess,
        "Popen",
        lambda args, stdout, stderr: (popen_calls.append(args) or FakeProcess()),
    )

    await cookie_manager._collect_reddit_cookies_via_guided_browser_login(silent=False)

    rendered = "\n".join(messages)
    assert "Opening a dedicated local browser window for Reddit login" in rendered
    assert "real local browser" in rendered
    assert "cloud desktop" in rendered
    assert "OpenClaw" in rendered
    assert "signs in to Reddit in the browser window that just opened" in rendered
    assert len(popen_calls) == 1
    assert popen_calls[0][0] == str(tmp_path / "chrome.exe")
    assert f"--user-data-dir={tmp_path / 'browser-profile'}" in popen_calls[0]
    assert "--no-first-run" in popen_calls[0]
    assert "--disable-sync" in popen_calls[0]
    assert "https://www.reddit.com/login" in popen_calls[0]


@pytest.mark.anyio
async def test_guided_login_prefers_google_chrome_then_edge(
    monkeypatch: pytest.MonkeyPatch,
    tmp_path: Path,
) -> None:
    chrome = tmp_path / "chrome.exe"
    edge = tmp_path / "msedge.exe"
    chrome.write_text("", encoding="utf-8")
    edge.write_text("", encoding="utf-8")

    monkeypatch.setattr(
        cookie_manager,
        "_known_browser_installations",
        lambda: [
            ("Google Chrome", chrome, tmp_path / "chrome-user-data"),
            ("Microsoft Edge", edge, tmp_path / "edge-user-data"),
        ],
    )

    browser_label, executable_path = cookie_manager._select_guided_login_browser_installation()

    assert browser_label == "Google Chrome"
    assert executable_path == chrome


@pytest.mark.anyio
async def test_guided_login_requires_real_local_browser_installation(
    monkeypatch: pytest.MonkeyPatch,
    tmp_path: Path,
) -> None:
    monkeypatch.setattr(cookie_manager, "ensure_config_dir", lambda: None)
    monkeypatch.setattr(cookie_manager, "BROWSER_PROFILE", tmp_path / "browser-profile")
    monkeypatch.setattr(cookie_manager, "_known_browser_installations", lambda: [])
    monkeypatch.setattr(cookie_manager.sys, "platform", "win32")

    with pytest.raises(RuntimeError, match="Chrome or Edge"):
        await cookie_manager._collect_reddit_cookies_via_guided_browser_login(silent=False)

    assert not (tmp_path / "browser-profile").exists()


def test_filter_reddit_cookies_keeps_only_reddit_domains() -> None:
    all_cookies = [
        {"name": "reddit_session", "value": "a", "domain": ".reddit.com"},
        {"name": "csrf_token", "value": "b", "domain": "reddit.com"},
        {"name": "other", "value": "c", "domain": ".example.com"},
    ]

    result = cookie_manager._filter_reddit_cookies(all_cookies)

    assert result == {"reddit_session": "a", "csrf_token": "b"}


@pytest.mark.anyio
async def test_collect_silent_mode_never_waits_for_source_profile_session(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    candidate = _candidate(rows=2)
    reads: list[str] = []
    waited: list[bool] = []

    async def fake_read(
        selected: cookie_manager.BrowserProfileCandidate,
        *,
        async_playwright: object,
    ) -> dict[str, str]:
        del async_playwright
        reads.append(selected.profile_name)
        return {}

    async def fake_wait_for_source_profile_session(
        _candidates: list[cookie_manager.BrowserProfileCandidate],
        *,
        async_playwright: object,
    ) -> dict[str, str]:
        del async_playwright
        waited.append(True)
        return {}

    monkeypatch.setattr(cookie_manager, "_discover_browser_profile_candidates", lambda: [candidate])
    monkeypatch.setattr(cookie_manager, "_read_cookies_from_profile_copy", fake_read)
    monkeypatch.setattr(
        cookie_manager,
        "_wait_for_source_profile_session",
        fake_wait_for_source_profile_session,
    )

    with pytest.raises(RuntimeError, match="No reusable Reddit session found"):
        await cookie_manager._collect_reddit_cookies_via_playwright(silent=True)

    assert reads == ["Profile 1"]
    assert waited == []


@pytest.mark.anyio
async def test_collect_non_silent_waits_for_source_profile_session_when_no_reusable(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    candidate = _candidate(profile_name="Profile 4", rows=0, mtime=456.0)
    waited: list[list[str]] = []

    async def fake_wait_for_source_profile_session(
        candidates: list[cookie_manager.BrowserProfileCandidate],
        *,
        async_playwright: object,
    ) -> dict[str, str]:
        del async_playwright
        waited.append([c.profile_name for c in candidates])
        return {"reddit_session": "session-token"}

    monkeypatch.setattr(cookie_manager, "_discover_browser_profile_candidates", lambda: [candidate])
    monkeypatch.setattr(cookie_manager, "_should_hint_windows_shutdown_browser", lambda _candidates: False)
    monkeypatch.setattr(
        cookie_manager,
        "_wait_for_source_profile_session",
        fake_wait_for_source_profile_session,
    )

    cookies = await cookie_manager._collect_reddit_cookies_via_playwright(silent=False)

    assert cookies["reddit_session"] == "session-token"
    assert waited == [["Profile 4"]]


@pytest.mark.anyio
async def test_collect_non_silent_windows_lock_hint_skips_wait_and_points_to_shutdown_browser(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    candidate = _candidate(
        profile_name="Profile 4",
        rows=0,
        mtime=456.0,
        cookie_probe_error="database is locked",
    )
    waited: list[bool] = []

    async def fake_wait_for_source_profile_session(
        candidates: list[cookie_manager.BrowserProfileCandidate],
        *,
        async_playwright: object,
    ) -> dict[str, str]:
        del candidates, async_playwright
        waited.append(True)
        return {}

    monkeypatch.setattr(cookie_manager, "_discover_browser_profile_candidates", lambda: [candidate])
    monkeypatch.setattr(
        cookie_manager,
        "_wait_for_source_profile_session",
        fake_wait_for_source_profile_session,
    )
    monkeypatch.setattr(cookie_manager.sys, "platform", "win32")

    with pytest.raises(RuntimeError, match="could not read the local cookie database reliably"):
        await cookie_manager._collect_reddit_cookies_via_playwright(silent=False)

    assert waited == []


@pytest.mark.anyio
async def test_collect_non_silent_windows_running_browser_skips_wait_and_points_to_shutdown_browser(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    candidate = _candidate(
        profile_name="Profile 4",
        rows=0,
        mtime=456.0,
    )
    waited: list[bool] = []

    async def fake_wait_for_source_profile_session(
        candidates: list[cookie_manager.BrowserProfileCandidate],
        *,
        async_playwright: object,
    ) -> dict[str, str]:
        del candidates, async_playwright
        waited.append(True)
        return {}

    monkeypatch.setattr(cookie_manager, "_discover_browser_profile_candidates", lambda: [candidate])
    monkeypatch.setattr(
        cookie_manager,
        "_wait_for_source_profile_session",
        fake_wait_for_source_profile_session,
    )
    monkeypatch.setattr(cookie_manager, "_list_running_windows_browser_processes", lambda: ["chrome"])
    monkeypatch.setattr(cookie_manager.sys, "platform", "win32")

    with pytest.raises(RuntimeError, match="--shutdown-browser"):
        await cookie_manager._collect_reddit_cookies_via_playwright(silent=False)

    assert waited == []


def test_should_hint_windows_shutdown_browser_only_when_probe_failed_on_windows(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    candidate = _candidate(
        profile_name="Profile 4",
        rows=0,
        mtime=456.0,
        cookie_probe_error="database is locked",
    )

    monkeypatch.setattr(cookie_manager.sys, "platform", "win32")
    monkeypatch.setattr(cookie_manager, "_list_running_windows_browser_processes", lambda: [])
    assert cookie_manager._should_hint_windows_shutdown_browser([candidate]) is True

    assert cookie_manager._should_hint_windows_shutdown_browser([_candidate()]) is False

    monkeypatch.setattr(cookie_manager, "_list_running_windows_browser_processes", lambda: ["chrome"])
    assert cookie_manager._should_hint_windows_shutdown_browser([_candidate()]) is True

    monkeypatch.setattr(cookie_manager.sys, "platform", "darwin")
    assert cookie_manager._should_hint_windows_shutdown_browser([candidate]) is False


@pytest.mark.anyio
async def test_collect_non_silent_errors_when_no_browser_profile_found(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    monkeypatch.setattr(cookie_manager, "_discover_browser_profile_candidates", lambda: [])

    with pytest.raises(RuntimeError, match="No compatible local Chrome/Edge profile found"):
        await cookie_manager._collect_reddit_cookies_via_playwright(silent=False)


@pytest.mark.anyio
async def test_collect_non_silent_errors_when_source_profile_session_times_out(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    candidate = _candidate(profile_name="Profile 7", rows=0, mtime=789.0)

    async def fake_wait_for_source_profile_session(
        _candidates: list[cookie_manager.BrowserProfileCandidate],
        *,
        async_playwright: object,
    ) -> dict[str, str]:
        del async_playwright
        return {}

    monkeypatch.setattr(cookie_manager, "_discover_browser_profile_candidates", lambda: [candidate])
    monkeypatch.setattr(cookie_manager, "_should_hint_windows_shutdown_browser", lambda _candidates: False)
    monkeypatch.setattr(
        cookie_manager,
        "_wait_for_source_profile_session",
        fake_wait_for_source_profile_session,
    )

    with pytest.raises(RuntimeError, match="No reusable Reddit session appeared"):
        await cookie_manager._collect_reddit_cookies_via_playwright(silent=False)


@pytest.mark.anyio
async def test_wait_for_source_profile_session_checks_all_candidates_until_found(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    first = _candidate(profile_name="Profile 1")
    second = _candidate(profile_name="Profile 2")
    calls: list[str] = []

    async def fake_read(
        selected: cookie_manager.BrowserProfileCandidate,
        *,
        async_playwright: object,
    ) -> dict[str, str]:
        del async_playwright
        calls.append(selected.profile_name)
        if selected.profile_name == "Profile 2":
            return {"reddit_session": "session-token"}
        return {}

    monkeypatch.setattr(cookie_manager, "_read_cookies_from_profile_copy", fake_read)

    cookies = await cookie_manager._wait_for_source_profile_session(
        [first, second],
        async_playwright=object(),
    )

    assert cookies["reddit_session"] == "session-token"
    assert calls == ["Profile 1", "Profile 2"]


@pytest.mark.anyio
async def test_wait_for_source_profile_session_returns_empty_on_timeout(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    candidate = _candidate()
    calls: list[str] = []

    async def fake_read(
        selected: cookie_manager.BrowserProfileCandidate,
        *,
        async_playwright: object,
    ) -> dict[str, str]:
        del async_playwright
        calls.append(selected.profile_name)
        return {}

    monkeypatch.setattr(cookie_manager, "_read_cookies_from_profile_copy", fake_read)
    monkeypatch.setattr(cookie_manager, "LOGIN_WAIT_TIMEOUT_SECONDS", 0.01)
    monkeypatch.setattr(cookie_manager, "SOURCE_PROFILE_POLL_INTERVAL_MS", 1)

    cookies = await cookie_manager._wait_for_source_profile_session(
        [candidate],
        async_playwright=object(),
    )

    assert cookies == {}
    assert calls


@pytest.mark.anyio
async def test_wait_for_guided_login_session_returns_when_reddit_session_appears(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class FakePage:
        def is_closed(self) -> bool:
            return False

    class FakeClient:
        def __init__(self) -> None:
            self.calls = 0

        async def send(self, _method: str) -> dict[str, list[dict[str, str]]]:
            self.calls += 1
            if self.calls == 1:
                return {"cookies": [{"name": "csv", "value": "x", "domain": ".reddit.com"}]}
            return {"cookies": [{"name": "reddit_session", "value": "token", "domain": ".reddit.com"}]}

    class FakeContext:
        async def new_cdp_session(self, _page: object) -> FakeClient:
            return FakeClient()

    async def fake_sleep(_seconds: float) -> None:
        return None

    monkeypatch.setattr(cookie_manager.anyio, "sleep", fake_sleep)

    cookies = await cookie_manager._wait_for_guided_login_session(
        FakeContext(),
        FakePage(),
    )

    assert cookies == {"reddit_session": "token"}
