"""Regression test exported by Argus from finding 20261104_205214_159651_96e6cd:1.

Deleted task reappears after page reload

Argus verified this symptom on a fresh load (2/2): 'Update API documentation' is present at http://127.0.0.1:51845/tasks.
Expected behavior: After deleting 'Update API documentation' and seeing 'Task deleted successfully', the task stays absent after reloading /tasks.

The test replays the recorded journey and asserts the opposite of the symptom,
so it fails while the bug is present and passes once the bug is fixed.
Run it with `python test_argus_20261104_205214_159651_96e6cd_1_deleted_task_reappears_after_page_reload.py` or pytest, using a Python that has Playwright
and Chromium (the interpreter that runs Argus has both). Set ARGUS_BASE_URL to
test another origin.
"""

import os
import re
from urllib.parse import urljoin

from playwright.sync_api import sync_playwright

BASE_URL = os.environ.get("ARGUS_BASE_URL", "http://127.0.0.1:51845")
SYMPTOM_MARKER = "ARGUS_SYMPTOM_PRESENT"
LOGIN_WALL_PHRASES = ["please log in", "please sign in", "log in to", "sign in to", "session expired", "session has expired", "you have been logged out", "you are logged out", "log in to continue", "sign in to continue"]


def _url(path):
    return urljoin(BASE_URL, path)


ROW_SELECTOR = "li, tr, .card, .list-item, [class*=\"item\"], [class*=\"row\"]"


def _in_row(page, text, find):
    """`find(scope)` within the row showing `text`: the innermost row holding
    the text and the control, not a list container that also matches."""
    rows = page.locator(ROW_SELECTOR).filter(has_text=text).filter(has=find(page))
    return find(rows.filter(has_not=rows)).first


def _matches(text, haystack):
    """Argus's word-boundary rule on whitespace-normalised text."""
    haystack = " ".join(haystack.lower().split())
    needle = " ".join(text.lower().split())
    before = r"(?<!\w)" if re.match(r"\w", needle) else ""
    after = r"(?!\w)" if re.search(r"\w$", needle) else ""
    return re.search(before + re.escape(needle) + after, haystack) is not None


def _check_page(page, response):
    if response is not None and response.status >= 400:
        raise RuntimeError(f"fresh-load check returned HTTP {response.status}")
    page.wait_for_load_state("networkidle")
    text = page.inner_text("body").lower()
    login_heading = page.get_by_role(
        "heading", name=re.compile(r"^(sign in|log in|login)$", re.IGNORECASE)
    )
    password_login = page.locator('input[type="password"]:visible').count() and login_heading.count()
    if password_login or any(phrase in text for phrase in LOGIN_WALL_PHRASES):
        raise RuntimeError("fresh-load check hit a login wall")


def _present(text, page, max_scrolls=20):
    """Text and field values, scrolling (bounded) like Argus's fresh-load check
    so a row a virtualized or lazy list renders further down is still found."""
    page.wait_for_load_state("networkidle")
    last_y = None
    for scrolls in range(max_scrolls + 1):
        for frame in page.frames:
            if frame.is_detached():
                continue
            body = frame.locator("body")
            if not body.count():
                continue
            values = frame.eval_on_selector_all("input, textarea", "els => els.map(e => e.value)")
            if _matches(text, body.inner_text() + " " + " ".join(values)):
                return True
        y, at_bottom = page.evaluate(
            "() => [window.scrollY, "
            "window.innerHeight + window.scrollY >= document.documentElement.scrollHeight - 2]"
        )
        if scrolls == max_scrolls or at_bottom or y == last_y:
            return False
        last_y = y
        page.evaluate("() => window.scrollBy(0, 1000)")
        page.wait_for_timeout(400)
    return False


def test_deleted_task_reappears_after_page_reload():
    with sync_playwright() as playwright:
        browser = playwright.chromium.launch()
        page = browser.new_page()
        # Accept a dialog only during a step that accepted it in the session;
        # any other dialog is dismissed, as it was there.
        accept_dialog = {"pending": False}

        def _on_dialog(dialog):
            if accept_dialog["pending"]:
                accept_dialog["pending"] = False
                dialog.accept()
            else:
                dialog.dismiss()

        page.on("dialog", _on_dialog)
        try:
            page.goto(_url("/tasks"))
            accept_dialog["pending"] = True
            _in_row(page, "Update API", lambda scope: scope.get_by_role("button", name="Delete", exact=True)).click()
            page.wait_for_load_state("networkidle")
            accept_dialog["pending"] = False
            page.goto("about:blank")
            response = page.goto(_url("/tasks"))
            _check_page(page, response)
            assert not _present("Update API documentation", page), SYMPTOM_MARKER + ": 'Update API documentation' is still shown"
        finally:
            browser.close()


if __name__ == "__main__":
    test_deleted_task_reappears_after_page_reload()
    print("PASS: the symptom is gone")
