# retoor <retoor@molodetz.nl>

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


def _clear_isslop_data():
    refresh_snapshot()
    jobs = get_table("jobs")
    for row in list(jobs.find(kind="isslop")):
        jobs.delete(uid=row["uid"])
    analyses = get_table("isslop_analyses")
    for row in list(analyses.find()):
        analyses.delete(uid=row["uid"])


def test_isslop_page_loads(page, app_server):
    page.goto(f"{BASE_URL}/tools/isslop", wait_until="domcontentloaded")
    page.locator("[data-isslop-tool]").wait_for(state="visible")
    page.locator("[data-isslop-form] input[name='url']").wait_for(state="visible")
    page.locator("[data-isslop-run]").wait_for(state="visible")
    page.locator(".isslop-history-title").wait_for(state="visible")


def test_isslop_tools_menu_links_to_page(page, app_server):
    page.goto(f"{BASE_URL}/tools", wait_until="domcontentloaded")
    card = page.locator(".tools-grid a.tool-card[href='/tools/isslop']")
    card.wait_for(state="visible")
    assert "AI Usage Analyzer" in card.inner_text()


def test_isslop_submit_opens_live_report(alice):
    page, _user = alice
    try:
        page.goto(f"{BASE_URL}/tools/isslop", wait_until="domcontentloaded")
        page.locator("[data-isslop-form] input[name='url']").fill(
            "https://github.com/owner/repository"
        )
        page.locator("[data-isslop-run]").click()
        page.wait_for_url("**/tools/isslop/*/report", wait_until="domcontentloaded")
        page.locator("dp-isslop-run").wait_for(state="attached")
        page.locator("[data-isslop-report] .sidebar-card").wait_for(state="visible")
        page.locator(".breadcrumb").wait_for(state="visible")
        page.locator(".isslop-feed-loader").wait_for(state="visible")
    finally:
        _clear_isslop_data()
