"""Allow-list HTML sanitizer for agent-written offer descriptions (Markdown rendered to HTML).

python-markdown passes raw HTML and `javascript:` links straight through, and the result is shown to every visitor of the public
offer page and to master in the CRM. Everything that leaves `markdown.markdown()` for a template goes through
`sanitize_description_html()` first (Jinja filter `sanitize_html`).

Engine: nh3 (Rust `ammonia`), an allow-list sanitizer. Formatting is preserved: paragraphs, headings, lists, links, images, tables, code.
`iframe` is kept ONLY for YouTube / YouTube-nocookie / Vimeo player URLs (checked per `src`, and always sandboxed); any other iframe
loses its `src` and is removed.

If nh3 cannot be imported (e.g. a host where the requirement is not installed yet) the function FAILS CLOSED: the whole text is
HTML-escaped (readable, never active) and an error is logged once. It never returns unsanitized markup.
"""
import html
import logging
import re

try:                                    # pragma: no cover - exercised through the fallback test
    import nh3
except ImportError:                     # pragma: no cover
    nh3 = None

logger = logging.getLogger(__name__)

ALLOWED_TAGS = frozenset({
    'p', 'br', 'hr', 'div', 'span', 'blockquote', 'pre', 'code',
    'strong', 'b', 'em', 'i', 'u', 's', 'del', 'ins', 'sup', 'sub', 'small', 'mark',
    'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'ul', 'ol', 'li', 'dl', 'dt', 'dd',
    'a', 'img', 'figure', 'figcaption',
    'table', 'thead', 'tbody', 'tfoot', 'tr', 'th', 'td', 'caption', 'colgroup', 'col',
    'iframe',
})
ALLOWED_ATTRIBUTES = {
    'a': {'href', 'title'},
    'img': {'src', 'alt', 'title', 'width', 'height', 'loading'},
    'th': {'colspan', 'rowspan', 'align'},
    'td': {'colspan', 'rowspan', 'align'},
    'col': {'span'},
    'iframe': {'src', 'width', 'height', 'title', 'allowfullscreen', 'frameborder', 'loading'},
    'ol': {'start'},
}
ALLOWED_URL_SCHEMES = frozenset({'http', 'https', 'mailto', 'tel'})
CLEAN_CONTENT_TAGS = frozenset({'script', 'style', 'noscript', 'template', 'object', 'embed', 'applet', 'frameset', 'frame'})

# Verified embed URLs only (no other hosts, no schemes other than https).
EMBED_SRC = re.compile(
    r'^https://(?:www\.youtube(?:-nocookie)?\.com/embed/[A-Za-z0-9_-]{6,20}|player\.vimeo\.com/video/\d{3,12})(?:\?[A-Za-z0-9_=&%.\-]{0,200})?$')
IFRAME_SANDBOX = 'allow-scripts allow-same-origin allow-presentation allow-popups'
_EMPTY_IFRAME = re.compile(r'<iframe(?![^>]*\ssrc=)[^>]*>\s*</iframe>', re.IGNORECASE)
_VALID_IFRAME = re.compile(r'<iframe\b(?=[^>]*\ssrc=)[^>]*>.*?</iframe>', re.IGNORECASE | re.DOTALL)

_warned = False


def _attribute_filter(tag, attribute, value):
    """Called by nh3 for every kept attribute: only verified embed URLs may stay on an iframe."""
    if tag == 'iframe' and attribute == 'src':
        return value if EMBED_SRC.match(value or '') else None
    return value


def sanitize_description_html(value, *, defer_video=False, video_language="pl"):
    """Sanitized HTML (as markupsafe.Markup, so Jinja does not escape it again). Empty/None -> empty Markup."""
    from markupsafe import Markup
    text = '' if value is None else str(value)
    if not text.strip():
        return Markup('')
    if nh3 is None:
        global _warned
        if not _warned:
            _warned = True
            logger.error('nh3 is not installed: offer descriptions are HTML-escaped (fail closed). Install the requirement from requirements.txt.')
        return Markup(html.escape(text))
    cleaned = nh3.clean(
        text,
        tags=set(ALLOWED_TAGS),
        attributes={tag: set(names) for tag, names in ALLOWED_ATTRIBUTES.items()},
        url_schemes=set(ALLOWED_URL_SCHEMES),
        link_rel='noopener noreferrer nofollow',
        strip_comments=True,
        clean_content_tags=set(CLEAN_CONTENT_TAGS),
        attribute_filter=_attribute_filter,
        set_tag_attribute_values={'iframe': {'sandbox': IFRAME_SANDBOX, 'referrerpolicy': 'strict-origin-when-cross-origin'}},
    )
    cleaned = _EMPTY_IFRAME.sub('', cleaned)
    if defer_video:
        if video_language == "en":
            notice = "Loading the video connects your browser to its external provider (YouTube or Vimeo)."
            action = "Load video"
        else:
            notice = "Wczytanie filmu połączy przeglądarkę z zewnętrznym dostawcą (YouTube lub Vimeo)."
            action = "Wczytaj film"
        # The sanitized iframe remains inert inside template.content until requested.
        cleaned = _VALID_IFRAME.sub(
            lambda match: '<div data-external-video class="rounded-lg border p-4">'
            f'<p>{notice}</p><button type="button" class="underline">{action}</button>'
            f'<template>{match[0]}</template></div>',
            cleaned,
        )
    return Markup(cleaned)
