"""Nettoyage du HTML saisi dans l'éditeur (équivalent de sanitizeHtml côté Laravel)."""

from urllib.parse import urlparse

import nh3
from django.conf import settings
from django.utils.html import strip_tags

ALLOWED_TAGS = {
    "p", "br", "strong", "b", "em", "i", "u", "s", "span", "div", "a", "img",
    "ul", "ol", "li", "h1", "h2", "h3", "h4", "h5", "h6", "blockquote", "hr",
    "table", "thead", "tbody", "tfoot", "tr", "th", "td", "caption",
    "figure", "figcaption", "code", "pre", "iframe", "sub", "sup",
}
_COMMON = {"class", "style", "title"}
ALLOWED_ATTRIBUTES = {
    "*": _COMMON,
    "a": _COMMON | {"href", "target"},
    "img": _COMMON | {"src", "alt", "width", "height", "loading", "srcset", "sizes"},
    "iframe": _COMMON | {"src", "width", "height", "allow", "allowfullscreen", "frameborder"},
    "td": _COMMON | {"colspan", "rowspan"},
    "th": _COMMON | {"colspan", "rowspan", "scope"},
}


def _allowed_iframe(src: str) -> bool:
    host = (urlparse(src).hostname or "").lower()
    return host in settings.LABELINFO["ALLOWED_IFRAME_HOSTS"]


def _attribute_filter(tag, attr, value):
    if tag == "iframe" and attr == "src" and not _allowed_iframe(value):
        return None
    return value


def sanitize_html(html: str) -> str:
    if not html:
        return ""
    return nh3.clean(
        html,
        tags=ALLOWED_TAGS,
        attributes=ALLOWED_ATTRIBUTES,
        attribute_filter=_attribute_filter,
        url_schemes={"http", "https", "mailto", "tel"},
        link_rel="noopener noreferrer",
        set_tag_attribute_values={
            "iframe": {"loading": "lazy", "referrerpolicy": "strict-origin-when-cross-origin"},
            "img": {"loading": "lazy"},
        },
        strip_comments=True,
    )


def plain_text(html: str) -> str:
    return " ".join(strip_tags(html or "").split())
