import asyncio
import random


async def human_delay(min_s: float = 0.8, max_s: float = 2.2) -> None:
    await asyncio.sleep(random.uniform(min_s, max_s))


async def safe_click(locator, *, timeout_ms: int = 5000, force_after_ms: int = 2500) -> None:
    """
    Click without burning the full Playwright default timeout on overlays.
    Tries a short normal click → force click → JS click.

    Only dismisses the activation-guide calendar — never full close_hudl_popups(),
    which would close Hudl's Confirm / exchange wizard modal.
    """
    from app.automation.tasks.popup import _dismiss_activation_guide

    page = locator.page
    try:
        await _dismiss_activation_guide(page)
    except Exception:
        pass

    try:
        await locator.click(timeout=min(timeout_ms, force_after_ms))
        return
    except Exception:
        pass

    try:
        await _dismiss_activation_guide(page)
        await locator.click(timeout=timeout_ms, force=True)
        return
    except Exception:
        pass

    handle = await locator.element_handle(timeout=timeout_ms)
    if handle is None:
        raise RuntimeError("safe_click: element not found")
    await page.evaluate("(el) => { el.scrollIntoView({block:'center'}); el.click(); }", handle)


async def find_and_click_next(page) -> str:
    """
    Dynamically finds an ENABLED Next button, clicks it, and returns the selector used.
    Hudl changes the ID of the next button on different steps.
    """
    selectors = [
        "xpath=//footer//button[contains(translate(., 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'next')]",
        "xpath=//button[contains(translate(., 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'next')]",
        "xpath=//button[@id='eventNextButton']",
        "xpath=//button[@id='gameStatsNextButton']",
        "xpath=//button[@id='breakdownNextButton']",
        "xpath=//button[@id='optionsNextButton']",
        "xpath=//button[@id='messageNextButton']",
        "xpath=//footer//button[contains(@class, 'primary')]"
    ]

    for sel in selectors:
        loc = page.locator(sel).first
        if await loc.count() == 0 or not await loc.is_visible():
            continue
        try:
            disabled = await loc.is_disabled()
        except Exception:
            disabled = False
        if disabled:
            print(f"Next button found but disabled: {sel}")
            continue
        print(f"Found Next button dynamically with: {sel}")
        await loc.click(timeout=8000)
        return sel

    raise Exception("Could not find any enabled Next button dynamically on this page!")
