import json
import subprocess
from pathlib import Path

import pytest

from tests.dashboard_bundle import dashboard


WIDGETS = Path(__file__).parents[1] / "frontend" / "widgets.js"


@pytest.mark.anyio
async def test_dashboard_renders_repo_mix_placeholder_before_javascript_runs():
    html = await dashboard()
    server_rendered_html = html.split("<script>", 1)[0]

    assert '<div class="small" id="repo-mix">Loading…</div>' in server_rendered_html


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

    assert "data.error ? 'Degraded · ' + data.error : 'Live · updated just now'" in html


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

    assert "Work items unavailable." in html
    assert "Kickoff issue" not in html
    assert "Live UI implementation" not in html
    assert "Docker build and push" not in html
    assert "Agent UI delta binding" not in html


def test_repo_mix_renders_counts_from_shared_context_snapshot():
    script = f"""
const renderRepoMix = require({json.dumps(str(WIDGETS))});
const element = {{ innerHTML: '' }};
renderRepoMix(element, {{
  repos:[{{}},{{}}],
  issues:[{{state:'open'}},{{state:'closed'}}],
  pull_requests:[{{}},{{}},{{}}],
}});
if (!element.innerHTML.includes('<div class="value">2</div>') ||
    !element.innerHTML.includes('<div class="value">1</div>') ||
    !element.innerHTML.includes('<div class="value">3</div>')) {{
  throw new Error('shared snapshot counts were not rendered: ' + element.innerHTML);
}}
"""

    subprocess.run(
        ["node", "-e", script], check=True, capture_output=True, text=True
    )
