from django.core.exceptions import ValidationError
from wagtail.embeds.blocks import EmbedBlock
from wagtail.embeds import embeds as wagtail_embeds
from wagtail import blocks
from urllib.parse import urlparse
from django.conf import settings


class ValidatingEmbedBlock(EmbedBlock):
    """
    Embed block that validates the URL at clean-time by resolving
    via Wagtail's embed system. Raises ValidationError if not embeddable.
    """

    def clean(self, value):
        value = super().clean(value)
        if value:
            # Inherit base validation (already run via super().clean), and add
            # optional network validation for selected providers.
            url_str = value if isinstance(value, str) else getattr(value, "url", None)
            if not url_str:
                return value
            host = (urlparse(url_str).hostname or "").lower()

            strict_hosts = getattr(
                settings,
                "EMBED_STRICT_HOSTS",
                ("instagram.com", "facebook.com"),
            )
            validate_all = getattr(settings, "EMBED_STRICT_VALIDATE_ALL", False)

            def _matches(h: str) -> bool:
                return host == h or host.endswith("." + h)

            must_validate = bool(validate_all or any(_matches(h) for h in strict_hosts))
            if must_validate:
                try:
                    # Attempt to resolve and cache embed; will raise on failure
                    wagtail_embeds.get_embed(url_str)
                except Exception:
                    raise ValidationError(
                        "嵌入連結無法驗證（需公開且有權杖）。請確認 URL 與設定。"
                    )
        return value


class H2HeadingBlock(blocks.CharBlock):
    class Meta:
        template = "home/blocks/h2_heading.html"
        icon = "title"
        label = "Heading"


class HorizontalRuleBlock(blocks.StaticBlock):
    class Meta:
        template = "home/blocks/horizontal_rule.html"
        icon = "horizontalrule"
        label = "Separator"
