"""Tests for SSE log streaming in the session detail view."""

from __future__ import annotations

from typing import TYPE_CHECKING

import pytest
from playwright.sync_api import expect

if TYPE_CHECKING:
    from playwright.sync_api import Page

pytestmark = pytest.mark.e2e


class TestSSEStreaming:
    """SSE log events render log entries in the DOM."""

    def _load_session(self, dashboard: Page) -> None:
        """Click the rich session to trigger SSE streaming."""
        dashboard.get_by_text("work/myapp").first.click()
        dashboard.locator("#log-container").wait_for(state="attached", timeout=10_000)

    def test_log_entries_appear(self, dashboard: Page) -> None:
        """Log entries are inserted into the log container via SSE."""
        self._load_session(dashboard)
        container = dashboard.locator("#log-container")
        expect(container).not_to_be_empty(timeout=15_000)

    def test_log_container_has_children(self, dashboard: Page) -> None:
        """Log container receives child elements from SSE events."""
        self._load_session(dashboard)
        dashboard.locator("#log-container > *").first.wait_for(state="visible", timeout=15_000)
        assert dashboard.locator("#log-container > *").count() >= 1

    def test_sse_connection_established(self, dashboard: Page) -> None:
        """The SSE URL is set on the log container's data attribute."""
        self._load_session(dashboard)
        url = dashboard.locator("#log-container").get_attribute("data-sse-url")
        assert url is not None
        assert "/logs" in url
