"""Adapter for luticlip.com, a WordPress tube-style site.

Listing, tag and category pages do not expose the media file; each card links
to a detail page that holds a single ``<video><source ...></video>`` element.
The generic adapter deliberately ignores arbitrary anchors, so this adapter
declares the site's own card selector and only uses it on pages without a
``<video>`` element (i.e. real listing pages, not detail pages with "related"
blocks).
"""

from __future__ import annotations

from urllib.parse import urlsplit

from bs4 import BeautifulSoup

from app.adapters.base import ParsedPage
from app.adapters.generic_html import GenericHTMLAdapter


class LutiClipAdapter(GenericHTMLAdapter):
    name = "luticlip"
    title_selectors = ("h1.entry-title",)
    caption_selectors = ("div.video-description .desc", "div.video-description")
    video_page_selectors = (
        "article.loop-video a[href]",
        "article.thumb-block a[href]",
    )

    def supports(self, url: str) -> bool:
        host = (urlsplit(url).hostname or "").lower()
        return host == "luticlip.com" or host.endswith(".luticlip.com")

    def parse(self, html: str, url: str) -> ParsedPage:
        soup = BeautifulSoup(html, "html.parser")
        caption = self.caption_parser.parse(
            soup,
            adapter=self,
            fallback_title=self._fallback_title(url),
        )
        selectors = () if soup.find("video") else self.video_page_selectors
        videos, video_pages = self.media_adapter.extract(
            soup,
            url,
            caption,
            adapter=self,
            video_page_selectors=selectors,
        )
        next_page = self.pagination.detect(soup, url, adapter=self)
        return ParsedPage(
            url=url,
            title=caption.title,
            caption=caption.caption,
            videos=videos,
            video_pages=video_pages,
            next_page_url=next_page.url,
            next_page_strategy=next_page.strategy,
            caption_source=caption.source,
            adapter_name=self.name,
        )
