from playwright.async_api import Page

from app.automation.helpers import human_delay, find_and_click_next, safe_click
from app.automation.selectors import NOTES_TEXTAREA
from app.automation.tasks.popup import _dismiss_activation_guide


async def add_notes(page: Page, message: str | None) -> dict:
    """
    POST /exchange/notes
    Fill the coach message (required for Request Video on Hudl), then click Next.

    Do NOT call close_hudl_popups() here — that closes the exchange wizard /
    Confirm modal (Hudl Modal) and breaks the Request Video flow.
    """
    # Only clear the activation-guide overlay if it is blocking clicks.
    await _dismiss_activation_guide(page)
    await human_delay(0.6, 1.0)

    text = (message or "").strip()
    textarea = page.locator(NOTES_TEXTAREA).first
    if await textarea.count() == 0:
        # Broader fallbacks used across classic + request message steps
        textarea = page.locator(
            "section.ex-message textarea, "
            "textarea[placeholder*='send' i], "
            "textarea[placeholder*='message' i], "
            "textarea[placeholder*='game' i], "
            ".ex-message textarea, "
            "textarea"
        ).first

    if text:
        if await textarea.count() == 0:
            raise RuntimeError(
                "Could not find Hudl message textarea on the Include a Message step."
            )
        await textarea.wait_for(state="visible", timeout=10000)
        await textarea.click(timeout=5000)
        await textarea.fill("")
        await textarea.fill(text)
        await human_delay(0.4, 0.8)
        # Trigger input events so Hudl enables Next when message is required.
        await page.evaluate(
            """(el) => {
              el.dispatchEvent(new Event('input', { bubbles: true }));
              el.dispatchEvent(new Event('change', { bubbles: true }));
            }""",
            await textarea.element_handle(),
        )
        await human_delay(0.3, 0.6)
    else:
        # Empty message — Hudl disables Next on Request Video; surface that clearly.
        try:
            next_btn = page.locator("#messageNextButton, footer button:has-text('Next')").first
            if await next_btn.count() > 0 and await next_btn.is_disabled():
                raise RuntimeError(
                    "Please include a message when requesting video."
                )
        except RuntimeError:
            raise
        except Exception:
            pass

    # Prefer the notes-step Next id Hudl uses for Request Video.
    found_next_button = None
    msg_next = page.locator("#messageNextButton").first
    try:
        if await msg_next.count() > 0 and await msg_next.is_visible():
            if await msg_next.is_disabled():
                raise RuntimeError(
                    "Please include a message when requesting video."
                )
            await safe_click(msg_next, timeout_ms=8000, force_after_ms=2500)
            found_next_button = "#messageNextButton"
        else:
            found_next_button = await find_and_click_next(page)
    except RuntimeError:
        raise
    except Exception as exc:
        # One more attempt after dismissing overlay only
        await _dismiss_activation_guide(page)
        found_next_button = await find_and_click_next(page)
        if not found_next_button:
            raise RuntimeError(f"Notes Next failed: {exc}") from exc

    await human_delay(1.2, 2.0)

    # Verify we left the message step (confirm or still notes with error).
    still_on_notes = False
    try:
        still_on_notes = await page.locator(
            "text=Include a Message, text=Include a message to the other coach, #messageNextButton"
        ).count() > 0 and await page.locator(
            "#sendExchange, button:has-text('Send'), text=Confirm Your Exchange"
        ).count() == 0
    except Exception:
        pass

    if still_on_notes and not text:
        raise RuntimeError("Please include a message when requesting video.")

    return {
        "status": "ok",
        "action": "notes",
        "message_sent": text or None,
        "url": page.url,
        "next_button_used": found_next_button,
        "message": "Notes step completed.",
    }
