# -*- coding: utf-8 -*-
"""
paradisehill.py — BieCuiLe(别催了) / TVBox Python 源   v2.1.0
目标站: https://en.paradisehill.cc

v2.1.0 (加载失败修复)
--------------------
* init() 不再联网: 门改为惰性, 首次请求时单次 5s 短尝试, 失败也放行不阻塞。
* 阶段 0 只取 /categories/ 第 1 页; 2-8 页挪到阶段 1, 字母/sitemap 后置。
* 首页预算 6s, 索引请求 5s, 超 7s 直接跳过片商抓取。
* init 整体 try/except, 配置异常不影响加载。

哲学
----
1) 证伪主义: 索引页是主证据, 探针裁决。
2) 奥卡姆剃刀: 首屏只做一页。
3) 控制论: 翻页以"无新增"为终止信号。
4) 斯多葛: 到点即返, 门失败也放行。
5) 现象学: 名称取页面原文。
"""

from __future__ import annotations

import functools
import html as html_lib
import json
import random
import re
import sys
import time
from dataclasses import dataclass, field
from typing import Any, Dict, Iterable, List, Optional, Tuple
from urllib.parse import quote, urljoin, urlparse

# --- embedded requests-compatible shim (urllib based) for Yingxia adaptation ---
# Inserted by py578 adaptation: used only when real `requests` is unavailable.
import json as _json
import ssl as _ssl
import urllib.error as _uerr
import urllib.parse as _uparse
import urllib.request as _ureq
import http.cookiejar as _cookiejar


class _ReqExc(Exception):
    pass


class _Timeout(_ReqExc):
    pass


class _ConnectionError(_ReqExc):
    pass


class _HTTPError(_ReqExc):
    pass


class _CaseDict(dict):
    def get(self, k, d=None):
        for kk, vv in self.items():
            if kk.lower() == str(k).lower():
                return vv
        return d

    def __getitem__(self, k):
        v = self.get(k)
        if v is None:
            raise KeyError(k)
        return v


class _Response:
    def __init__(self, status_code=0, headers=None, content=b"", url="", cookies=None):
        self.status_code = status_code
        self.headers = _CaseDict(headers or {})
        self.content = content or b""
        self.url = url
        self.cookies = cookies or {}
        self.encoding = None
        self._text = None

    @property
    def text(self):
        if self._text is None:
            enc = self.encoding
            if not enc:
                ct = self.headers.get("Content-Type", "")
                m = _uparse.parse_qs(ct.replace(";", "&")) if False else None
                enc = "utf-8"
                if "charset=" in ct:
                    enc = ct.split("charset=")[-1].split(";")[0].strip() or "utf-8"
            try:
                self._text = self.content.decode(enc, "ignore")
            except Exception:
                self._text = self.content.decode("utf-8", "ignore")
        return self._text

    def json(self):
        return _json.loads(self.text)

    def raise_for_status(self):
        if self.status_code >= 400:
            raise _HTTPError("HTTP %s" % self.status_code)

    def iter_content(self, chunk_size=65536):
        for i in range(0, len(self.content), chunk_size):
            yield self.content[i:i + chunk_size]

    def close(self):
        pass


class _Session:
    def __init__(self):
        self.headers = {"User-Agent": "Mozilla/5.0 (Linux; Android 13) AppleWebKit/537.36 Chrome/120 Mobile Safari/537.36"}
        self.cookies = {}
        self._jar = _cookiejar.CookieJar()
        self._ctx = _ssl._create_unverified_context()
        self._opener = _ureq.build_opener(
            _ureq.HTTPCookieProcessor(self._jar),
            _ureq.HTTPSHandler(context=self._ctx))

    def request(self, method, url, headers=None, timeout=15, data=None,
                json=None, params=None, cookies=None, verify=False,
                allow_redirects=True, stream=False, **kw):
        if params:
            qs = _uparse.urlencode(params, doseq=True)
            url = url + ("&" if "?" in url else "?") + qs
        hd = dict(self.headers)
        if headers:
            hd.update(headers)
        body = None
        if json is not None:
            body = _json.dumps(json, ensure_ascii=False).encode("utf-8")
            hd.setdefault("Content-Type", "application/json")
        elif isinstance(data, dict):
            body = _uparse.urlencode(data, doseq=True).encode("utf-8")
            hd.setdefault("Content-Type", "application/x-www-form-urlencoded")
        elif isinstance(data, str):
            body = data.encode("utf-8")
        elif isinstance(data, (bytes, bytearray)):
            body = bytes(data)
        if cookies:
            hd["Cookie"] = "; ".join("%s=%s" % kv for kv in cookies.items())
        elif self.cookies:
            hd.setdefault("Cookie", "; ".join("%s=%s" % kv for kv in self.cookies.items()))
        req = _ureq.Request(url, data=body, headers=hd, method=method.upper())
        try:
            to = timeout
            if isinstance(to, (tuple, list)):
                to = max(to)
            if to and float(to) > 120:
                to = float(to) / 1000.0
            with self._opener.open(req, timeout=to or 15) as resp:
                content = resp.read()
                hdrs = dict(resp.headers.items())
                final = resp.geturl()
                status = resp.status
        except _uerr.HTTPError as e:
            try:
                content = e.read()
            except Exception:
                content = b""
            hdrs = dict(e.headers.items()) if e.headers else {}
            final = e.geturl() if hasattr(e, "geturl") else url
            status = e.code
        except Exception as e:
            raise _ConnectionError(str(e))
        for c in self._jar:
            self.cookies[c.name] = c.value
        return _Response(status, hdrs, content, final, dict(self.cookies))

    def get(self, url, **kw):
        return self.request("GET", url, **kw)

    def post(self, url, data=None, **kw):
        return self.request("POST", url, data=data, **kw)

    def head(self, url, **kw):
        return self.request("HEAD", url, **kw)

    def close(self):
        pass


class _Exceptions:
    RequestException = _ReqExc
    Timeout = _Timeout
    ConnectTimeout = _Timeout
    ReadTimeout = _Timeout
    ConnectionError = _ConnectionError
    HTTPError = _HTTPError
    SSLError = _ConnectionError


class _RequestsShim:
    Session = _Session
    exceptions = _Exceptions
    Response = _Response

    @staticmethod
    def request(method, url, **kw):
        return _Session().request(method, url, **kw)

    @staticmethod
    def get(url, **kw):
        return _Session().request("GET", url, **kw)

    @staticmethod
    def post(url, data=None, **kw):
        return _Session().request("POST", url, data=data, **kw)

    @staticmethod
    def head(url, **kw):
        return _Session().request("HEAD", url, **kw)


requests = _RequestsShim
# --- end embedded requests shim ---

# --- py578 shim compat additions (RequestException/utils/cookies/mount) ---
try:
    _RequestsShim.RequestException = _ReqExc
    _RequestsShim.Timeout = _Timeout
    _RequestsShim.ConnectionError = _ConnectionError
    _RequestsShim.HTTPError = _HTTPError
    _Response.apparent_encoding = property(lambda self: "utf-8")

    class _ReqUtils(object):
        @staticmethod
        def quote(s, safe="/"):
            return _uparse.quote(str(s), safe=safe)

        @staticmethod
        def unquote(s):
            return _uparse.unquote(str(s))

    _RequestsShim.utils = _ReqUtils

    class _CookieDict(dict):
        def set(self, name, value, domain=None, path=None, **kw):
            self[name] = value

        def get_dict(self):
            return dict(self)

    _orig_session_init = _Session.__init__

    def _session_init(self):
        _orig_session_init(self)
        self.cookies = _CookieDict(self.cookies)

    _Session.__init__ = _session_init
    if not hasattr(_Session, "mount"):
        _Session.mount = lambda self, prefix, adapter=None: None
except Exception:
    pass
# --- end py578 shim compat additions ---
try:
    import requests
except Exception:
    requests = _RequestsShim

__version__ = "2.1.0"

DEFAULT_SITE = "https://en.paradisehill.cc"
MIRRORS = ("https://en.paradisehill.cc", "https://ru.paradisehill.cc")
MEDIA_HOST = "https://v1.paradisehill.cc"
SITEMAPS = ("/sitemap.xml", "/sitemap_index.xml", "/sitemap/sitemap.xml", "/sitemaps.xml")

SEEDS = (
    "asian", "bbw", "anal", "animation", "bdsm", "big-ass", "big-tits", "classic",
    "ebony", "fetish", "french-porn", "feature-films", "all-sex", "anal-sex",
    "amateur", "blonde", "blowjob", "brunette", "creampie", "czech", "gangbang",
    "german", "group-sex", "hairy", "hentai", "hungarian", "interracial", "italian",
    "japanese", "latina", "lesbian", "mature", "milf", "oral", "pov", "russian",
    "solo", "squirting", "stockings", "tattoo", "teen", "threesome", "vintage",
)

UA = ("Mozilla/5.0 (Linux; Android 12; Pixel 6) AppleWebKit/537.36 "
      "(KHTML, like Gecko) Chrome/124.0.0.0 Mobile Safari/537.36")

try:
    from base.spider import Spider as _BaseSpider  # type: ignore
except Exception:
    class _BaseSpider(object):
        def init(self, extend: str = "") -> None:
            pass


@dataclass(order=True)
class Hypothesis:
    score: float
    name: str = field(compare=False)
    url: str = field(compare=False)

    def __str__(self) -> str:
        return f"<{self.name} {self.score:.1f}>"


def resilient(tries: int = 3, base: float = 0.4, cap: float = 3.0, factor: float = 2.0):
    def deco(fn):
        @functools.wraps(fn)
        def wrapper(self, *a, **kw):
            last = None
            for i in range(tries):
                try:
                    return fn(self, *a, **kw)
                except Exception as exc:  # noqa: BLE001
                    last = exc
                    if i == tries - 1:
                        break
                    time.sleep(min(cap, base * (factor ** i)) * (0.7 + random.random() * 0.6))
            self.log(f"[warn] {getattr(fn, '__name__', fn)}: {last}")
            return None
        return wrapper
    return deco


RE_ROUTE = re.compile(r'<a\b[^>]*?href="([^"]*?/([0-9a-f]{6,})/?)"[^>]*>', re.I)
RE_IMG_TAG = re.compile(r'<img\b[^>]*?>', re.I)
RE_IFRAME = re.compile(r'<(?:iframe|embed)\b[^>]*?\bsrc="([^"]+)"', re.I)
RE_LAZY = re.compile(r'\b(?:data-src|data-original|data-lazy-src|data-echo|src)="([^"]+)"', re.I)
RE_MEDIA = re.compile(r'(?:https?:)?//[^\s"\'<>\\)\]]+?\.(?:m3u8|mp4)(?:\?[^\s"\'<>\\)\]]*)?', re.I)
RE_MEDIA_REL = re.compile(r'["\'(\s](/[^\s"\'<>)\]]+?\.(?:m3u8|mp4))(?:\?[^\s"\'<>)\]]*)?', re.I)
RE_SOURCE = re.compile(r'<(?:source|video)\b[^>]*?\bsrc="([^"]+)"', re.I)
RE_JSONFILE = re.compile(r'["\'](?:file|src|url|source|hls|mp4)["\']\s*:\s*["\']([^"\']+\.(?:m3u8|mp4)[^"\']*)["\']', re.I)
RE_PART_URL = re.compile(
    r'((?:https?:)?//[^\s"\'<>]+?/video/([A-Za-z0-9]{5,24})_(\d{1,2})_part(\d{1,3})\.mp4)', re.I)
RE_PART_REL = re.compile(r'/video/([A-Za-z0-9]{5,24})_(\d{1,2})_part(\d{1,3})\.mp4', re.I)
RE_SCRIPT = re.compile(r'<script\b[^>]*?\bsrc="([^"]+)"', re.I)
RE_ENDPOINT = re.compile(r'["\'](/[a-z0-9_\-/]{3,48}?(?:api|video|player|json|ajax)[a-z0-9_\-/]*)["\']', re.I)
RE_TAG = re.compile(r'<[^>]+>')
RE_WS = re.compile(r'\s+')
RE_DIGITS = re.compile(r'\d+')
RE_ALNUM = re.compile(r'[A-Za-z0-9]{8,24}')
RE_SLUG_OK = re.compile(r'[a-z0-9][a-z0-9\-]{1,39}')
RE_ALT = re.compile(r'\balt="([^"]*)"', re.I)
RE_TITLE_ATTR = re.compile(r'\btitle="([^"]*)"', re.I)
RE_META = re.compile(
    r'<meta\b[^>]*?(?:property|name)="(og:[a-z:_]+|description|twitter:[a-z:_]+)"'
    r'[^>]*?content="([^"]*)"', re.I)
RE_JSONLD = re.compile(r'<script[^>]+application/ld\+json[^>]*>(.*?)</script>', re.S | re.I)
RE_NEAR = re.compile(r'.{0,240}(?:part\d|_part|\.mp4|video[_-]?src|player).{0,240}', re.I | re.S)

RE_A_PAIR = re.compile(
    r'<a\b[^>]*?href\s*=\s*(?:"([^"]*)"|\'([^\']*)\'|([^\s>]+))[^>]*>(.*?)</a>', re.S | re.I)
RE_OPT_PAIR = re.compile(
    r'<option\b[^>]*?value\s*=\s*(?:"([^"]*)"|\'([^\']*)\'|([^\s>]+))[^>]*>(.*?)</option>', re.S | re.I)
RE_HREF = re.compile(r"""href\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))""", re.I)
RE_TAXO_PATH = re.compile(r'/(category|categories|tag|tags)/([^/"\'?#\s]{1,40})', re.I)
RE_LETTER_LINK = re.compile(r'href\s*=\s*["\']?([^"\'\s>]*?[?&]letter=([A-Za-z0-9]))', re.I)
RE_SITEMAP_LOC = re.compile(r'<loc>\s*([^<\s]+)\s*</loc>', re.I)
RE_CATS_LINE = re.compile(r'Categor(?:y|ies):\s*([^<\n]{2,200})', re.I)

TOKEN_RULES: Tuple[Tuple[re.Pattern, float], ...] = (
    (re.compile(r'\bdata-(?:video|file|stream|src|movie)[_-]?(?:id|src)?="([A-Za-z0-9]{8,24})"', re.I), 5.0),
    (re.compile(r'(?:video[_-]?id|videoId|videoid|file[_-]?id|fileId|stream[_-]?id)'
                r'["\']?\s*[:=]\s*["\']([A-Za-z0-9]{8,24})["\']'), 4.5),
    (re.compile(r'/(?:video|embed|player|v|e)/([A-Za-z0-9]{8,24})[/_."]'), 3.5),
    (re.compile(r'\b([A-Za-z0-9]{10,14})_1_part1\.mp4'), 3.0),
    (re.compile(r'["\'](?:token|hash|key|code|file)["\']\s*:\s*["\']([A-Za-z0-9]{8,24})["\']'), 2.5),
)

PART_TPL: Tuple[str, ...] = (
    "{m}/video/{t}_{q}_part{n}.mp4",
    "{m}/video/{t}_{q}_part{n2}.mp4",
    "{m}/video/{t}_part{n}.mp4",
    "{m}/video/{t}/{n}.mp4",
    "{m}/video/{t}_{n}.mp4",
    "{m}/video/{t}_{q}_{n}.mp4",
)

HLS_TPL: Tuple[str, ...] = (
    "{m}/video/{t}/index.m3u8",
    "{m}/video/{t}_{q}/index.m3u8",
    "{m}/video/{t}/master.m3u8",
    "{m}/hls/{t}/index.m3u8",
    "{m}/video/{t}_1/index.m3u8",
)

PLAYER_TPL: Tuple[str, ...] = (
    "{s}/player/{i}/",
    "{s}/player/?hash={i}",
    "{s}/player/?id={i}",
    "{s}/{i}/?player=1",
    "{s}/{i}/?ajax=1",
    "{s}/embed/{i}/",
    "{m}/embed/{i}/",
    "{m}/video/{i}/",
    "{s}/api/video/{i}",
    "{s}/api/video/{i}/",
)

JUNK_SLUG = {"all", "new", "popular", "page", "help", "search", "login", "register",
             "news", "studios", "studio", "porn", "category", "categories", "tag", "tags",
             "terms", "privacy", "advertisers", "about"}
SORTS: Tuple[Tuple[str, str], ...] = (
    ("created_at", "最新收录"), ("release", "发行日期"),
    ("title", "标题"), ("by_films", "片数"),
)

HLS_LABEL = "HLS 整片(推荐)"
MAX_CATS = 800
STAGES = 4


def clean(text: Optional[str]) -> str:
    if not text:
        return ""
    return RE_WS.sub(" ", RE_TAG.sub(" ", html_lib.unescape(str(text)))).strip()


def slugify(name: str) -> str:
    s = re.sub(r'[^a-z0-9]+', '-', (name or "").lower()).strip('-')
    return s if RE_SLUG_OK.fullmatch(s) else ""


def part_labels(total: int, quality: int = 1) -> List[str]:
    width = max(2, len(str(max(total, 1))))
    prefix = f"q{quality}·" if quality and quality > 1 else ""
    return [f"{prefix}P{str(i).zfill(width)}/{total}" for i in range(1, total + 1)]


class Spider(_BaseSpider):
    """ParadiseHill 源。"""

    def __init__(self) -> None:
        self.site = DEFAULT_SITE
        self.timeout = 10
        self.fast_timeout = 5
        self.probe_timeout = 4
        self.max_items = 42
        self.max_parts = 40
        self.max_tokens = 8
        self.budget = 6.0
        self.cat_ttl = 900
        self.logs: List[str] = []
        self.diag: List[str] = []
        self.s = requests.Session()
        self.header = {
            "User-Agent": UA,
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
            "Accept-Language": "en-US,en;q=0.9,zh-CN;q=0.8",
            "Referer": self.site + "/",
            "Origin": self.site,
        }
        self.s.headers.update(self.header)
        self._gate_tried = False
        self._home = ""
        self._path_ok: Dict[str, str] = {}
        self._resolved: Dict[str, Tuple[List[Tuple[str, str]], str]] = {}
        self._ep_cache: Dict[str, List[str]] = {}
        self._cats: List[Dict[str, Any]] = []
        self._cat_seen: set = set()
        self._stage = 0
        self._stage_ts = 0.0
        self._deadline = 0.0

    # ---------------- 生命周期 ----------------

    def getName(self) -> str:
        return "ParadiseHill"

    def init(self, extend: Any = "") -> None:
        """零网络: 只解析配置。"""
        try:
            cfg: Dict[str, Any] = {}
            if isinstance(extend, dict):
                cfg = extend
            elif isinstance(extend, str) and extend.strip().startswith("{"):
                cfg = json.loads(extend)
            if cfg.get("site"):
                self.site = str(cfg["site"]).rstrip("/")
                self.header["Referer"] = self.site + "/"
                self.header["Origin"] = self.site
                self.s.headers.update(self.header)
            for key in ("timeout", "budget"):
                if cfg.get(key):
                    setattr(self, key, float(cfg[key]))
        except Exception as exc:  # noqa: BLE001
            self.log(f"init 配置异常 {exc}")

    def destroy(self) -> None:
        try:
            self.s.close()
        except Exception:  # noqa: BLE001
            pass

    def log(self, msg: str) -> None:
        line = f"[PH] {msg}"
        self.logs.append(line)
        self.diag.append(line)
        if len(self.logs) > 400:
            del self.logs[:120]
        print(line)

    def _left(self) -> float:
        return self._deadline - time.monotonic() if self._deadline else 999.0

    # ---------------- 传输 ----------------

    @resilient(tries=2)
    def get(self, url: str, **kw) -> Optional[str]:
        kw.setdefault("timeout", self.timeout)
        r = self.s.get(url, **kw)
        if r.status_code >= 400:
            raise RuntimeError(f"HTTP {r.status_code} {url}")
        if not r.encoding or r.encoding.lower() in ("iso-8859-1", "ascii"):
            r.encoding = "utf-8"
        return r.text

    def _fast(self, url: str) -> str:
        try:
            r = self.s.get(url, timeout=self.fast_timeout)
            if r.status_code >= 400:
                return ""
            if not r.encoding or r.encoding.lower() in ("iso-8859-1", "ascii"):
                r.encoding = "utf-8"
            return r.text
        except Exception:  # noqa: BLE001
            return ""

    def _probe(self, url: str, referer: str = "") -> int:
        if self._left() <= 0:
            return 0
        hdr = dict(self.header)
        hdr["Range"] = "bytes=0-2047"
        if referer:
            hdr["Referer"] = referer
        for use_head in (False, True):
            try:
                if use_head:
                    r = self.s.head(url, headers=hdr, timeout=self.probe_timeout, allow_redirects=True)
                else:
                    r = self.s.get(url, headers=hdr, timeout=self.probe_timeout,
                                   stream=True, allow_redirects=True)
                code = r.status_code
                r.close()
                if code in (200, 206, 416):
                    return code
                if code in (403, 404, 410):
                    return code
            except Exception:  # noqa: BLE001
                continue
        return 0

    def _exists(self, url: str, referer: str = "") -> bool:
        return self._probe(url, referer) in (200, 206, 416)

    def _fetch_page(self, ident: str) -> str:
        for host in [self.site] + [m for m in MIRRORS if m != self.site]:
            page = self._fast(f"{host}/{ident}/")
            if page and re.search(r'\bh1\b|<title', page, re.I):
                return page
        return ""

    # ---------------- 年龄门(惰性, 单次) ----------------

    def ensure_gate(self) -> None:
        if self._gate_tried:
            return
        self._gate_tried = True
        page = self._fast(self.site + "/")
        if not page:
            return
        self._home = page
        if not any(k in page[:4000].lower() for k in ("come of age", "majority", "confirm your age")):
            return
        self.log("年龄门")
        for name in ("age", "adult", "confirm", "age_confirm", "adult_confirm", "ph_age"):
            try:
                self.s.cookies.set(name, "1", domain=".paradisehill.cc")
            except Exception:  # noqa: BLE001
                pass
        form = re.search(r'<form[^>]*action="([^"]+)"[^>]*>(.*?)</form>', page, re.S | re.I)
        if form:
            action = urljoin(self.site + "/", html_lib.unescape(form.group(1)))
            fields = dict(re.findall(r'<input[^>]*name="([^"]+)"[^>]*value="([^"]*)"', form.group(2), re.I))
            try:
                self.s.post(action, data=fields, timeout=self.fast_timeout)
                return
            except Exception:  # noqa: BLE001
                pass
        for href, text in re.findall(r'<a[^>]+href="([^"]+)"[^>]*>(.*?)</a>', page, re.S | re.I):
            if re.search(r'confirm|enter|agree|adult|18', href + clean(text), re.I):
                self._fast(urljoin(self.site + "/", html_lib.unescape(href)))
                return

    # ---------------- 列表 ----------------

    def cards(self, page: str) -> List[Dict[str, str]]:
        if not page:
            return []
        out, seen = [], set()
        for m in RE_ROUTE.finditer(page):
            vid = m.group(2)
            if vid in seen:
                continue
            seen.add(vid)
            block = page[max(0, m.start() - 700): m.end() + 700]
            pic = ""
            for img in RE_IMG_TAG.finditer(block):
                for cand in RE_LAZY.finditer(img.group(0)):
                    u = html_lib.unescape(cand.group(1))
                    if u.startswith("data:") or "lazy" in u or "blank" in u:
                        continue
                    pic = urljoin(self.site + "/", u)
                    break
                if pic:
                    break
            name = ""
            alt = RE_ALT.search(block)
            if alt:
                name = clean(alt.group(1))
            if not name:
                t = RE_TITLE_ATTR.search(m.group(0))
                if t:
                    name = clean(t.group(1))
            if not name:
                name = clean(page[m.end(): m.end() + 300].split("<")[0])
            if not name:
                continue
            out.append({"vod_id": vid, "vod_name": name, "vod_pic": pic, "vod_remarks": ""})
            if len(out) >= self.max_items:
                break
        return out

    # ---------------- 分类取证 ----------------

    def _slug_ok(self, slug: str) -> bool:
        return bool(slug) and bool(RE_SLUG_OK.fullmatch(slug)) and slug not in JUNK_SLUG

    def _absorb(self, kind: str, slug: str, name: str, verified: bool = True) -> bool:
        slug = html_lib.unescape(slug).strip().lower().strip("/")
        key = kind + ":" + slug
        if not self._slug_ok(slug) or len(self._cats) >= MAX_CATS:
            return False
        label = clean(name)
        if not label or len(label) > 34:
            label = slug.replace("-", " ").title()
        if key in self._cat_seen:
            for c in self._cats:
                if c["type_id"] == key:
                    if len(label) > len(c["type_name"]):
                        c["type_name"] = label
                    if verified:
                        c["v"] = True
                    break
            return False
        self._cat_seen.add(key)
        self._cats.append({"type_id": key, "type_name": label, "v": verified})
        return True

    def _harvest(self, page: str, verified: bool = True) -> int:
        if not page:
            return 0
        before = len(self._cats)
        for rx in (RE_A_PAIR, RE_OPT_PAIR):
            for m in rx.finditer(page):
                href = html_lib.unescape(m.group(1) or m.group(2) or m.group(3) or "")
                label = clean(m.group(4))
                for kind_raw, slug in RE_TAXO_PATH.findall(href):
                    self._absorb("t" if kind_raw.lower().startswith("tag") else "c",
                                 slug, label, verified)
        for m in RE_HREF.finditer(page):
            href = html_lib.unescape(m.group(1) or m.group(2) or m.group(3) or "")
            for kind_raw, slug in RE_TAXO_PATH.findall(href):
                self._absorb("t" if kind_raw.lower().startswith("tag") else "c", slug, "", verified)
        for line in RE_CATS_LINE.findall(page):
            for name in re.split(r'[,/|]', clean(line)):
                s = slugify(name)
                if s:
                    self._absorb("c", s, name, False)
        return len(self._cats) - before

    def _harvest_index(self, base: str, start: int = 1, end: int = 1) -> int:
        total = 0
        first = None
        for p in range(start, end + 1):
            if self._left() <= 0:
                break
            sep = "&" if "?" in base else "?"
            page = self._fast(self.site + base if p == 1 else f"{self.site}{base}{sep}page={p}")
            if not page:
                break
            if first is None:
                first = page
            if self._harvest(page) == 0:
                break
            total += 1
        return total

    def _letters_from(self, page: str) -> List[str]:
        seen: List[str] = []
        for _url, ch in RE_LETTER_LINK.findall(page or ""):
            ch = ch.lower()
            if ch.isalnum() and ch not in seen:
                seen.append(ch)
        return seen

    def _letter_sweep(self, letters: Iterable[str]) -> None:
        for ch in letters:
            if self._left() <= 0:
                return
            hit = False
            for base in ("/categories/", "/category/", "/tags/"):
                for case in (ch, ch.upper()):
                    page = self._fast(f"{self.site}{base}?letter={case}")
                    if page and self._harvest(page):
                        hit = True
                        break
                if hit:
                    break

    def _sitemaps(self, children: bool = False) -> None:
        for path in SITEMAPS:
            if self._left() <= 0:
                return
            root = self._fast(self.site + path)
            if not root:
                continue
            locs = RE_SITEMAP_LOC.findall(root)
            if not locs:
                continue
            for loc in locs:
                if loc.lower().endswith(".xml"):
                    continue
                for kind_raw, slug in RE_TAXO_PATH.findall(loc):
                    self._absorb("t" if kind_raw.lower().startswith("tag") else "c", slug, "", True)
            if children and self._left() > 1:
                for child in [l for l in locs if l.lower().endswith(".xml")][:4]:
                    if self._left() <= 0:
                        return
                    for loc in RE_SITEMAP_LOC.findall(self._fast(child)):
                        for kind_raw, slug in RE_TAXO_PATH.findall(loc):
                            self._absorb("t" if kind_raw.lower().startswith("tag") else "c", slug, "", True)
            if len(self._cats) > 80:
                return

    def _verify(self, cap: int = 24) -> None:
        order = sorted(self._cats, key=lambda c: 0 if c["type_id"].partition(":")[2] in SEEDS else 1)
        budget = cap
        keep: List[Dict[str, Any]] = []
        for c in order:
            if c["v"] or budget <= 0 or self._left() <= 0:
                keep.append(c)
                continue
            budget -= 1
            slug = c["type_id"].partition(":")[2]
            bases = ("/category/", "/tag/") if c["type_id"].startswith("c:") else ("/tag/", "/category/")
            for base in bases:
                if self._probe(f"{self.site}{base}{quote(slug)}/") in (200, 206):
                    c["v"] = True
                    self._path_ok[slug] = base + slug + "/"
                    keep.append(c)
                    break
        dropped = len(self._cats) - len(keep)
        self._cats = keep
        if dropped:
            self.log(f"证伪剔除 {dropped}")

    def _stage_run(self, stage: int) -> None:
        if stage == 0:
            for s in SEEDS:
                self._absorb("c", s, "", False)
            n = self._harvest_index("/categories/", 1, 1)
            self.log(f"/categories/ 首页收割 {n}")
            if not n:
                self._harvest(self._home or "")
        elif stage == 1:
            self._harvest_index("/categories/", 2, 8)
            self._harvest_index("/category/", 1, 2)
            self._harvest_index("/tags/", 1, 2)
        elif stage == 2:
            letters = self._letters_from(self._home or "") or list("abcdefghijklmnop")
            self._letter_sweep(letters)
            self._sitemaps(False)
        else:
            self._letter_sweep("qrstuvwxyz")
            self._sitemaps(True)
            self._verify()

    def _build_categories(self, advance: bool = True) -> List[Dict[str, Any]]:
        done = self._stage >= STAGES
        if self._cats and done and time.time() - self._stage_ts < self.cat_ttl:
            return self._cats
        if not advance:
            return self._cats
        stage = min(self._stage, STAGES - 1)
        try:
            self._stage_run(stage)
        except Exception as exc:  # noqa: BLE001
            self.log(f"阶段{stage}异常 {exc}")
        self._stage = min(STAGES, self._stage + 1)
        self._stage_ts = time.time()
        self._cats.sort(key=lambda c: (c["type_id"][0], c["type_name"].lower()))
        self.log(f"分类 stage={self._stage} 累计={len(self._cats)}")
        return self._cats

    def _harvest_studios(self, bag: List[Dict[str, str]], seen: set, cap: int = 30) -> None:
        rx = re.compile(r'<a\b[^>]*href="([^"]*?/studio/(\d+)/)"[^>]*>(.*?)</a>', re.S | re.I)
        for p in (1, 2):
            if self._left() <= 0:
                return
            page = self._fast(f"{self.site}/studios/?page={p}")
            if not page:
                return
            for _h, sid, text in rx.findall(page):
                key = "s:" + sid
                name = clean(text)
                if key in seen or not name or len(name) > 34:
                    continue
                seen.add(key)
                bag.append({"type_id": key, "type_name": "★ " + name})
                if len(bag) >= cap:
                    return

    def homeContent(self, filter: bool = True) -> Dict[str, Any]:
        t0 = time.monotonic()
        self._deadline = t0 + self.budget
        classes: List[Dict[str, str]] = [{"type_id": "n", "type_name": "最新收录"}]
        try:
            self.ensure_gate()
            for c in self._build_categories():
                classes.append({"type_id": c["type_id"], "type_name": c["type_name"]})
        except Exception as exc:  # noqa: BLE001
            self.log(f"分类失败 {exc}")
        seen = {c["type_id"] for c in classes}
        if time.monotonic() - t0 < 7.0:
            try:
                self._harvest_studios(classes, seen)
            except Exception as exc:  # noqa: BLE001
                self.log(f"片商失败 {exc}")
        filters = {c["type_id"]: [{"key": "sort", "name": "排序",
                                  "value": [{"n": n, "v": v} for v, n in SORTS]}]
                   for c in classes if not c["type_id"].startswith("s:")}
        self._deadline = 0.0
        return {"class": classes, "filters": filters}

    def homeVideoContent(self) -> Dict[str, Any]:
        self.ensure_gate()
        return {"list": self.cards(self._home or self._fast(self.site + "/porn/"))}

    def _path_candidates(self, tid: str) -> List[str]:
        kind, _, val = (tid or "n").partition(":")
        val = quote(val.strip())
        if kind == "s" and val:
            return [f"/studio/{val}/"]
        if kind == "c" and val:
            cached = self._path_ok.get(val)
            ladder = [f"/category/{val}/", f"/{val}/", f"/categories/{val}/"]
            return ([cached] + [p for p in ladder if p != cached]) if cached else ladder
        if kind == "t" and val:
            cached = self._path_ok.get("t:" + val)
            ladder = [f"/tag/{val}/", f"/tags/{val}/", f"/{val}/"]
            return ([cached] + [p for p in ladder if p != cached]) if cached else ladder
        return ["/porn/"]

    def categoryContent(self, tid: str, pg: Any = 1, filter: bool = False,
                        extend: Any = None) -> Dict[str, Any]:
        self.ensure_gate()
        hit = RE_DIGITS.search(str(pg))
        page_no = int(hit.group()) if hit else 1
        sort = str(extend.get("sort")) if isinstance(extend, dict) and extend.get("sort") else "created_at"
        val = (tid or "").partition(":")[2].strip()
        html_text, items, used = "", [], ""
        for path in self._path_candidates(tid):
            html_text = self._fast(f"{self.site}{path}?sort={sort}&page={page_no}")
            items = self.cards(html_text)
            if not items and page_no > 1:
                html_text = self._fast(f"{self.site}{path}page/{page_no}/?sort={sort}")
                items = self.cards(html_text)
            if items:
                used = path
                break
        if used and val:
            self._path_ok[val] = used
        pagecount = page_no + 1 if len(items) >= 12 else page_no
        nums = [int(x) for x in re.findall(r'[?&]page=(\d+)', html_text)]
        nums += [int(x) for x in re.findall(r'/page/(\d+)', html_text)]
        if nums:
            pagecount = max(pagecount, max(nums))
        return {"list": items, "page": page_no, "pagecount": pagecount,
                "limit": len(items), "total": pagecount * max(len(items), 1)}

    # ---------------- 详情字段 ----------------

    def _ident(self, raw: str) -> Optional[str]:
        raw = (raw or "").strip()
        if not raw:
            return None
        m = re.search(r'/([0-9a-f]{6,})/?$', raw)
        if m:
            return m.group(1)
        return raw if re.fullmatch(r'[0-9a-f]{6,}', raw) else None

    def _meta(self, page: str) -> Dict[str, str]:
        bag: Dict[str, str] = {}
        for key, val in RE_META.findall(page or ""):
            bag.setdefault(key.lower(), clean(val))
        for blob in RE_JSONLD.findall(page or ""):
            try:
                data = json.loads(blob.strip())
            except Exception:  # noqa: BLE001
                continue
            stack = data if isinstance(data, list) else [data]
            while stack:
                node = stack.pop()
                if isinstance(node, dict):
                    for k in ("name", "description", "thumbnailUrl", "contentUrl",
                              "embedUrl", "uploadDate", "duration"):
                        if isinstance(node.get(k), str):
                            bag.setdefault("ld:" + k, clean(node[k]))
                    stack.extend(node.values())
                elif isinstance(node, list):
                    stack.extend(node)
        return bag

    # ---------------- 地址取证 ----------------

    def _abs(self, u: str) -> str:
        u = html_lib.unescape(u.strip())
        if u.startswith("//"):
            return "https:" + u
        if u.startswith("/"):
            return MEDIA_HOST + u if u.startswith("/video/") or u.startswith("/hls/") else self.site + u
        return u

    def _explicit(self, text: str) -> List[Tuple[str, str]]:
        text = html_lib.unescape((text or "").replace("\\/", "/").replace("\\u002F", "/"))
        eps: List[Tuple[str, str]] = []
        seen = set()

        def push(name: str, raw: str) -> None:
            u = self._abs(raw)
            if u in seen or not u.startswith("http"):
                return
            seen.add(u)
            eps.append((name, u))

        for m in RE_MEDIA.finditer(text):
            u = m.group(0).rstrip(".,;")
            if ".m3u8" in u.lower() and re.search(r'paradisehill|/video/|/hls/', u, re.I):
                push(HLS_LABEL, u)
                break
        for rx in (RE_SOURCE, RE_JSONFILE):
            for raw in rx.findall(text):
                if ".m3u8" in raw.lower():
                    push(HLS_LABEL, raw)
        for raw in RE_MEDIA_REL.findall(text):
            if ".m3u8" in raw.lower() and re.search(r'/video/|/hls/', raw, re.I):
                push(HLS_LABEL, raw)

        groups: Dict[Tuple[str, int], Dict[int, str]] = {}
        for m in RE_PART_URL.finditer(text):
            url, tok, q, part = m.group(1), m.group(2), int(m.group(3)), int(m.group(4))
            groups.setdefault((tok, q), {})[part] = self._abs(url)
        for m in RE_PART_REL.finditer(text):
            tok, q, part = m.group(1), int(m.group(2)), int(m.group(3))
            groups.setdefault((tok, q), {}).setdefault(part, f"{MEDIA_HOST}/video/{tok}_{q}_part{part}.mp4")
        if groups:
            tok, q = max(groups, key=lambda k: (len(groups[k]), k[1]))
            parts = groups[(tok, q)]
            total = max(parts)
            labels = part_labels(total, q)
            for i in range(1, total + 1):
                push(labels[i - 1], parts.get(i) or f"{MEDIA_HOST}/video/{tok}_{q}_part{i}.mp4")

        for rx in (RE_SOURCE, RE_JSONFILE):
            for raw in rx.findall(text):
                if ".mp4" in raw.lower():
                    push("单段直链", raw)
        return eps

    def _cover_tokens(self, page: str) -> List[str]:
        out: List[str] = []
        for m in RE_META.finditer(page or ""):
            if "image" not in m.group(1).lower():
                continue
            name = urlparse(html_lib.unescape(m.group(2))).path.rsplit("/", 1)[-1]
            stem = name.rsplit(".", 1)[0]
            for tok in re.split(r'[^A-Za-z0-9]+', stem):
                if 8 <= len(tok) <= 24:
                    out.append(tok)
        return out

    def _tokens(self, text: str, ident: str = "") -> List[str]:
        text = html_lib.unescape((text or "").replace("\\/", "/"))
        scored: Dict[str, float] = {}
        for rx, weight in TOKEN_RULES:
            for tok in rx.findall(text):
                scored[tok.strip()] = max(scored.get(tok.strip(), 0.0), weight)
        for tok in self._cover_tokens(text):
            scored[tok] = max(scored.get(tok, 0.0), 6.0)
        for win in RE_NEAR.findall(text):
            for tok in RE_ALNUM.findall(win):
                if re.search(r'\d', tok) or len(tok) >= 11:
                    scored[tok] = max(scored.get(tok, 0.0), 1.5)
        if ident:
            scored[ident] = max(scored.get(ident, 0.0), 2.0)
        return [t for t, _ in sorted(scored.items(), key=lambda kv: -kv[1])[: self.max_tokens]]

    # ---------------- 探针与展开 ----------------

    def _fmt(self, tpl: str, token: str, q: int, n: int) -> str:
        return tpl.format(m=MEDIA_HOST, s=self.site, t=token, q=q, n=n, n2=f"{n:02d}", i=token)

    def _quick(self, token: str, ref: str) -> bool:
        for u in (f"{MEDIA_HOST}/video/{token}_1_part1.mp4",
                  f"{MEDIA_HOST}/video/{token}_1_part01.mp4",
                  f"{MEDIA_HOST}/video/{token}/1.mp4"):
            if self._exists(u, ref):
                return True
        return False

    def _probe_hls(self, token: str, ref: str) -> str:
        for tpl in HLS_TPL:
            for q in (1, 2):
                url = self._fmt(tpl, token, q, 1)
                if self._exists(url, ref):
                    return url
        return ""

    def _probe_parts(self, token: str, ref: str) -> List[Tuple[str, str]]:
        for q in (1, 2, 3):
            for tpl in PART_TPL:
                first = self._fmt(tpl, token, q, 1)
                if not self._exists(first, ref):
                    continue
                self.log(f"模板锁定 t={token} tpl={tpl} q={q}")
                urls = [first]
                misses = 0
                for i in range(2, self.max_parts + 1):
                    url = self._fmt(tpl, token, q, i)
                    if self._exists(url, ref):
                        urls.append(url)
                        misses = 0
                    else:
                        misses += 1
                        if misses >= 2:
                            break
                return list(zip(part_labels(len(urls), q), urls))
        return []

    def _discover(self, page: str) -> List[str]:
        found: List[str] = []

        def grab(blob: str) -> None:
            for path in RE_ENDPOINT.findall(blob):
                if path.count("/") > 5 or path in found:
                    continue
                found.append(path)

        grab(page)
        for src in RE_SCRIPT.findall(page)[:3]:
            url = urljoin(self.site + "/", html_lib.unescape(src))
            if "paradisehill" not in url:
                continue
            body = self._ep_cache.get(url, [""])[0] or self._fast(url)
            self._ep_cache[url] = [body]
            grab(body)
        return found[:8]

    def resolve(self, ident: str, page: Optional[str] = None) -> Tuple[List[Tuple[str, str]], str]:
        if ident in self._resolved:
            eps, note = self._resolved[ident]
            return list(eps), note

        page = page if page is not None else self._fetch_page(ident)
        ref = f"{self.site}/{ident}/"

        eps = self._explicit(page)
        if eps:
            self._resolved[ident] = (eps, "explicit")
            return list(eps), "explicit"

        bodies = [page]
        urls = [tpl.format(s=self.site, m=MEDIA_HOST, i=ident) for tpl in PLAYER_TPL]
        urls += [urljoin(self.site + "/", p.lstrip("/")) for p in self._discover(page)]
        for url in dict.fromkeys(urls):
            if len(bodies) >= 6:
                break
            body = self._fast(url)
            if not body or len(body) < 60:
                continue
            bodies.append(body)
            self.log(f"端点 {len(body)}B {url}")
            if re.search(r'_part\d|\.mp4|\.m3u8', body, re.I):
                break

        blob = "\n".join(bodies)
        eps = self._explicit(blob)
        if eps:
            self._resolved[ident] = (eps, "endpoint")
            return list(eps), "endpoint"

        for emb in self._iframes(blob):
            body = self._fast(emb)
            if body:
                blob += "\n" + body
                eps = self._explicit(body)
                if eps:
                    self._resolved[ident] = (eps, "iframe")
                    return list(eps), "iframe"

        for tok in self._tokens(blob, ident):
            if not self._quick(tok, ref):
                self.diag.append(f"token {tok} 速判失败")
                continue
            hls = self._probe_hls(tok, ref)
            parts = self._probe_parts(tok, ref)
            if hls or parts:
                eps = ([(HLS_LABEL, hls)] if hls else []) + parts
                note = "hls" if hls else "probe"
                self.log(f"token 生效 {tok} {note} {len(eps)}集")
                self._resolved[ident] = (eps, note)
                return list(eps), note

        self._resolved[ident] = ([], "none")
        return [], "none"

    def _iframes(self, text: str) -> List[str]:
        out: List[str] = []
        for raw in RE_IFRAME.findall(html_lib.unescape(text or "")):
            u = urljoin(self.site + "/", raw.strip())
            if u.startswith("http") and u not in out and "/ad" not in u:
                out.append(u)
        return out[:3]

    # ---------------- 详情 ----------------

    def detailContent(self, ids: Any) -> Dict[str, Any]:
        raw = ids[0] if isinstance(ids, (list, tuple)) and ids else str(ids)
        ident = self._ident(raw)
        if not ident:
            return {"list": []}
        self.ensure_gate()
        self._deadline = time.monotonic() + 12.0
        try:
            page = self._fetch_page(ident)
            meta = self._meta(page)
            self._harvest(page, verified=True)

            name = meta.get("og:title") or meta.get("ld:name")
            if not name:
                h1 = re.search(r'<h1[^>]*>(.*?)</h1>', page, re.S | re.I)
                name = clean(h1.group(1)) if h1 else ""
            if not name:
                title = re.search(r'<title[^>]*>(.*?)</title>', page, re.S | re.I)
                name = clean(title.group(1)) if title else ""
                name = re.sub(r'^(?:Porn Film Online\s*[-–]\s*)', "", name)
                name = re.sub(r'\s*[-–]\s*(?:Watching Free!?|смотреть онлайн).*$', "", name)

            pic = meta.get("og:image") or meta.get("ld:thumbnailUrl") or ""
            if not pic:
                for img in RE_IMG_TAG.finditer(page):
                    for cand in RE_LAZY.finditer(img.group(0)):
                        u = cand.group(1)
                        if u.startswith("http") and re.search(r'\.(?:jpe?g|png|webp)', u, re.I):
                            pic = u
                            break
                    if pic:
                        break

            studio = re.search(r'Studio:\s*([^<\n]+)', page, re.I)
            cats = re.search(r'Categor(?:y|ies):\s*([^<\n]+)', page, re.I)
            rel = re.search(r'Release date:\s*([0-9]{1,2}\s+\w+\s+(\d{4}))', page, re.I)
            dur = re.search(r'Duration:\s*([0-9:]{4,10})', page, re.I)

            content = (meta.get("og:description") or meta.get("description")
                       or meta.get("ld:description") or "")
            if not content:
                desc = re.search(r'Description:\s*(.{40,900}?)(?:<br|\n\n|Studio:)', page, re.S | re.I)
                content = clean(desc.group(1)) if desc else ""
            if not content:
                content = name or ident

            eps, note = self.resolve(ident, page)
            parts = [e for e in eps if e[0] != HLS_LABEL]
            marks: List[str] = []
            if parts:
                marks.append(f"共{len(parts)}段")
            elif eps:
                marks.append("HLS")
            if dur:
                marks.insert(0, dur.group(1))
            if rel:
                marks.append(rel.group(1))

            play_url = "#".join(f"{n}${u}" for n, u in eps) if eps else f"正片${ident}"
            self.log(f"详情 {ident} 集数={len(eps)} 分段={len(parts)} via={note}")

            return {"list": [{
                "vod_id": ident,
                "vod_name": name or ident,
                "vod_pic": pic,
                "type_name": clean(cats.group(1)) if cats else "",
                "vod_year": rel.group(2) if rel else "",
                "vod_area": clean(studio.group(1)) if studio else "",
                "vod_remarks": " ".join(marks),
                "vod_content": content,
                "vod_play_from": "ParadiseHill",
                "vod_play_url": play_url,
            }]}
        except Exception as exc:  # noqa: BLE001
            self.log(f"详情异常 {exc}")
            return {"list": [{"vod_id": ident, "vod_name": ident,
                              "vod_play_from": "ParadiseHill",
                              "vod_play_url": f"正片${ident}"}]}
        finally:
            self._deadline = 0.0

    # ---------------- 搜索 ----------------

    def searchContent(self, key: str, quick: bool = False, pg: Any = 1) -> Dict[str, Any]:
        self.ensure_gate()
        q = quote((key or "").strip())
        if not q:
            return {"list": []}
        for url in (f"{self.site}/search/?q={q}", f"{self.site}/search/?text={q}",
                    f"{self.site}/search/{q}/", f"{self.site}/search/{q}?",
                    f"{self.site}/poisk/?q={q}"):
            page = self._fast(url)
            if not page:
                continue
            items = self.cards(page)
            if items:
                self.log(f"搜索命中 {url}")
                return {"list": items, "page": 1, "pagecount": 1,
                        "limit": len(items), "total": len(items)}
        return {"list": [], "page": 1, "pagecount": 1, "limit": 0, "total": 0}

    # ---------------- 播放 ----------------

    def _score_media(self, url: str) -> float:
        low = url.lower()
        s = 0.0
        if ".m3u8" in low:
            s += 60.0
        if "master" in low:
            s += 12.0
        if ".mp4" in low:
            s += 20.0
        if "part1" in low:
            s += 6.0
        if "v1." in low or "/video/" in low:
            s += 5.0
        if low.startswith("https:"):
            s += 3.0
        return s

    def _media(self, text: str) -> List[Hypothesis]:
        out, seen = [], set()
        for m in RE_MEDIA.finditer(html_lib.unescape(text or "")):
            u = self._abs(m.group(0).rstrip(".,;"))
            if u in seen or not u.startswith("http"):
                continue
            seen.add(u)
            out.append(Hypothesis(self._score_media(u), "media", u))
        return out

    def _best(self, cands: Iterable[Hypothesis]) -> Optional[Hypothesis]:
        pool = [c for c in cands if c.url]
        return max(pool) if pool else None

    def playerContent(self, flag: str, id: str, vipFlags: Any = None) -> Dict[str, Any]:
        raw = (id or "").strip()
        if raw.startswith("http") and re.search(r'\.(?:m3u8|mp4)(?:\?|$)', raw, re.I):
            return {"parse": 0, "url": raw, "header": self.header}

        ident = self._ident(raw)
        if not ident:
            return {"parse": 1, "url": raw, "header": self.header, "jx": 1}

        self.ensure_gate()
        ref = f"{self.site}/{ident}/"
        hdr = {**self.header, "Referer": ref}
        self._deadline = time.monotonic() + 18.0
        try:
            eps, note = self.resolve(ident)
            for name, url in eps:
                code = self._probe(url, ref)
                if code in (200, 206, 416):
                    self.log(f"播放 {name} via={note} {code}")
                    return {"parse": 0, "url": url, "header": hdr}
                self.log(f"死链 {name} {code} {url[:70]}")

            page = self._fetch_page(ident)
            for cand in sorted(self._media(page), reverse=True):
                if self._probe(cand.url, ref) in (200, 206, 416):
                    return {"parse": 0, "url": cand.url, "header": hdr}
            embeds = self._iframes(page)
            if embeds:
                return {"parse": 1, "url": embeds[0], "header": hdr, "jx": 1}
            return {"parse": 1, "url": f"{self.site}/{ident}/", "header": hdr, "jx": 1}
        finally:
            self._deadline = 0.0

    def isVideoFormat(self, url: str) -> bool:
        return bool(re.search(r'\.(?:m3u8|mp4|flv|mkv)(?:\?|$)', url or "", re.I))

    def manualVideoCheck(self) -> bool:
        return False

    def localProxy(self, param: Any) -> Optional[list]:
        return None

    # ---------------- 诊断 ----------------

    def diagnose(self, ident: str) -> None:
        t0 = time.monotonic()
        first = self._fast(self.site + "/categories/")
        print(f"/categories/ {len(first)}B {time.monotonic() - t0:.2f}s  "
              f"链接={len(RE_TAXO_PATH.findall(first))}")
        for m in list(RE_A_PAIR.finditer(first))[:12]:
            print("   ", clean(m.group(4))[:28], "|", (m.group(1) or m.group(2) or m.group(3)))
        self._deadline = time.monotonic() + self.budget
        for i in range(STAGES):
            t = time.monotonic()
            cats = self._build_categories()
            print(f"第{i + 1}轮 累计={len(cats)} 耗时={time.monotonic() - t:.2f}s")
        self._deadline = 0.0
        print("总数:", len(self._cats))


def _selftest(ident: Optional[str] = None, diag: bool = False) -> int:
    sp = Spider()
    sp.init(json.dumps({"site": DEFAULT_SITE}))
    if diag:
        sp.diagnose(ident or "")
        return 0
    t0 = time.monotonic()
    home = sp.homeContent(True)
    first = time.monotonic() - t0
    print(f"首屏 {len(home.get('class', []))} 项, {first:.2f}s")
    for i in range(STAGES - 1):
        t = time.monotonic()
        h = sp.homeContent(True)
        print(f"第{i + 2}轮 {len(h.get('class', []))} 项, {time.monotonic() - t:.2f}s")
    classes = (sp.homeContent(True) or {}).get("class", [])
    cats = [c for c in classes if c["type_id"].startswith(("c:", "t:"))]
    want = ("asian", "bbw", "anal", "animation", "bdsm", "big-ass", "big-tits",
            "classic", "ebony", "fetish", "french-porn")
    have = {c["type_id"].partition(":")[2] for c in cats}
    hit = [w for w in want if w in have]
    print(f"分类={len(cats)} 命中={len(hit)}/{len(want)}")
    print("样例:", [c["type_name"] for c in cats[:12]])

    alive = sum(1 for c in cats[:4]
                if (sp.categoryContent(c["type_id"], 1, True, None) or {}).get("list"))
    tid = cats[0]["type_id"] if cats else "n"
    items = (sp.categoryContent(tid, 1, True, None) or {}).get("list", [])
    target = ident or (items[0]["vod_id"] if items else "")
    row = ((sp.detailContent([target]) if target else {}).get("list") or [{}])[0]
    eps = [x for x in row.get("vod_play_url", "").split("#") if "$" in x]
    play = sp.playerContent("", eps[0].split("$", 1)[1]) if eps else {}
    print(f"集数={len(eps)} parse={play.get('parse', '-')} url={str(play.get('url', ''))[:100]}")

    ok = (first < 8 and len(hit) >= 9 and len(cats) >= 40
          and alive >= 2 and len(eps) >= 1)
    print("\n== 结论:", "OK" if ok else "仍有断点", "==")
    return 0 if ok else 1


if __name__ == "__main__":
    argv = [a for a in sys.argv[1:] if not a.startswith("--")]
    sys.exit(_selftest(argv[0] if argv else None, diag="--diag" in sys.argv))