"""Tests für dsi_discovery — Shadow-DOM/versteckte Link-Erfassung (Feature A)
+ Interaktions-Fixpunkt (Feature B)."""

from __future__ import annotations

import asyncio

import pytest

from services.dsi_discovery import (
    _dom_grew,
    _expand_to_fixpoint,
    _find_dsi_links,
)


# ── Pure: Fixpunkt-Stopbedingung ────────────────────────────────────


def test_dom_grew_threshold():
    assert _dom_grew(100, 200) is True
    assert _dom_grew(100, 133) is True       # 33 > 32 (Schwelle)
    assert _dom_grew(100, 110) is False      # unter Schwelle
    assert _dom_grew(100, 100) is False


# ── Browser-Integration (skip wenn kein chromium) ───────────────────


def _chromium_ok() -> bool:
    try:
        from playwright.sync_api import sync_playwright
        with sync_playwright() as p:
            b = p.chromium.launch(headless=True, args=["--no-sandbox"])
            b.close()
        return True
    except Exception:
        return False


_BROWSER = _chromium_ok()

_FIXTURE = """
<html><body>
  <a href="https://example.com/datenschutz" style="display:none">Datenschutz</a>
  <details><summary>Mehr</summary>
    <a href="https://example.com/impressum">Impressum</a>
  </details>
  <div id="host"></div>
  <script>
    const sr = document.getElementById('host').attachShadow({mode:'open'});
    sr.innerHTML =
      '<a href="https://example.com/cookie-richtlinie">Cookies</a>';
  </script>
</body></html>
"""


async def _scan_fixture():
    from playwright.async_api import async_playwright
    async with async_playwright() as p:
        b = await p.chromium.launch(headless=True, args=["--no-sandbox"])
        try:
            page = await (await b.new_context()).new_page()
            await page.set_content(_FIXTURE)
            tel = await _expand_to_fixpoint(page)
            links = await _find_dsi_links(page, "example.com")
            details_open = await page.evaluate(
                "() => !!(document.querySelector('details')"
                " && document.querySelector('details').open)")
            return links, tel, details_open
        finally:
            await b.close()


@pytest.mark.skipif(not _BROWSER, reason="chromium nicht installiert")
def test_shadow_and_hidden_links_discovered():
    links, tel, details_open = asyncio.get_event_loop().run_until_complete(
        _scan_fixture())
    hrefs = [l["href"] for l in links]
    # A: Shadow-DOM-Link gefunden + geflaggt
    assert any("cookie-richtlinie" in h for h in hrefs), hrefs
    assert any(l.get("in_shadow") for l in links)
    # A: versteckter (display:none) Link gefunden + als hidden geflaggt
    assert any("datenschutz" in h for h in hrefs), hrefs
    assert any(not l["visible"] for l in links)
    # B: Fixpunkt lief + hat das geschlossene Akkordeon geoeffnet
    assert tel["rounds"] >= 1
    assert details_open is True
