# -*- coding: utf-8 -*-
# @Author  : 基于梦的 JS 版移植 (修复线路/集数/播放)
# @Desc    : 片吧影院 TVBox Python 爬虫 (pbpb.tv, 苹果CMS V10)
# @dependencies: requests, beautifulsoup4

import re
import time
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
from urllib.parse import urljoin, urlparse
try:
    from bs4 import BeautifulSoup
except Exception:
    # --- embedded BeautifulSoup-compatible shim (pyquery/lxml based) for Yingxia adaptation ---
    # Inserted by py578 adaptation: Yingxia has no bs4; pyquery is available via host html().
    import re as _re_bs4


    class _Bs4Text(str):
        """NavigableString stand-in: str with .parent."""
        def __new__(cls, s, parent=None):
            obj = str.__new__(cls, s)
            obj.parent = parent
            return obj


    class _Bs4Tag:
        def __init__(self, pq_obj):
            self._pq = pq_obj  # PyQuery holding exactly one element (or empty)

        # -- basic --
        @property
        def _el(self):
            els = list(self._pq) if self._pq is not None else []
            return els[0] if els else None

        @property
        def name(self):
            el = self._el
            return el.tag if el is not None else None

        @property
        def attrs(self):
            el = self._el
            if el is None:
                return {}
            out = dict(el.attrib)
            if "class" in out:
                out["class"] = out["class"].split()
            return out

        def get(self, key, default=None):
            el = self._el
            if el is None:
                return default
            v = el.get(key)
            if v is None:
                return default
            if key == "class":
                return v.split()
            return v

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

        def __contains__(self, key):
            el = self._el
            return el is not None and key in el.attrib

        def __bool__(self):
            return self._el is not None

        __nonzero__ = __bool__

        def __repr__(self):
            return "<_Bs4Tag %s>" % (self.name,)

        # -- text --
        def get_text(self, separator="", strip=False):
            el = self._el
            if el is None:
                return ""
            chunks = list(el.itertext())
            if strip:
                chunks = [c.strip() for c in chunks]
                chunks = [c for c in chunks if c]
            return separator.join(chunks)

        @property
        def text(self):
            return self.get_text()

        @property
        def string(self):
            el = self._el
            if el is None:
                return None
            texts = [t for t in el.itertext() if t.strip()]
            return texts[0].strip() if len(texts) == 1 else None

        # -- traversal --
        @property
        def parent(self):
            el = self._el
            if el is None:
                return None
            p = el.getparent()
            if p is None:
                return None
            return _Bs4Tag(self._pq.__class__(p))

        def find_parent(self, name=None, **kw):
            node = self.parent
            while node is not None:
                if name is None or node.name == name:
                    if _bs4_match_attrs(node, kw):
                        return node
                node = node.parent
            return None

        def find_previous_sibling(self, name=None, **kw):
            el = self._el
            if el is None:
                return None
            prev = el.getprevious()
            while prev is not None:
                if isinstance(prev.tag, str):
                    node = _Bs4Tag(self._pq.__class__(prev))
                    if name is None or node.name == name:
                        if _bs4_match_attrs(node, kw):
                            return node
                prev = prev.getprevious()
            return None

        previous_sibling = property(lambda self: self.find_previous_sibling())

        def find_next_sibling(self, name=None, **kw):
            el = self._el
            if el is None:
                return None
            nxt = el.getnext()
            while nxt is not None:
                if isinstance(nxt.tag, str):
                    node = _Bs4Tag(self._pq.__class__(nxt))
                    if name is None or node.name == name:
                        if _bs4_match_attrs(node, kw):
                            return node
                nxt = nxt.getnext()
            return None

        next_sibling = property(lambda self: self.find_next_sibling())

        # -- search --
        def select(self, css):
            if self._pq is None:
                return []
            try:
                found = self._pq(css)
            except Exception:
                return []
            return [_Bs4Tag(item) for item in found.items()]

        def select_one(self, css):
            res = self.select(css)
            return res[0] if res else None

        def find_all(self, name=None, attrs=None, recursive=True, text=None, **kw):
            if text is not None or (attrs and "text" in (attrs or {})):
                pat = text if text is not None else attrs.get("text")
                return self._find_text(pat)
            css = _bs4_css_for(name, attrs, kw)
            if css is None:
                # regex attr filters etc.: gather candidates then filter in python
                base = name if isinstance(name, str) and name else "*"
                cands = self.select(base)
                return [c for c in cands if _bs4_match_attrs(c, _bs4_merge_attrs(attrs, kw))]
            return self.select(css)

        def find(self, name=None, attrs=None, recursive=True, text=None, **kw):
            res = self.find_all(name, attrs, recursive, text, **kw)
            return res[0] if res else None

        def _find_text(self, pat):
            el = self._el
            if el is None:
                return []
            out = []
            for node in el.iter():
                if not isinstance(node.tag, str):
                    continue
                for txt, parent_el in ((node.text, node), (node.tail, node.getparent())):
                    if txt and _bs4_text_match(pat, txt):
                        if parent_el is None:
                            parent_el = node
                        out.append(_Bs4Text(txt, _Bs4Tag(self._pq.__class__(parent_el))))
            return out


    def _bs4_text_match(pat, txt):
        if pat is None:
            return True
        if hasattr(pat, "search"):
            return bool(pat.search(txt))
        return str(pat) in txt


    def _bs4_merge_attrs(attrs, kw):
        merged = {}
        if attrs:
            merged.update(attrs)
        merged.update(kw)
        return merged


    def _bs4_match_attrs(tag, want):
        if not want:
            return True
        for k, v in want.items():
            key = "class" if k == "class_" else k
            have = tag.get(key)
            if have is None:
                return False
            if hasattr(v, "search"):
                if not v.search(" ".join(have) if isinstance(have, list) else str(have)):
                    return False
            elif isinstance(v, (list, tuple)):
                have_list = have if isinstance(have, list) else [have]
                if not all(x in have_list for x in v):
                    return False
            elif key == "class":
                have_list = have if isinstance(have, list) else str(have).split()
                if not all(x in have_list for x in str(v).split()):
                    return False
            elif str(have) != str(v):
                return False
        return True


    def _bs4_css_for(name, attrs, kw):
        """Build CSS selector, or None if python-side filtering is needed."""
        merged = _bs4_merge_attrs(attrs, kw)
        for v in merged.values():
            if hasattr(v, "search"):
                return None
        parts = []
        if isinstance(name, str) and name:
            parts.append(name)
        elif isinstance(name, (list, tuple)):
            return None
        for k, v in merged.items():
            if k == "class_":
                for cls in str(v).split():
                    parts.append("." + cls)
            elif k == "id":
                parts.append("#" + str(v))
            elif isinstance(v, (list, tuple)):
                parts.append('[%s="%s"]' % (k, " ".join(str(x) for x in v)))
            elif v is True:
                parts.append("[%s]" % k)
            else:
                parts.append('[%s="%s"]' % (k, str(v).replace('"', '\\"')))
        return "".join(parts) if parts else "*"


    def _bs4_make(html_text):
        from pyquery import PyQuery as _PQ
        if html_text is None:
            html_text = ""
        if isinstance(html_text, bytes):
            html_text = html_text.decode("utf-8", "ignore")
        return _PQ(str(html_text))


    class BeautifulSoup(_Bs4Tag):
        def __init__(self, markup="", features=None, **kw):
            super().__init__(_bs4_make(markup))
    # --- end embedded BeautifulSoup shim ---
from base.spider import Spider


class Spider(Spider):

    def getName(self):
        return "片吧影院"

    def init(self, extend=""):
        self.base_url = "https://www.pbpb.tv"
        self.ua = (
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
            "AppleWebKit/537.36 (KHTML, like Gecko) "
            "Chrome/144.0.0.0 Safari/537.36"
        )
        self.session = requests.Session()
        self.session.headers.update({
            "User-Agent": self.ua,
            "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
        })

        self._list_cache = {}
        self._list_cache_ttl = 900
        self._detail_cache = {}
        self._detail_cache_ttl = 1800
        self._search_cache = {}
        self._search_cache_ttl = 600

        self.categories = [
            {"id": "1",  "name": "全部"},
            {"id": "5",  "name": "动作片"},
            {"id": "6",  "name": "喜剧片"},
            {"id": "7",  "name": "恐怖片"},
            {"id": "8",  "name": "科幻片"},
            {"id": "9",  "name": "爱情片"},
            {"id": "10", "name": "剧情片"},
            {"id": "11", "name": "战争片"},
            {"id": "13", "name": "国产剧"},
            {"id": "14", "name": "港台剧"},
            {"id": "15", "name": "欧美剧"},
            {"id": "16", "name": "日韩剧"},
            {"id": "17", "name": "海外剧"},
            {"id": "21", "name": "动画电影"},
            {"id": "22", "name": "动画剧集"},
            {"id": "23", "name": "节目秀"},
        ]
        self.page_size = 24

    # ---------------- 基础请求与工具 ----------------

    def _get(self, url, timeout=15, headers=None, is_json=False):
        if not url.startswith("http"):
            url = self.base_url + url
        h = dict(self.session.headers)
        if headers:
            h.update(headers)
        try:
            r = self.session.get(url, headers=h, timeout=timeout, verify=False)
            r.raise_for_status()
            if is_json:
                return r.json()
            r.encoding = r.apparent_encoding or "utf-8"
            return r.text
        except Exception:
            return None

    def _get_cache(self, cache_dict, key, ttl, producer):
        now = time.time()
        if key in cache_dict:
            val, ts = cache_dict[key]
            if now - ts < ttl:
                return val
        val = producer()
        if val:
            cache_dict[key] = (val, now)
        return val

    def _class_url(self, tid, page):
        pg = max(1, int(page or 1))
        if pg <= 1:
            return f"/class/{tid}-----------.html"
        return f"/class/{tid}--------{pg}---.html"

    @staticmethod
    def _extract_id_from_href(href):
        m = re.search(r"/(?:html|v|play|yun)/(\d+)", href or "")
        return m.group(1) if m else ""

    @staticmethod
    def _absolute_url(url):
        if not url:
            return ""
        if url.startswith("http"):
            return url
        return urljoin("https://www.pbpb.tv", url)

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

    def _parse_vod_list(self, html):
        if not html:
            return []
        soup = BeautifulSoup(html, "html.parser")
        result = []
        for el in soup.select(".stui-vodlist__thumb"):
            href = el.get("href", "")
            vid = self._extract_id_from_href(href)
            name = (el.get("title") or "").strip()
            if not name:
                img = el.find("img")
                name = (img.get("alt") if img else "").strip()
            if not vid or not name:
                continue
            pic = el.get("data-original") or ""
            if not pic:
                img = el.find("img")
                if img:
                    pic = img.get("data-original") or img.get("src") or ""
            remarks_el = el.select_one(".pic-text")
            remarks = remarks_el.get_text(strip=True) if remarks_el else ""
            result.append({
                "vod_id": vid,
                "vod_name": name,
                "vod_pic": self._absolute_url(pic),
                "vod_remarks": remarks,
                "vod_year": "",
                "vod_director": "",
                "vod_actor": "",
                "vod_content": "",
            })
        return result

    # ---------------- 首页 ----------------

    def homeContent(self, filter):
        classes = [{"type_id": c["id"], "type_name": c["name"]} for c in self.categories]

        def produce():
            html = self._get(self._class_url("1", 1))
            return self._parse_vod_list(html)[:20]

        videos = self._get_cache(self._list_cache, "home:1", self._list_cache_ttl, produce)
        return {"class": classes, "filters": {}, "list": videos or []}

    def homeVideoContent(self):
        return {"list": []}

    # ---------------- 分类 ----------------

    def categoryContent(self, tid, pg, filter, extend):
        tid = str(tid or "1")
        pg = max(1, int(pg or 1))

        def produce():
            html = self._get(self._class_url(tid, pg))
            return self._parse_vod_list(html)

        videos = self._get_cache(self._list_cache, f"list:{tid}:{pg}", self._list_cache_ttl, produce) or []
        has_more = len(videos) >= self.page_size
        return {
            "page": pg,
            "pagecount": pg + 1 if has_more else pg,
            "limit": self.page_size,
            "total": pg * self.page_size + 1 if has_more else (pg - 1) * self.page_size + len(videos),
            "list": videos,
        }

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

    def _build_vod_from_api(self, item, vod_id):
        """把苹果CMS接口返回的条目转成 TVBox 详情对象"""
        vod = {
            "vod_id": str(vod_id),
            "vod_name": (item.get("vod_name") or "").strip(),
            "vod_pic": self._absolute_url(item.get("vod_pic") or ""),
            "vod_remarks": (item.get("vod_remarks") or "").strip(),
            "vod_content": (item.get("vod_content") or "").strip(),
            "vod_year": str(item.get("vod_year") or ""),
            "vod_director": (item.get("vod_director") or "").strip(),
            "vod_actor": (item.get("vod_actor") or "").strip(),
            "vod_area": (item.get("vod_area") or "").strip(),
        }

        play_from = (item.get("vod_play_from") or "").split("$$$")
        play_url = (item.get("vod_play_url") or "").split("$$$")

        froms, urls = [], []
        for i, group in enumerate(play_url):
            if not group:
                continue
            eps = []
            for ep in group.split("#"):
                if not ep:
                    continue
                if "$" in ep:
                    ep_name, _, ep_url = ep.partition("$")
                else:
                    ep_name, ep_url = ep, ep
                ep_name = ep_name.strip()
                ep_url = ep_url.strip()
                if ep_name and ep_url:
                    eps.append(f"{ep_name}${ep_url}")
            if not eps:
                continue
            src_name = play_from[i].strip() if i < len(play_from) and play_from[i].strip() else f"线路{i + 1}"
            froms.append(src_name)
            urls.append("#".join(eps))

        if froms:
            vod["vod_play_from"] = "$$$".join(froms)
            vod["vod_play_url"] = "$$$".join(urls)
        return vod

    def _fetch_detail_api(self, vod_id):
        """尝试多种苹果CMS接口获取详情"""
        candidates = [
            f"/index.php/ajax/data?mid=1&id={vod_id}",
            f"/api.php/provide/vod/?ac=detail&ids={vod_id}",
            f"/api.php/provide/vod/at/json/?ac=detail&ids={vod_id}",
        ]
        for path in candidates:
            data = self._get(path, headers={
                "Accept": "application/json, text/plain, */*",
                "X-Requested-With": "XMLHttpRequest",
            }, is_json=True)
            if not isinstance(data, dict):
                continue
            # 情况1：直接是视频对象
            if data.get("vod_name") or data.get("vod_play_url"):
                vod = self._build_vod_from_api(data, vod_id)
                if vod.get("vod_play_from"):
                    return vod
            # 情况2：苹果CMS api 规范 {code, list:[...]}
            lst = data.get("list")
            if isinstance(lst, list) and lst:
                vod = self._build_vod_from_api(lst[0], vod_id)
                if vod.get("vod_play_from"):
                    return vod
        return None

    def _parse_detail_html(self, html, vod_id):
        """HTML 兜底解析：兼容多种苹果CMS模板"""
        if not html:
            return None
        soup = BeautifulSoup(html, "html.parser")
        vod = {
            "vod_id": str(vod_id),
            "vod_name": "",
            "vod_pic": "",
            "vod_remarks": "",
            "vod_content": "",
            "vod_year": "",
            "vod_director": "",
            "vod_actor": "",
            "vod_area": "",
        }

        # 标题
        for sel in ["h1.title", "h1", ".stui-content__detail h1", ".vod-title"]:
            el = soup.select_one(sel)
            if el and el.get_text(strip=True):
                vod["vod_name"] = el.get_text(strip=True)
                break

        # 封面
        cover = soup.select_one(
            ".stui-content__detail img, .stui-content__thumb img, .vod-img img, .detail-pic img"
        )
        if cover:
            vod["vod_pic"] = self._absolute_url(
                cover.get("data-original") or cover.get("src") or ""
            )

        # 信息段落
        for p in soup.select(".stui-content__detail p, .content p, .detail-info p, .vod-info p"):
            text = p.get_text(" ", strip=True)
            if "：" not in text:
                continue
            key, _, val = text.partition("：")
            key, val = key.strip(), val.strip()
            if not val:
                continue
            if re.search(r"年份|年代", key):
                vod["vod_year"] = val
            elif re.search(r"导演", key):
                vod["vod_director"] = val
            elif re.search(r"主演|演员", key):
                vod["vod_actor"] = val
            elif re.search(r"地区|地域", key):
                vod["vod_area"] = val
            elif re.search(r"类型|分类", key):
                vod["vod_remarks"] = val
            elif re.search(r"状态", key) and not vod["vod_remarks"]:
                vod["vod_remarks"] = val
            elif re.search(r"剧情|简介|描述", key):
                vod["vod_content"] = val

        # 播放线路（多种选择器兼容）
        froms, urls = [], []
        playlists = soup.select(
            ".stui-content__playlist, .playlist, .content_playlist, "
            "ul.content_playlist, #playlist_1, #playlist_2, #playlist_3, #playlist_4"
        )
        seen_groups = set()
        for idx, pl in enumerate(playlists):
            eps = []
            for a in pl.find_all("a"):
                href = a.get("href", "")
                name = a.get_text(strip=True)
                if not href or not name:
                    continue
                # 相对 href 转成绝对，作为 playId
                full = href if href.startswith("http") else urljoin(self.base_url, href)
                if full in seen_groups:
                    continue
                eps.append(f"{name}${full}")
            if not eps:
                continue
            # 去重
            uniq = []
            seen = set()
            for e in eps:
                if e not in seen:
                    seen.add(e)
                    uniq.append(e)
            if not uniq:
                continue
            seen_groups.update(uniq)
            src_name = self._guess_source_name(pl, idx)
            froms.append(src_name)
            urls.append("#".join(uniq))

        if froms:
            vod["vod_play_from"] = "$$$".join(froms)
            vod["vod_play_url"] = "$$$".join(urls)
        return vod

    @staticmethod
    def _guess_source_name(pl, idx):
        """尝试从播放列表前面的标题猜测线路名"""
        prev = pl.find_previous_sibling()
        loop = 0
        while prev and loop < 5:
            cand = ""
            t = prev.select_one("h3, h4, .title, .stui-vodlist__head, .play-title")
            if t:
                cand = t.get_text(strip=True)
            else:
                cand = prev.get_text(strip=True)
            cand = re.sub(r"\s+", " ", cand or "").strip()
            if cand and len(cand) <= 20 and not re.match(
                r"^(选集|播放|线路|点播|高清|国语|粤语|剧情简介|播放列表)$", cand
            ):
                return cand
            prev = prev.find_previous_sibling()
            loop += 1
        return f"线路{idx + 1}"

    def detailContent(self, array):
        if not array:
            return {"list": []}
        vod_id = str(array[0]).strip()
        if not vod_id:
            return {"list": []}

        def produce():
            vod = self._fetch_detail_api(vod_id)
            if vod and vod.get("vod_play_from"):
                return vod
            html = self._get(f"/html/{vod_id}.html")
            return self._parse_detail_html(html, vod_id)

        vod = self._get_cache(self._detail_cache, f"detail:{vod_id}", self._detail_cache_ttl, produce)
        return {"list": [vod] if vod and vod.get("vod_name") else []}

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

    def searchContent(self, key, quick, pg="1"):
        keyword = (key or "").strip()
        pg = max(1, int(pg or 1))
        if not keyword:
            return {"page": 1, "pagecount": 1, "limit": self.page_size, "total": 0, "list": []}

        def produce():
            url = (
                f"{self.base_url}/index.php/ajax/suggest?"
                f"mid=1&wd={requests.utils.quote(keyword)}"
                f"&limit={self.page_size}&page={pg}"
            )
            return self._get(url, headers={
                "Accept": "application/json, text/plain, */*",
                "X-Requested-With": "XMLHttpRequest",
            }, is_json=True)

        data = self._get_cache(self._search_cache, f"search:{keyword}:{pg}", self._search_cache_ttl, produce)
        raw = data.get("list", []) if isinstance(data, dict) else []
        videos = []
        for item in raw:
            vid = str(item.get("id") or "")
            name = (item.get("name") or "").strip()
            if vid and name:
                videos.append({
                    "vod_id": vid,
                    "vod_name": name,
                    "vod_pic": self._absolute_url(item.get("pic") or ""),
                    "vod_remarks": "",
                    "vod_year": "",
                    "vod_director": "",
                    "vod_actor": "",
                    "vod_content": "",
                })

        total = int(data.get("total", len(videos))) if isinstance(data, dict) else len(videos)
        pagecount = max(1, (total + self.page_size - 1) // self.page_size) if total else 1
        return {
            "page": pg,
            "pagecount": pagecount,
            "limit": self.page_size,
            "total": total,
            "list": videos,
        }

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

    def playerContent(self, flag, id, vipFlags):
        play_id = str(id or "").strip()
        if not play_id:
            return {"parse": 0, "url": "", "header": {}}

        # 情况1：已经是直链，直接播放
        if re.search(r"\.(m3u8|mp4)(\?|$|#)", play_id, re.I):
            return {
                "parse": 0,
                "url": play_id,
                "header": {
                    "User-Agent": self.ua,
                    "Referer": self.base_url + "/",
                },
                "jx": 0,
            }

        # 情况2：是播放页地址，需要从页面里提取真实视频
        try:
            path = urlparse(play_id).path if play_id.startswith("http") else play_id
            html = self._get(path, timeout=20)
            if not html:
                return {"parse": 0, "url": "", "header": {}}

            real_url = ""
            # 直接匹配 m3u8/mp4 的 url
            m = re.search(r'"url"\s*:\s*"([^"]+?\.(?:m3u8|mp4)[^"]*)"', html, re.I)
            if m:
                real_url = m.group(1).replace("\\/", "/")
            # 从 player_aaaa 块提取
            if not real_url:
                block = re.search(r'\{[^{}]*"flag"\s*:\s*"play"[^{}]*\}', html)
                if block:
                    bm = re.search(r'"url"\s*:\s*"([^"]+)"', block.group(0))
                    if bm:
                        real_url = bm.group(1).replace("\\/", "/")
            # 通用：从 m3u8 关键字抓
            if not real_url:
                m = re.search(r'(https?://[^\s"\'<>]+\.(?:m3u8|mp4)[^\s"\'<>]*)', html)
                if m:
                    real_url = m.group(1).replace("\\/", "/")

            if not real_url:
                return {"parse": 0, "url": "", "header": {}}

            return {
                "parse": 0 if re.search(r"\.(m3u8|mp4)", real_url, re.I) else 1,
                "url": real_url,
                "header": {
                    "User-Agent": self.ua,
                    "Referer": self.base_url + "/",
                    "Origin": self.base_url,
                },
                "jx": 0,
            }
        except Exception:
            return {"parse": 0, "url": "", "header": {}}

    def localProxy(self, params):
        return [200, "video/MP2T", "", ""]