"""Detect Hudl permission / 403 Forbidden pages and raise a clear error."""
from playwright.async_api import Page


class HudlForbiddenError(PermissionError):
    """Raised when Hudl returns the classic 403 permission page."""

    def __init__(
        self,
        message: str = "You need permission to access this page.",
        *,
        detail: str | None = None,
        url: str | None = None,
        team_id: str | None = None,
        area: str = "exchange",
    ):
        super().__init__(message)
        self.title = "You need permission to access this page."
        self.detail = detail or (
            "Either you're not logged in or your current email isn't linked to this team. "
            "Try logging in or contact your coach to double-check permissions. "
            "If you continue to have trouble, hit up Hudl Support."
        )
        self.code = "Error 403 - Forbidden"
        self.url = url
        self.team_id = team_id
        self.area = area

    def as_dict(self) -> dict:
        return {
            "status": "forbidden",
            "error": "forbidden",
            "code": 403,
            "title": self.title,
            "message": self.title,
            "detail": self.detail,
            "error_code": self.code,
            "url": self.url,
            "team_id": self.team_id,
            "area": self.area,
        }


async def detect_hudl_forbidden(page: Page) -> dict | None:
    """
    Return forbidden payload if the current page is Hudl's 403 screen
    ("You need permission to access this page.").
    """
    try:
        info = await page.evaluate(
            """() => {
              const title = (document.title || '').toLowerCase();
              const body = (document.body?.innerText || '');
              const h1 = (document.querySelector('h1')?.innerText || '').trim();
              const isForbidden =
                title.includes('forbidden') ||
                /you need permission to access this page/i.test(body) ||
                /error\\s*403/i.test(body) ||
                /you need permission to access this page/i.test(h1);

              if (!isForbidden) return null;

              return {
                title: h1 || 'You need permission to access this page.',
                detail: body.includes("not logged in")
                  ? "Either you're not logged in or your current email isn't linked to this team. Try logging in or contact your coach to double-check permissions. If you continue to have trouble, hit up Hudl Support."
                  : (body.slice(0, 400) || null),
                error_code: 'Error 403 - Forbidden',
                url: location.href,
              };
            }"""
        )
        return info
    except Exception:
        return None


async def raise_if_hudl_forbidden(
    page: Page,
    *,
    team_id: str | None = None,
    area: str = "exchange",
) -> None:
    """Raise HudlForbiddenError when the headed browser is on Hudl's 403 page."""
    info = await detect_hudl_forbidden(page)
    if not info:
        return
    raise HudlForbiddenError(
        info.get("title") or "You need permission to access this page.",
        detail=info.get("detail"),
        url=info.get("url") or page.url,
        team_id=team_id,
        area=area,
    )
