import pytest

from tests.dashboard_bundle import dashboard


@pytest.mark.anyio
async def test_one_context_snapshot_updates_every_context_backed_panel():
    html = await dashboard()

    assert '<script src="static/context-poller.js"></script>' in html
    assert "createContextPoller({" in html
    assert "renderContextSnapshot(data)" in html
    assert "renderRepoMix(qs('#repo-mix'), data)" in html
    assert "setInterval(tickWidgets, 2000)" not in html
    assert "updateRepoMix(qs('#repo-mix'), fetch)" not in html
    assert "setInterval(load, 8000)" not in html
    assert "document.addEventListener('visibilitychange'" in html


@pytest.mark.anyio
async def test_one_live_snapshot_updates_work_and_activity_on_one_timer():
    html = await dashboard()

    assert "fetch('api/v1/live'" in html
    assert "onSnapshot: renderLiveSnapshot" in html
    assert "createContextPoller.buildRevisionQuery(revisions)" in html
    assert "workChanged = contextChanged || notificationsChanged" in html
    assert "renderContextSnapshot(snapshot.context)" in html
    assert "paintEventStream(snapshot.events)" in html
    assert "loadEventStream" not in html
    assert "5000" not in html


@pytest.mark.anyio
async def test_dashboard_announces_when_recent_snapshot_is_revalidating():
    html = await dashboard()

    assert "snapshot.freshness?.revalidating" in html
    assert "Refreshing · showing recent snapshot" in html


@pytest.mark.anyio
async def test_dashboard_announces_failed_refresh_and_retry_without_blanking_panels():
    html = await dashboard()

    assert "snapshot.freshness?.degraded" in html
    assert "Refresh failed · showing last known data" in html
    assert "snapshot.freshness.retry_in_seconds" in html


@pytest.mark.anyio
async def test_dashboard_reports_each_live_section_from_its_own_freshness():
    html = await dashboard()

    assert "snapshot.freshness?.sections?.notifications" in html
    assert "snapshot.freshness?.sections?.events" in html
    assert "const notificationsFresh = Array.isArray(snapshot.notifications)" not in html
    assert "Unread updates unavailable · showing last known updates" in html
    assert "Activity refresh failed · showing last activity" in html


@pytest.mark.anyio
async def test_operator_refresh_and_reconnect_supersede_a_stalled_live_request():
    html = await dashboard()

    assert "async function fetchLiveSnapshot(revisions = {}, { signal } = {})" in html
    assert "headers: { Accept: 'application/json' },\n      signal," in html
    assert "function load() { return contextPoller.refresh({ force: true }); }" in html
    assert "contextPoller.refresh({ force: true });" in html


@pytest.mark.anyio
async def test_stalled_refresh_keeps_the_last_snapshot_with_specific_guidance():
    html = await dashboard()

    assert "e.name === 'TimeoutError'" in html
    assert "Update delayed · showing last snapshot" in html
