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

v1.1.0 修复
-----------
* 集数: 分段 mp4 (`_{q}_part{N}.mp4`) 还原为多集, 写入 vod_play_url;
  段数来源 = 显式链接 > 段数变量 > Range 探针证伪。
* 分类: 三处取证 + slug 合法性过滤 + 路径阶梯 + 命中缓存 + 片商平铺。

设计哲学
--------
1) 证伪主义: 选择器与路径都是假设, 由页面证据检验, 失败即淘汰。
2) 奥卡姆剃刀: m3u8 > mp4 直链 > iframe > token 重建。
3) 控制论闭环: 提取器产出带 score 的 Hypothesis, 评分器回选。
4) 斯多葛降级: 门 -> 直链 -> iframe -> token -> parse=1。
5) 现象学: 只采纳页面自身暴露的证据。
"""

from __future__ import annotations

import functools
import html as html_lib
import json
import os
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

try:
    import requests
except Exception:
    # --- 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 ---
    requests.RequestException = requests.exceptions.RequestException
    requests.Timeout = requests.exceptions.Timeout
    requests.ConnectionError = requests.exceptions.ConnectionError
    requests.HTTPError = requests.exceptions.HTTPError
    requests.SSLError = requests.exceptions.SSLError
    def _req_mount(self, prefix, adapter):
        pass
    requests.Session.mount = _req_mount
    requests.Session.proxies = {}
    requests.Session.trust_env = True
    class _CookieDict(dict):
        def set(self, name, value, **kw):
            self[name] = value
        def get_dict(self):
            return dict(self)
        def clear(self):
            dict.clear(self)
    _orig_sess_init = requests.Session.__init__
    def _sess_init(self, *a, **kw):
        _orig_sess_init(self, *a, **kw)
        self.cookies = _CookieDict(self.cookies)
        self.proxies = {}
    requests.Session.__init__ = _sess_init
    _orig_sess_request = requests.Session.request
    def _sess_request(self, method, url, headers=None, timeout=15, data=None, json=None, params=None, cookies=None, verify=False, allow_redirects=True, stream=False, **kw):
            # 映匣适配：容忍 IncompleteRead（分片传输截断时用已读部分），并自动解 gzip/deflate
            import urllib.parse as _up2
            import urllib.request as _ur2
            import urllib.error as _ue2
            import http.client as _hc2
            import json as _json2
            if params:
                _qs = _up2.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 = _json2.dumps(json, ensure_ascii=False).encode("utf-8")
                _hd.setdefault("Content-Type", "application/json")
            elif isinstance(data, dict):
                _body = _up2.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()))
            _to = timeout
            if isinstance(_to, (tuple, list)):
                _to = max(_to)
            if _to and float(_to) > 120:
                _to = float(_to) / 1000.0
            _last_exc = None
            for _attempt in range(2):
                _req = _ur2.Request(url, data=_body, headers=_hd, method=method.upper())
                try:
                    with self._opener.open(_req, timeout=_to or 15) as _resp:
                        try:
                            _content = _resp.read()
                        except _hc2.IncompleteRead as _ire:
                            _content = _ire.partial or b""
                        _hdrs = dict(_resp.headers.items())
                        _final = _resp.geturl()
                        _status = _resp.status
                except _ue2.HTTPError as _he:
                    try:
                        _content = _he.read()
                    except _hc2.IncompleteRead as _ire:
                        _content = _ire.partial or b""
                    except Exception:
                        _content = b""
                    _hdrs = dict(_he.headers.items()) if _he.headers else {}
                    _final = _he.geturl() if hasattr(_he, "geturl") else url
                    _status = _he.code
                except Exception as _exc:
                    _last_exc = _exc
                    continue
                try:
                    _ce = (_hdrs.get("Content-Encoding", "") or "").lower()
                    if "gzip" in _ce:
                        import gzip as _gz
                        _content = _gz.decompress(_content)
                    elif "deflate" in _ce:
                        import zlib as _zl
                        _content = _zl.decompress(_content)
                except Exception:
                    pass
                for _c in self._jar:
                    self.cookies[_c.name] = _c.value
                return requests.Response(_status, _hdrs, _content, _final, dict(self.cookies))
            raise requests.exceptions.ConnectionError(str(_last_exc))
    requests.Session.request = _sess_request
    def _resp_apparent_encoding(self):
        _ct = self.headers.get("Content-Type", "") or ""
        return _ct.split("charset=")[-1].split(";")[0].strip() if "charset=" in _ct else "utf-8"
    requests.Response.apparent_encoding = property(_resp_apparent_encoding)
    requests.Response.ok = property(lambda self: self.status_code < 400)
    requests.Response.reason = property(lambda self: "")
    def _resp_apparent_encoding(self):
        _ct = self.headers.get("Content-Type", "") or ""
        return _ct.split("charset=")[-1].split(";")[0].strip() if "charset=" in _ct else "utf-8"
    requests.Response.apparent_encoding = property(_resp_apparent_encoding)
    requests.Response.ok = property(lambda self: self.status_code < 400)
    requests.Response.reason = property(lambda self: "")
    class _ReqUtils:
        @staticmethod
        def quote(s, safe="/"):
            import urllib.parse as _up
            return _up.quote(s, safe=safe)
        @staticmethod
        def unquote(s):
            import urllib.parse as _up
            return _up.unquote(s)
    requests.utils = _ReqUtils
__version__ = "1.1.0"

DEFAULT_SITE = "https://en.paradisehill.cc"
MEDIA_HOST = "https://v1.paradisehill.cc"

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_TOKEN = re.compile(r'(?:video[_-]?id|videoId|videoid|file[_-]?id|movie[_-]?id)'
                      r'["\']?\s*[:=]\s*["\']([A-Za-z0-9]{5,24})["\']')
RE_VIDEO_PATH = re.compile(r'/video/([A-Za-z0-9]{5,24})_1_part1\.mp4', re.I)
# 分段直链: //host/video/{token}_{q}_part{n}.mp4
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_PARTS_VAR = re.compile(r'(?:parts?|part_count|total_?parts?|segments?|chunks?)\s*[:=]\s*["\']?(\d{1,3})', re.I)
RE_QUALITY = re.compile(r'_(\d{1,2})_part1\.mp4', re.I)

RE_TAG = re.compile(r'<[^>]+>')
RE_WS = re.compile(r'\s+')
RE_DIGITS = re.compile(r'\d+')
RE_SLUG_OK = re.compile(r'[a-z0-9][a-z0-9\-]{1,39}')

JUNK_SLUG = {"all", "new", "popular", "page", "help", "search", "login", "register",
             "news", "studios", "studio", "porn", "category", "categories", "tags",
             "terms", "privacy", "advertisers", "about"}

SORTS: Tuple[Tuple[str, str], ...] = (
    ("created_at", "最新收录"),
    ("release", "发行日期"),
    ("title", "标题"),
    ("by_films", "片数"),
)

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)


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


# ---------------------------------------------------------------- 主体

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

    def __init__(self) -> None:
        self.site = DEFAULT_SITE
        self.timeout = 14
        self.max_items = 42
        self.max_parts = 60
        self.logs: 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 + "/",
        }
        self.s.headers.update(self.header)
        self._gated = False
        self._path_ok: Dict[str, str] = {}

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

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

    def init(self, extend: Any = "") -> None:
        cfg: Dict[str, Any] = {}
        if isinstance(extend, dict):
            cfg = extend
        elif isinstance(extend, str) and extend.strip().startswith("{"):
            try:
                cfg = json.loads(extend)
            except Exception:  # noqa: BLE001
                cfg = {}
        site = (cfg.get("site") or "").rstrip("/")
        if site:
            self.site = site
            self.header["Referer"] = self.site + "/"
            self.s.headers.update(self.header)
        if cfg.get("timeout"):
            self.timeout = int(cfg["timeout"])
        self.pass_gate()

    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)
        if len(self.logs) > 300:
            del self.logs[:100]
        print(line)

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

    @resilient(tries=3)
    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

    @resilient(tries=2)
    def post(self, url: str, data: Dict[str, str]) -> Optional[str]:
        r = self.s.post(url, data=data, timeout=self.timeout,
                        headers={"Referer": self.site + "/"})
        if r.status_code >= 400:
            raise RuntimeError(f"HTTP {r.status_code} {url}")
        return r.text

    def _exists(self, url: str) -> bool:
        """Range 探针: 只取 1KB, 用来证伪"这一段存在吗"。"""
        try:
            r = self.s.get(url, headers={**self.header, "Range": "bytes=0-1023"},
                           timeout=8, stream=True)
            ok = r.status_code in (200, 206)
            r.close()
            return ok
        except Exception:  # noqa: BLE001
            return False

    # ---------------- 年龄门 ----------------

    def pass_gate(self) -> bool:
        if self._gated:
            return True
        page = self.get(self.site + "/")
        if not page:
            return False
        if not any(k in page[:4000].lower() for k in ("come of age", "majority", "confirm your age")):
            self._gated = True
            return True
        self.log("检测到年龄门")

        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))
            if self.post(action, fields) is not None:
                self._gated = True
                return True

        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):
                if self.get(urljoin(self.site + "/", html_lib.unescape(href))) is not None:
                    self._gated = True
                    return True

        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
        self._gated = True
        return True

    # ---------------- 列表解析 ----------------

    def cards(self, page: str) -> List[Dict[str, str]]:
        if not page:
            return []
        out: List[Dict[str, str]] = []
        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 _harvest_categories(self, page: str, bag: List[Dict[str, str]], seen: set) -> None:
        rx = re.compile(r'<a\b[^>]*href="([^"]*?/(?:category|categories)/([^/"]+)/)"[^>]*>(.*?)</a>',
                        re.S | re.I)
        for _href, slug, text in rx.findall(page or ""):
            slug = html_lib.unescape(slug).strip().lower()
            if not self._slug_ok(slug) or slug in seen:
                continue
            name = clean(text)
            if not name or len(name) > 34:
                name = slug.replace("-", " ").title()
            seen.add(slug)
            bag.append({"type_id": "c:" + slug, "type_name": name})

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

    def homeContent(self, filter: bool = True) -> Dict[str, Any]:
        classes: List[Dict[str, str]] = [{"type_id": "n", "type_name": "最新收录"}]
        seen = {"n"}

        # 三处取证, 任一处命中即够用
        for url in (self.site + "/categories/", self.site + "/category/", self.site + "/"):
            page = self.get(url) or ""
            if not page:
                continue
            before = len(classes)
            self._harvest_categories(page, classes, seen)
            if len(classes) - before >= 3:
                break

        # 片商平铺(可点即分类, 无需假详情页)
        self._harvest_studios(self.get(self.site + "/studios/") or "", classes, seen)

        if len(classes) <= 1:  # 全证伪失败时的种子假设
            for slug, name in (("feature-films", "Feature films"), ("all-sex", "All Sex"),
                               ("anal-sex", "Anal Sex"), ("lesbian", "Lesbian")):
                classes.append({"type_id": "c:" + slug, "type_name": name})

        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:")}
        return {"class": classes, "filters": filters}

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

    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
        return ["/porn/"]

    def categoryContent(self, tid: str, pg: Any = 1, filter: bool = False,
                        extend: Any = None) -> Dict[str, Any]:
        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.get(f"{self.site}{path}?sort={sort}&page={page_no}") or ""
            items = self.cards(html_text)
            if not items and page_no > 1:
                html_text = self.get(f"{self.site}{path}page/{page_no}/?sort={sort}") or ""
                items = self.cards(html_text)
            if items:
                used = path
                break
        if used and val and used.startswith("/category/"):
            self._path_ok[val] = used
            self.log(f"分类路径锁定 {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 _url_of(self, ident: str) -> str:
        return f"{self.site}/{ident}/"

    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 _episodes(self, page: str) -> List[Tuple[str, str]]:
        """分段 mp4 -> 集数。三级假设: 显式链接 > 段数变量 > Range 探针。"""
        text = self._unescape(page or "")

        explicit: Dict[Tuple[str, int], Dict[int, str]] = {}
        for m in RE_PART_URL.finditer(text):
            url, token, q, part = m.group(1), m.group(2), int(m.group(3)), int(m.group(4))
            if url.startswith("//"):
                url = "https:" + url
            explicit.setdefault((token, q), {})[part] = url

        if explicit:
            token, q = max(explicit, key=lambda k: (len(explicit[k]), k[1]))
            parts = explicit[(token, q)]
            top = max(parts)
            self.log(f"显式分段 token={token} q={q} 段数={top}")
            return [(f"第{i}段", parts.get(i) or f"{MEDIA_HOST}/video/{token}_{q}_part{i}.mp4")
                    for i in range(1, top + 1)]

        tokens = RE_VIDEO_PATH.findall(text) + RE_TOKEN.findall(text)
        if not tokens:
            return []
        token = tokens[0]
        qh = RE_QUALITY.search(text)
        q = int(qh.group(1)) if qh else 1

        counter = RE_PARTS_VAR.search(text)
        if counter:
            n = max(1, min(self.max_parts, int(counter.group(1))))
            self.log(f"段数变量 token={token} n={n}")
            return [(f"第{i}段", f"{MEDIA_HOST}/video/{token}_{q}_part{i}.mp4")
                    for i in range(1, n + 1)]

        eps: List[Tuple[str, str]] = []
        misses = 0
        for i in range(1, min(self.max_parts, 13) + 1):
            url = f"{MEDIA_HOST}/video/{token}_{q}_part{i}.mp4"
            if self._exists(url):
                eps.append((f"第{i}段", url))
                misses = 0
            else:
                misses += 1
                if misses >= 2:
                    break
        self.log(f"探针 token={token} 命中段数={len(eps)}")
        return eps

    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": []}
        page = self.get(self._url_of(ident)) or ""
        meta = self._meta(page)

        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 = self._episodes(page)
        if not eps:
            tok = (RE_VIDEO_PATH.findall(page) or RE_TOKEN.findall(page))
            if tok:
                eps = [("正片", f"{MEDIA_HOST}/video/{tok[0]}_1_part1.mp4")]
        if eps:
            play_url = "#".join(f"{n}${u}" for n, u in eps)
            marks = [f"共{len(eps)}段"]
        else:
            play_url = f"正片${ident}"
            marks = []
        if dur:
            marks.insert(0, dur.group(1))
        if rel:
            marks.append(rel.group(1))

        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,
        }]}

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

    def searchContent(self, key: str, quick: bool = False, pg: Any = 1) -> Dict[str, Any]:
        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.get(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 _unescape(self, text: str) -> str:
        return html_lib.unescape(
            (text or "").replace("\\/", "/").replace("\\u002F", "/").replace("\\u002f", "/"))

    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
        if len(low) > 260:
            s -= 4.0
        return s

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

    def _iframes(self, text: str) -> List[str]:
        out: List[str] = []
        for raw in RE_IFRAME.findall(self._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 _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.pass_gate()
        page_url = self._url_of(ident)
        page = self.get(page_url) or ""
        cands = self._media(page)

        best = self._best(cands)
        if best and best.score >= 60:
            self.log(f"直取 {best}")
            return {"parse": 0, "url": best.url, "header": self.header}

        embeds = self._iframes(page)
        for emb in embeds:
            sub = self.get(emb) or ""
            cands += self._media(sub)
            for emb2 in self._iframes(sub):
                cands += self._media(self.get(emb2) or "")
        for _n, u in self._episodes(page)[:1]:
            cands.append(Hypothesis(46.0, "episode", u))

        best = self._best(cands)
        if best:
            self.log(f"闭环选中 {best}")
            return {"parse": 0, "url": best.url, "header": self.header}

        if embeds:
            return {"parse": 1, "url": embeds[0], "header": self.header, "jx": 1}
        return {"parse": 1, "url": page_url, "header": self.header, "jx": 1}

    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 _selftest(ident: Optional[str] = None) -> int:
    sp = Spider()
    sp.init(json.dumps({"site": DEFAULT_SITE, "timeout": 15}))
    steps: List[Tuple[str, bool, str]] = []

    def run(name: str, fn) -> Any:
        try:
            val = fn()
            ok = bool(val)
        except Exception as exc:  # noqa: BLE001
            val, ok = None, False
            print(f"  ! {name}: {exc}")
        steps.append((name, ok, str(val)[:120]))
        print(f"{'PASS' if ok else 'FAIL'}  {name}")
        return val

    print("== 1 门 ==")
    run("age-gate", lambda: sp.pass_gate())

    print("== 2 分类 ==")
    home = run("homeContent", lambda: sp.homeContent(True))
    classes = (home or {}).get("class", [])
    cats = [c for c in classes if c["type_id"].startswith("c:")]
    studios = [c for c in classes if c["type_id"].startswith("s:")]
    print(f"  分类={len(cats)} 片商={len(studios)}")
    print("  分类样例:", [c["type_name"] for c in cats[:6]])
    if not cats:
        print("  ! 分类取证为空, 命中兜底种子")

    tid = cats[0]["type_id"] if cats else "n"
    print("== 3 列表 ==")
    lst = run("categoryContent", lambda: sp.categoryContent(tid, 1, True, {"sort": "created_at"}))
    items = (lst or {}).get("list", [])
    print(f"  条目数={len(items)} tid={tid}")
    if items:
        print("  样例:", items[0]["vod_name"], "->", items[0]["vod_id"])

    if studios:
        print("== 3b 片商页 ==")
        st = run("studioContent", lambda: sp.categoryContent(studios[0]["type_id"], 1, True, None))
        print("  条目数=", len((st or {}).get("list", [])))

    target = ident or (items[0]["vod_id"] if items else "")
    print("== 4 详情/集数 ==")
    det = run("detailContent", lambda: sp.detailContent([target]) if target else None)
    row = ((det or {}).get("list") or [{}])[0]
    play_url = row.get("vod_play_url", "")
    eps = [x for x in play_url.split("#") if "$" in x]
    print(f"  标题={row.get('vod_name')}")
    print(f"  集数={len(eps)}  备注={row.get('vod_remarks')}")
    for e in eps[:4]:
        print("   ", e.split("$")[0], e.split("$", 1)[1][:90])
    if not eps:
        print("  ! 集数为 0, 集数还原失败")

    print("== 5 搜索 ==")
    run("searchContent", lambda: sp.searchContent("anal", True, 1))

    print("== 6 播放 ==")
    first = eps[0].split("$", 1)[1] if eps else target
    play = run("playerContent", lambda: sp.playerContent("", first) if first else None)
    url = (play or {}).get("url", "")
    print(f"  parse={play.get('parse') if play else '-'}  url={str(url)[:140]}")
    if url:
        print("  可达性探针:", "OK" if sp._exists(str(url)) else "FAIL")

    critical = ("categoryContent", "detailContent", "playerContent")
    ok = (all(s[1] for s in steps if s[0] in critical)
          and len(eps) >= 1 and str(url).startswith("http"))
    print("\n== 结论:", "链路与集数均可用" if ok else "存在断点, 见 FAIL", "==")
    if sp.logs:
        print("\n-- 日志尾部 --")
        print("\n".join(sp.logs[-8:]))
    return 0 if ok else 1


if __name__ == "__main__":
    sys.exit(_selftest(sys.argv[1] if len(sys.argv) > 1 else None))