# retoor <retoor@molodetz.nl>

from __future__ import annotations

from .base import (
    HIGH,
    MEDIUM,
    LOW,
    Check,
    PageContext,
    SiteContext,
    ok_check,
    page_check,
)

CATEGORY = "mobile_accessibility"


@page_check
def responsive(page: PageContext, site: SiteContext) -> Check:
    mobile = page.mobile or {}
    overflow = bool(mobile.get("hasHorizontalOverflow"))
    return ok_check(
        "mobile.no_overflow",
        CATEGORY,
        "No horizontal overflow (mobile)",
        not overflow,
        severity=MEDIUM,
        value="ok" if not overflow else f"scrollWidth {mobile.get('scrollWidth', '?')}px",
        recommendation="Eliminate horizontal scrolling at a 390px mobile viewport.",
        warn=True,
        url=page.url,
    )


@page_check
def tap_targets(page: PageContext, site: SiteContext) -> Check | None:
    mobile = page.mobile or {}
    small = int(mobile.get("smallTapTargets", 0) or 0)
    if "smallTapTargets" not in mobile:
        return None
    return ok_check(
        "mobile.tap_targets",
        CATEGORY,
        "Tap target sizing",
        small == 0,
        severity=LOW,
        value="ok" if small == 0 else f"{small} small target(s)",
        recommendation="Make interactive targets at least 24x24 px (48 px recommended).",
        warn=True,
        url=page.url,
    )


@page_check
def image_alt(page: PageContext, site: SiteContext) -> Check | None:
    images = page.dom.get("images", []) or []
    if not images:
        return None
    missing = [img for img in images if not (img.get("alt", "") or "").strip()]
    return ok_check(
        "a11y.image_alt",
        CATEGORY,
        "Image alt coverage",
        not missing,
        severity=MEDIUM,
        value="complete" if not missing else f"{len(missing)}/{len(images)} missing alt",
        recommendation="Add descriptive alt text to every meaningful image.",
        warn=True,
        url=page.url,
    )


@page_check
def form_labels(page: PageContext, site: SiteContext) -> Check | None:
    missing = int(page.dom.get("formsMissingLabels", 0) or 0)
    if not page.dom.get("formFieldCount"):
        return None
    return ok_check(
        "a11y.form_labels",
        CATEGORY,
        "Form fields labelled",
        missing == 0,
        severity=LOW,
        value="ok" if missing == 0 else f"{missing} unlabelled field(s)",
        recommendation="Associate a <label> or aria-label with every form control.",
        warn=True,
        url=page.url,
    )


@page_check
def document_title(page: PageContext, site: SiteContext) -> Check:
    return ok_check(
        "a11y.document_title",
        CATEGORY,
        "Accessible document title",
        bool((page.dom.get("title", "") or "").strip()),
        severity=LOW,
        value="present" if (page.dom.get("title", "") or "").strip() else "missing",
        recommendation="Every page needs a non-empty <title> for assistive tech.",
        warn=True,
        url=page.url,
    )
