# retoor <retoor@molodetz.nl>

from tests.conftest import BASE_URL
from devplacepy.database import get_table, refresh_snapshot


def _clear_deepsearch_jobs():
    refresh_snapshot()
    jobs = get_table("jobs")
    for row in list(jobs.find(kind="deepsearch")):
        jobs.delete(uid=row["uid"])
    sessions = get_table("deepsearch_sessions")
    for row in list(sessions.find()):
        sessions.delete(uid=row["uid"])


def test_deepsearch_page_loads(page, app_server):
    page.goto(f"{BASE_URL}/tools/deepsearch", wait_until="domcontentloaded")
    page.locator("[data-deepsearch-tool]").wait_for(state="visible")
    page.locator("[data-deepsearch-form] textarea[name='query']").wait_for(state="visible")
    page.locator("[data-deepsearch-run]").wait_for(state="visible")


def test_progress_timeline_has_all_phases(page, app_server):
    page.goto(f"{BASE_URL}/tools/deepsearch", wait_until="domcontentloaded")
    timeline = page.locator("[data-deepsearch-timeline]")
    timeline.wait_for(state="attached")
    for phase in ("planning", "searching", "crawling", "indexing", "analysis", "synthesis"):
        assert timeline.locator(f"[data-deepsearch-phase='{phase}']").count() == 1


def test_form_submit_reveals_live_progress(alice):
    page, _user = alice
    try:
        page.goto(f"{BASE_URL}/tools/deepsearch", wait_until="domcontentloaded")
        page.locator("[data-deepsearch-form]").wait_for(state="visible")
        page.locator("[data-deepsearch-form] textarea[name='query']").fill(
            "history of the transistor"
        )
        page.locator("[data-deepsearch-run]").click()
        live = page.locator("[data-deepsearch-live]")
        live.wait_for(state="visible")
        live.locator("[data-deepsearch-bar]").wait_for(state="attached")
        live.locator("[data-deepsearch-status]").wait_for(state="visible")
    finally:
        _clear_deepsearch_jobs()
