import re

from selenium.webdriver.common.by import By
from .base import FunctionalTest


class JasmineTest(FunctionalTest):
    def test_jasmine_specs_pass(self):
        self.browser.get(self.live_server_url + "/static/tests/SpecRunner.html")

        def check_results():
            result = self.browser.find_element(By.CSS_SELECTOR, ".jasmine-overall-result")
            # Word-boundary anchor — Jasmine 6 reports as "N specs, X failures".
            # Plain `"0 failures" in text` matches "10 failures", "20 failures",
            # etc., letting up to 99 failed specs slip past as green.
            if not re.search(r"(?<!\d)0 failures\b", result.text):
                failures = self.browser.find_elements(
                    By.CSS_SELECTOR, ".jasmine-failed .jasmine-description"
                )
                detail = "\n".join(f.text for f in failures) if failures else "(no detail)"
                self.fail(f"{result.text}\nFailing specs:\n{detail}")

        # wait_for_slow w. 60s ceiling — the spec suite has grown well past the
        # 10s MAX_WAIT the default wait_for affords. Under CI contention
        # (parallel Selenium workers competing for CPU) Jasmine's still
        # reporting "Running..." at 10s; pipeline #303 caught this. The
        # check_results body keeps raising AssertionError ("Running..." doesn't
        # match the 0-failures regex) so wait_for_slow naturally retries til
        # the result settles or the timeout fires.
        self.wait_for_slow(check_results, timeout=60)
