import base64
import binascii
import hashlib
import json
import re
import threading
import time

try:
    import requests
except ImportError:  # pragma: no cover
    requests = None

import urllib.parse
import urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

try:
    from base.spider import Spider
except ImportError:  # pragma: no cover
    class Spider(object):
        pass

# ---------------------------------------------------------------- 基础配置
_API_HOSTS = ("https://a82o.j3mqn.com", "https://a64x.gbr2q.com")
_AES_KEY = b"B77A9FF7F323B5404902102257503C2F"   # AES-256
_AES_IV = b"B77A9FF7F323B540"                    # 取前 16 字节
_IMG_KEY = b"46cc793c53dc451b"                   # 封面 AES-128-ECB
_UA = ("Mozilla/5.0 (Linux; Android 14; Redmi K70) AppleWebKit/537.36 "
       "(KHTML, like Gecko) Chrome/120.0 Mobile Safari/537.36")
_SITE = "https://www.ju1m1.com"
_PAGE_LEN = 20
_COVER_PORT_RANGE = (10040, 10060)

# 分类：typeId -> 显示名（去重后取量最大的那个 typeId）
# 由 getList 扫 typeId 1..60 并用 getInfo 取 typeName 得到
_CATS = [
    ("new", "最新上新"),
    ("hot", "最热"),
    ("4", "自拍"), ("6", "偷拍"), ("7", "私拍"), ("8", "在校学生"),
    ("9", "迷奸"), ("10", "角色扮演"), ("11", "潮吹喷水"), ("12", "裸舞诱惑"),
    ("13", "约啪剧情"), ("14", "野外露出"), ("15", "网红女神"), ("17", "高清无码"),
    ("19", "精品素人"), ("20", "中文字幕"), ("21", "熟女OL"), ("22", "剧情综艺"),
    ("23", "欧美"), ("24", "群P"), ("25", "肛交"), ("26", "野战"),
    ("27", "黑白配"), ("28", "重口剧情"), ("29", "动漫"), ("30", "3D"),
    ("31", "同人"), ("32", "制服萝莉"), ("33", "萝莉"), ("36", "AI短剧"),
    ("37", "BBW"),
]

# ---------------------------------------------------------------- 纯 Python AES
_SBOX = [
    0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,
    0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,
    0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
    0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,
    0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,
    0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
    0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,
    0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,
    0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
    0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,
    0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
    0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
    0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,
    0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,
    0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
    0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16,
]
_INV_SBOX = [0] * 256
for _i, _v in enumerate(_SBOX):
    _INV_SBOX[_v] = _i
_RCON = [0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d]


def _xtime(a):
    return ((a << 1) ^ 0x1b) & 0xff if a & 0x80 else (a << 1) & 0xff


def _mul(a, b):
    r = 0
    while b:
        if b & 1:
            r ^= a
        a = _xtime(a)
        b >>= 1
    return r


class _PureAES(object):
    """最小纯 Python AES，支持 128/192/256 位密钥的单块加解密。"""

    def __init__(self, key):
        self.nk = len(key) // 4
        self.nr = self.nk + 6
        w = [list(key[i * 4:(i + 1) * 4]) for i in range(self.nk)]
        for i in range(self.nk, 4 * (self.nr + 1)):
            t = list(w[i - 1])
            if i % self.nk == 0:
                t = t[1:] + t[:1]
                t = [_SBOX[x] for x in t]
                t[0] ^= _RCON[i // self.nk - 1]
            elif self.nk > 6 and i % self.nk == 4:
                t = [_SBOX[x] for x in t]
            w.append([w[i - self.nk][j] ^ t[j] for j in range(4)])
        self.w = w

    def _add_rk(self, s, rnd):
        for c in range(4):
            for r in range(4):
                s[r][c] ^= self.w[rnd * 4 + c][r]

    def _sub(self, s):
        for r in range(4):
            for c in range(4):
                s[r][c] = _SBOX[s[r][c]]

    def _inv_sub(self, s):
        for r in range(4):
            for c in range(4):
                s[r][c] = _INV_SBOX[s[r][c]]

    def _shift(self, s):
        for r in range(1, 4):
            s[r] = s[r][r:] + s[r][:r]

    def _inv_shift(self, s):
        for r in range(1, 4):
            s[r] = s[r][-r:] + s[r][:-r]

    def _mix(self, s):
        for c in range(4):
            a = [s[r][c] for r in range(4)]
            s[0][c] = _mul(a[0], 2) ^ _mul(a[1], 3) ^ a[2] ^ a[3]
            s[1][c] = a[0] ^ _mul(a[1], 2) ^ _mul(a[2], 3) ^ a[3]
            s[2][c] = a[0] ^ a[1] ^ _mul(a[2], 2) ^ _mul(a[3], 3)
            s[3][c] = _mul(a[0], 3) ^ a[1] ^ a[2] ^ _mul(a[3], 2)

    def _inv_mix(self, s):
        for c in range(4):
            a = [s[r][c] for r in range(4)]
            s[0][c] = _mul(a[0], 14) ^ _mul(a[1], 11) ^ _mul(a[2], 13) ^ _mul(a[3], 9)
            s[1][c] = _mul(a[0], 9) ^ _mul(a[1], 14) ^ _mul(a[2], 11) ^ _mul(a[3], 13)
            s[2][c] = _mul(a[0], 13) ^ _mul(a[1], 9) ^ _mul(a[2], 14) ^ _mul(a[3], 11)
            s[3][c] = _mul(a[0], 11) ^ _mul(a[1], 13) ^ _mul(a[2], 9) ^ _mul(a[3], 14)

    def encrypt_block(self, blk):
        s = [[blk[4 * c + r] for c in range(4)] for r in range(4)]
        self._add_rk(s, 0)
        for rnd in range(1, self.nr):
            self._sub(s)
            self._shift(s)
            self._mix(s)
            self._add_rk(s, rnd)
        self._sub(s)
        self._shift(s)
        self._add_rk(s, self.nr)
        return bytes(s[r][c] for c in range(4) for r in range(4))

    def decrypt_block(self, blk):
        s = [[blk[4 * c + r] for c in range(4)] for r in range(4)]
        self._add_rk(s, self.nr)
        for rnd in range(self.nr - 1, 0, -1):
            self._inv_shift(s)
            self._inv_sub(s)
            self._add_rk(s, rnd)
            self._inv_mix(s)
        self._inv_shift(s)
        self._inv_sub(s)
        self._add_rk(s, 0)
        return bytes(s[r][c] for c in range(4) for r in range(4))


def _pkcs7_pad(data):
    n = 16 - len(data) % 16
    return data + bytes([n]) * n


def _strip_pad(data):
    """先试 PKCS7，不行就去尾部 0 填充（列表封面用 0 填充）。"""
    if not data:
        return data
    n = data[-1]
    if 1 <= n <= 16 and data[-n:] == bytes([n]) * n:
        return data[:-n]
    return data.rstrip(b"\x00")


# 有 pycryptodome 就用它（快），没有就用纯 Python（OK影视里走这条）
try:
    from Crypto.Cipher import AES as _CryptoAES
    from Crypto.Util.Padding import pad as _crypto_pad

    def _aes_cbc_encrypt(key, iv, data):
        c = _CryptoAES.new(key, _CryptoAES.MODE_CBC, iv)
        return c.encrypt(_crypto_pad(data, 16))

    def _aes_ecb_decrypt(key, data):
        c = _CryptoAES.new(key, _CryptoAES.MODE_ECB)
        return c.decrypt(data)

    _USE_CRYPTO = True
except Exception:  # pragma: no cover
    def _aes_cbc_encrypt(key, iv, data):
        a = _PureAES(key)
        out = b""
        prev = iv
        data = _pkcs7_pad(data)
        for i in range(0, len(data), 16):
            blk = bytes(x ^ y for x, y in zip(data[i:i + 16], prev))
            ct = a.encrypt_block(blk)
            out += ct
            prev = ct
        return out

    def _aes_ecb_decrypt(key, data):
        a = _PureAES(key)
        out = b""
        for i in range(0, len(data), 16):
            out += a.decrypt_block(data[i:i + 16])
        return out

    _USE_CRYPTO = False


def _aes_b64(plain):
    """站内 enc()：AES-256-CBC + PKCS7，返回 Base64 密文。"""
    if isinstance(plain, str):
        plain = plain.encode("utf-8")
    return base64.b64encode(_aes_cbc_encrypt(_AES_KEY, _AES_IV, plain)).decode("ascii")


def _decrypt_cover_bytes(raw):
    """把 .aes 封面文件解成 JPEG 字节；失败返回 None。"""
    if not raw:
        return None
    # 文件内容本身是 Base64 文本
    try:
        text = raw.decode("ascii").strip()
        text += "=" * (-len(text) % 4)
        data = base64.b64decode(text)
    except Exception:
        data = raw
    if len(data) % 16:
        return None
    try:
        pt = _strip_pad(_aes_ecb_decrypt(_IMG_KEY, data))
    except Exception:
        return None
    # 解出来是 data:image/...;base64,... 或直接就是 JPEG
    if pt[:2] == b"\xff\xd8":
        return pt
    try:
        s = pt.decode("utf-8", "ignore")
    except Exception:
        return None
    if s.startswith("data:image"):
        _, _, b64 = s.partition(",")
        try:
            img = base64.b64decode(b64.strip())
        except Exception:
            return None
        return img if img[:2] == b"\xff\xd8" else img
    return None


# ---------------------------------------------------------------- 封面本机服务
_COVER_CACHE = {}
_COVER_LOCK = threading.Lock()
_COVER_STATE = {"port": 0, "server": None}


def _http_get_bytes(url, timeout=25):
    """取一个远端地址的字节；requests 优先，urllib 兜底。"""
    if requests is not None:
        try:
            r = requests.get(url, headers={"User-Agent": _UA}, timeout=timeout)
            if r.status_code == 200:
                return r.content
            return None
        except Exception:
            pass
    try:
        req = urllib.request.Request(url, headers={"User-Agent": _UA})
        with urllib.request.urlopen(req, timeout=timeout) as resp:
            return resp.read()
    except Exception:
        return None


def _abs_url(base, ref):
    return urllib.parse.urljoin(base, ref)


class _LocalHandler(BaseHTTPRequestHandler):
    """本机服务：/cover 解密封面；/play.m3u8、/seg、/key 转播 HLS。"""

    def log_message(self, *args):  # 静默
        pass

    def _fail(self, code, body=b""):
        try:
            self.send_response(code)
            self.send_header("Content-Type", "text/plain; charset=utf-8")
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            if body:
                self.wfile.write(body)
        except Exception:
            pass

    def _send_bytes(self, body, ctype):
        try:
            self.send_response(200)
            self.send_header("Content-Type", ctype)
            self.send_header("Cache-Control", "no-cache")
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            self.wfile.write(body)
        except Exception:
            pass

    def _serve_cover(self, qs):
        url = (qs.get("u") or [""])[0]
        if not url:
            self._fail(400, b"missing u")
            return
        img = _COVER_CACHE.get(url)
        if img is None:
            try:
                img = _fetch_cover(url)
            except Exception:
                img = None
            if img:
                with _COVER_LOCK:
                    if len(_COVER_CACHE) > 200:
                        _COVER_CACHE.clear()
                    _COVER_CACHE[url] = img
        if not img:
            self._fail(502, b"cover failed")
            return
        self._send_bytes(img, "image/jpeg")

    def _serve_play(self, qs):
        """/play.m3u8?u=<master 地址>：取 master→取 variant→重写为本机地址后返回。"""
        master = (qs.get("u") or [""])[0]
        if not master:
            self._fail(400, b"missing u")
            return
        port = _COVER_STATE["port"]
        base_local = "http://127.0.0.1:%d" % port
        mtext = _http_get_bytes(master)
        if not mtext:
            self._fail(502, b"master failed")
            return
        try:
            mtext = mtext.decode("utf-8", "ignore")
        except Exception:
            self._fail(502, b"master decode failed")
            return
        # 找 variant 行
        variant_ref = None
        for line in mtext.splitlines():
            line = line.strip()
            if line and not line.startswith("#") and ".m3u8" in line:
                variant_ref = line
                break
        if not variant_ref:
            # master 本身就是单级列表，直接重写它
            vtext, vbase = mtext, master
        else:
            vurl = _abs_url(master, variant_ref)
            vraw = _http_get_bytes(vurl)
            if not vraw:
                self._fail(502, b"variant failed")
                return
            vtext = vraw.decode("utf-8", "ignore")
            vbase = vurl
        out = []
        for line in vtext.splitlines():
            s = line.strip()
            if s.startswith("#EXT-X-KEY"):
                m = re.search(r'URI="([^"]+)"', s)
                if m:
                    kurl = _abs_url(vbase, m.group(1))
                    ku = urllib.parse.quote(kurl, safe="")
                    s = s[:m.start(1)] + base_local + "/key?u=" + ku + s[m.end(1):]
                out.append(s)
            elif s and not s.startswith("#"):
                # 分片：相对路径→绝对地址，再走本机中转
                seg_url = _abs_url(vbase, s)
                su = urllib.parse.quote(seg_url, safe="")
                out.append(base_local + "/seg?u=" + su)
            else:
                out.append(line)
        body = ("\n".join(out) + "\n").encode("utf-8")
        self._send_bytes(body, "application/vnd.apple.mpegurl")

    def _serve_seg(self, qs):
        url = (qs.get("u") or [""])[0]
        if not url:
            self._fail(400, b"missing u")
            return
        data = _http_get_bytes(url, timeout=30)
        if data is None:
            self._fail(502, b"seg failed")
            return
        self._send_bytes(data, "video/MP2T")

    def _serve_key(self, qs):
        url = (qs.get("u") or [""])[0]
        if not url:
            self._fail(400, b"missing u")
            return
        data = _http_get_bytes(url, timeout=15)
        if data is None:
            self._fail(502, b"key failed")
            return
        self._send_bytes(data, "application/octet-stream")

    def do_GET(self):
        parsed = urllib.parse.urlparse(self.path)
        qs = urllib.parse.parse_qs(parsed.query)
        if parsed.path == "/cover":
            self._serve_cover(qs)
        elif parsed.path == "/play.m3u8":
            self._serve_play(qs)
        elif parsed.path == "/seg":
            self._serve_seg(qs)
        elif parsed.path == "/key":
            self._serve_key(qs)
        else:
            self._fail(404, b"not found")


# 旧名保留，供 _start_cover_server 引用
_CoverHandler = _LocalHandler


def _fetch_cover(url):
    """下载 .aes 并解密成 JPEG。"""
    raw = _http_get_bytes(url, timeout=20)
    if raw is None:
        try:
            req = urllib.request.Request(url, headers={"User-Agent": _UA, "Referer": _SITE + "/home"})
            with urllib.request.urlopen(req, timeout=20) as resp:
                raw = resp.read()
        except Exception:
            raw = None
    return _decrypt_cover_bytes(raw)


def _start_cover_server():
    with _COVER_LOCK:
        if _COVER_STATE["port"]:
            return int(_COVER_STATE["port"])
        for port in range(_COVER_PORT_RANGE[0], _COVER_PORT_RANGE[1]):
            try:
                server = ThreadingHTTPServer(("127.0.0.1", port), _CoverHandler)
            except OSError:
                continue
            server.daemon_threads = True
            threading.Thread(target=server.serve_forever, daemon=True).start()
            _COVER_STATE["port"] = port
            _COVER_STATE["server"] = server
            return port
    return 0


# ---------------------------------------------------------------- 工具
def _fmt_len(sec):
    try:
        sec = int(sec)
    except Exception:
        return ""
    if sec <= 0:
        return ""
    m, s = divmod(sec, 60)
    h, m = divmod(m, 60)
    return ("%d:%02d:%02d" % (h, m, s)) if h else ("%02d:%02d" % (m, s))


def _fmt_num(n):
    try:
        n = int(n)
    except Exception:
        return ""
    if n >= 10000:
        return "%.1f万" % (n / 10000.0)
    return str(n)


class Spider(Spider):
    def getName(self):
        return "含羞草"

    def init(self, extend=""):
        self._sess = None
        if requests is not None:
            try:
                self._sess = requests.Session()
            except Exception:
                self._sess = None
        self._host_idx = 0
        self._cover_port = _start_cover_server()
        return {"code": 0, "msg": "init ok"}

    # ---- 网络 ----
    def _headers(self, referer):
        return {
            "User-Agent": _UA,
            "Content-Type": "application/json",
            "Origin": _SITE,
            "Referer": referer,
            "source": "4",
            "Did": "1",
        }

    def _post(self, path, body, referer):
        """加密 POST，两个网关轮换重试；返回解析后的 JSON dict，失败返回 {}。"""
        payload = {
            "endata": _aes_b64(json.dumps(body, separators=(",", ":"), ensure_ascii=False)),
            "ents": _aes_b64(str(int(time.time()) + 60 * (-480))),
        }
        data = json.dumps(payload).encode("utf-8")
        last_err = None
        for _ in range(2):
            base = _API_HOSTS[self._host_idx % len(_API_HOSTS)]
            self._host_idx += 1
            url = base + path
            try:
                if self._sess is not None:
                    r = self._sess.post(url, json=payload,
                                        headers=self._headers(referer), timeout=20)
                    if r.status_code == 200:
                        return r.json()
                    last_err = "http %s" % r.status_code
                else:
                    req = urllib.request.Request(
                        url, data=data, headers=self._headers(referer), method="POST")
                    with urllib.request.urlopen(req, timeout=20) as resp:
                        return json.loads(resp.read().decode("utf-8", "ignore"))
            except Exception as e:
                last_err = str(e)
                continue
        return {}

    # ---- 封面 ----
    def _pic(self, aes_url):
        """把 .aes 封面地址换成本机解密服务地址；服务起不来时返回空。"""
        if not aes_url:
            return ""
        if self._cover_port:
            u = urllib.parse.quote(aes_url, safe="")
            return "http://127.0.0.1:%d/cover?u=%s" % (self._cover_port, u)
        return ""

    # ---- 列表项 ----
    def _vod(self, v):
        vid = v.get("id")
        name = (v.get("name") or "").strip()
        if not vid or not name:
            return None
        remarks = _fmt_len(v.get("length"))
        see = _fmt_num(v.get("seeCount"))
        if see:
            remarks = (remarks + " · " + see + "次") if remarks else (see + "次")
        return {
            "vod_id": str(vid),
            "vod_name": name,
            "vod_pic": self._pic(v.get("coverImgUrl") or ""),
            "vod_remarks": remarks,
        }

    def _list(self, items):
        out = []
        seen = set()
        for v in items or []:
            item = self._vod(v)
            if item and item["vod_id"] not in seen:
                seen.add(item["vod_id"])
                out.append(item)
        return out

    # ---- TVBox 接口 ----
    def homeContent(self, filter):
        classes = [{"type_id": tid, "type_name": name} for tid, name in _CATS]
        # 首页 list 留空：避免播放器把首页内容另起一个“推荐”页，和分类重复
        return {"class": classes, "list": [], "filters": {}}

    def homeVideoContent(self):
        # 同上，不给播放器自带的推荐页留内容
        return {"list": []}

    def categoryContent(self, tid, pg, filter, extend):
        try:
            pg = int(pg)
        except Exception:
            pg = 1
        if pg < 1:
            pg = 1
        body = {"page": pg, "length": _PAGE_LEN}
        if tid == "new":
            body["orderType"] = 1
        elif tid == "hot":
            body["orderType"] = 2
        else:
            try:
                body["typeId"] = int(tid)
            except Exception:
                body["typeId"] = 0
            body["orderType"] = 1
        d = self._post("/videos/getList", body, _SITE + "/home")
        data = d.get("data") or {}
        total = data.get("count") or 0
        try:
            total = int(total)
        except Exception:
            total = 0
        pagecount = (total + _PAGE_LEN - 1) // _PAGE_LEN if total else 1
        if pagecount > 500:
            pagecount = 500
        return {
            "list": self._list(data.get("list") or []),
            "page": pg,
            "pagecount": pagecount,
            "limit": 90,
            "total": total,
        }

    def detailContent(self, ids):
        try:
            vid = int(str(ids[0]).strip())
        except Exception:
            return {"list": []}
        d = self._post("/videos/getInfo", {"videoId": vid},
                       _SITE + "/play/video/%d" % vid)
        data = d.get("data") or {}
        info = data.get("info") or {}
        if not info:
            return {"list": []}
        name = (info.get("name") or "").strip()
        tags = (info.get("tags") or "").strip()
        type_name = (info.get("typeName") or "").strip()
        length = _fmt_len(info.get("length"))
        remarks = []
        if length:
            remarks.append("时长 " + length)
        see = _fmt_num(info.get("seeCount"))
        if see:
            remarks.append("播放 " + see)
        like = _fmt_num(info.get("likeCount"))
        if like:
            remarks.append("点赞 " + like)
        if info.get("isVip"):
            remarks.append("VIP")
        elif info.get("point"):
            remarks.append("付费 %s钻" % info.get("point"))
        vod = {
            "vod_id": str(vid),
            "vod_name": name,
            "vod_pic": self._pic(info.get("coverImgUrl") or info.get("coverImgUrlVertical") or ""),
            "type_name": type_name,
            "vod_tag": tags,
            "vod_remarks": " · ".join(remarks),
            "vod_actor": "",
            "vod_director": "",
            "vod_content": (info.get("description") or "").strip(),
            "vod_play_from": "含羞草",
            "vod_play_url": "播放$%d" % vid,
        }
        return {"list": [vod]}

    def _play_url(self, cdn_url):
        """把 CDN 的 m3u8 换成本机转播地址，播放器只跟本机打交道，
        避免它直接解析带长签名的 master 列表时报 Manifest Malformed。"""
        if not cdn_url or not cdn_url.startswith("http"):
            return ""
        if self._cover_port:
            u = urllib.parse.quote(cdn_url, safe="")
            return "http://127.0.0.1:%d/play.m3u8?u=%s" % (self._cover_port, u)
        return cdn_url

    def playerContent(self, flag, id, vipFlags):
        try:
            vid = int(str(id).strip().split("$")[-1])
        except Exception:
            return {"parse": 1, "url": "", "header": ""}
        referer = _SITE + "/play/video/%d" % vid
        info_d = self._post("/videos/getInfo", {"videoId": vid}, referer)
        info_data = info_d.get("data") or {}
        can_play = info_data.get("canPlay")
        can_pre = info_data.get("canPrePlay")
        # 免费 / 限时免费：直接拿全片地址
        if can_play:
            d = self._post("/videos/v2/getUrl", {"videoId": vid}, referer)
            url = ((d.get("data") or {}).get("url") or "").strip()
            if url.startswith("http"):
                return {"parse": 0, "url": self._play_url(url), "header": ""}
        # VIP / 付费：试看地址改范围拿全片
        if can_pre:
            d = self._post("/videos/getPreUrl", {"videoId": vid}, referer)
            url = ((d.get("data") or {}).get("url") or "").strip()
            if url.startswith("http"):
                full = re.sub(r"start=\d+&end=\d+&", "start=0&end=9999&", url)
                if full != url:
                    return {"parse": 0, "url": self._play_url(full), "header": ""}
                return {"parse": 0, "url": self._play_url(url), "header": ""}
        # 兜底：仍可免费试看的直接给试看地址；否则打开网页
        if can_pre:
            d = self._post("/videos/getPreUrl", {"videoId": vid}, referer)
            url = ((d.get("data") or {}).get("url") or "").strip()
            if url.startswith("http"):
                return {"parse": 0, "url": self._play_url(url), "header": ""}
        return {"parse": 1, "url": referer, "header": ""}

    def searchContent(self, key, quick, pg):
        try:
            pg = int(pg)
        except Exception:
            pg = 1
        if pg < 1:
            pg = 1
        key = (key or "").strip()
        if not key:
            return {"list": []}
        d = self._post("/base/globalSearch",
                       {"key": key, "page": pg, "length": _PAGE_LEN, "type": 1},
                       _SITE + "/home")
        data = d.get("data") or {}
        total = data.get("count") or 0
        try:
            total = int(total)
        except Exception:
            total = 0
        pagecount = (total + _PAGE_LEN - 1) // _PAGE_LEN if total else 1
        return {
            "list": self._list(data.get("infos") or []),
            "page": pg,
            "pagecount": pagecount,
            "limit": 90,
            "total": total,
        }

    def isVideoFormat(self, url):
        return False

    def manualVideoCheck(self):
        return False

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


# ---------------------------------------------------------------- 本地自测
if __name__ == "__main__":
    import sys
    sys.path.insert(0, "/tmp/ghgbases")
    sp = Spider()
    print("init:", sp.init())
    print("crypto:", "pycryptodome" if _USE_CRYPTO else "pure-python")
    print("cover port:", sp._cover_port)
    hc = sp.homeContent(None)
    print("home classes:", len(hc["class"]), "| list:", len(hc["list"]))
    cat = sp.categoryContent("new", 1, None, None)
    print("最新上新 p1:", len(cat["list"]), "条 | pagecount:", cat["pagecount"])
    if cat["list"]:
        print("  首条:", cat["list"][0]["vod_name"][:30], "|", cat["list"][0]["vod_remarks"])
        vid = cat["list"][0]["vod_id"]
        det = sp.detailContent([vid])
        print("详情:", det["list"][0]["vod_name"][:30] if det["list"] else "空",
              "|", det["list"][0]["vod_remarks"] if det["list"] else "")
        pc = sp.playerContent("", vid, None)
        print("播放 parse:", pc.get("parse"), "| url 前80:", (pc.get("url") or "")[:80])
        # 本机转播的 m3u8 应能直接取回且为完整全片
        if pc.get("url", "").startswith("http://127.0.0.1"):
            import urllib.request as _u2
            import re as _re
            try:
                with _u2.urlopen(pc["url"], timeout=30) as resp:
                    pl = resp.read().decode("utf-8", "ignore")
                infs = _re.findall(r"#EXTINF:([\d.]+)", pl)
                print("本机转播 m3u8:", resp.status, "| 段数:", len(infs),
                      "| 总时长:", round(sum(float(x) for x in infs), 1), "秒",
                      "| 含本机分片:", "/seg?u=" in pl, "| 含本机key:", "/key?u=" in pl)
                # 取第一个本机分片
                m = _re.search(r"(http://127\.0\.0\.1:\d+/seg\?u=[^\s]+)", pl)
                if m:
                    with _u2.urlopen(m.group(1), timeout=30) as resp2:
                        seg = resp2.read()
                    print("本机分片:", resp2.status, len(seg), "bytes |", resp2.headers.get("Content-Type"))
            except Exception as e:
                print("本机转播失败:", type(e).__name__, str(e)[:100])
    cat2 = sp.categoryContent("36", 1, None, None)
    print("AI短剧 p1:", len(cat2["list"]), "条 | total:", cat2.get("total"))
    sr = sp.searchContent("AI", False, 1)
    print("搜索 AI:", len(sr["list"]), "条 | total:", sr.get("total"))
    # 封面本机服务
    if cat["list"] and sp._cover_port:
        import urllib.request as _u
        pic = cat["list"][0]["vod_pic"]
        print("封面地址:", pic[:80])
        try:
            with _u.urlopen(pic, timeout=25) as resp:
                body = resp.read()
            print("封面服务:", resp.status, len(body), "bytes |",
                  resp.headers.get("Content-Type"), "| JPEG头:", body[:2] == b"\xff\xd8")
        except Exception as e:
            print("封面服务失败:", type(e).__name__, str(e)[:100])
