import base64
import json
import re
import threading
import time
import urllib.parse
import urllib.request

try:
    import http.client
except Exception:  # pragma: no cover
    http = None

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

try:
    from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
except Exception:  # pragma: no cover
    BaseHTTPRequestHandler = None
    ThreadingHTTPServer = None

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

_API = "https://api.yueseglobal.com"
_SITE = "https://ys.24fwwn44.icu"
_LANDING_URL = "https://yuese01.cc/"  # 最新地址中转页，失效时从这里提新地址，不用自己改新地址。
_UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
       "(KHTML, like Gecko) Chrome/120.0 Safari/537.36")
_API_KEY = b"LqzCOd16vnYhOHTz"      # 接口响应 AES-128-CBC，key = iv
_IMG_KEY = b"yuese!niubia!666"     # 封面 .aes 的 AES-128-CBC key，IV = 文件前 16 字节
_PAGE_LEN = 20
_COVER_PORT_RANGE = (10040, 10060)


# ---------------------------------------------------------------- 纯 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


def _mul_table(b):
    t = [0] * 256
    for a in range(256):
        t[a] = _mul(a, b)
    return t


_MUL2 = _mul_table(2)
_MUL3 = _mul_table(3)
_MUL9 = _mul_table(9)
_MUL11 = _mul_table(11)
_MUL13 = _mul_table(13)
_MUL14 = _mul_table(14)


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] = _MUL2[a[0]] ^ _MUL3[a[1]] ^ a[2] ^ a[3]
            s[1][c] = a[0] ^ _MUL2[a[1]] ^ _MUL3[a[2]] ^ a[3]
            s[2][c] = a[0] ^ a[1] ^ _MUL2[a[2]] ^ _MUL3[a[3]]
            s[3][c] = _MUL3[a[0]] ^ a[1] ^ a[2] ^ _MUL2[a[3]]

    def _inv_mix(self, s):
        for c in range(4):
            a = [s[r][c] for r in range(4)]
            s[0][c] = _MUL14[a[0]] ^ _MUL11[a[1]] ^ _MUL13[a[2]] ^ _MUL9[a[3]]
            s[1][c] = _MUL9[a[0]] ^ _MUL14[a[1]] ^ _MUL11[a[2]] ^ _MUL13[a[3]]
            s[2][c] = _MUL13[a[0]] ^ _MUL9[a[1]] ^ _MUL14[a[2]] ^ _MUL11[a[3]]
            s[3][c] = _MUL11[a[0]] ^ _MUL13[a[1]] ^ _MUL9[a[2]] ^ _MUL14[a[3]]

    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):
    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")


def _aes_cbc_decrypt(key, iv, data):
    """AES-CBC 解密（纯 Python），data 长度须为 16 的倍数。"""
    a = _PureAES(key)
    out = b""
    prev = iv
    for i in range(0, len(data), 16):
        blk = data[i:i + 16]
        if len(blk) < 16:
            break
        pt = a.decrypt_block(blk)
        out += bytes(x ^ y for x, y in zip(pt, prev))
        prev = blk
    return _strip_pad(out)


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 _ys_decrypt(content):
    """解密接口返回的 content：{encrypt:1, encryptData} → 真实对象；否则原样。"""
    if isinstance(content, dict) and content.get("encrypt") == 1 and content.get("encryptData"):
        try:
            raw = base64.b64decode(content["encryptData"])
            pt = _aes_cbc_decrypt(_API_KEY, _API_KEY, raw)
            return json.loads(pt.decode("utf-8"))
        except Exception:
            return None
    return content


def _decrypt_cover_bytes(raw):
    """封面 .aes：前 16 字节 IV，余下 AES-128-CBC(key=yuese!niubia!666) → JPEG。"""
    if not raw or len(raw) <= 16:
        return None
    try:
        pt = _aes_cbc_decrypt(_IMG_KEY, raw[:16], raw[16:])
    except Exception:
        return None
    if not pt or pt[:2] != b"\xff\xd8":
        return None
    return pt


# ---------------------------------------------------------------- 网络
try:
    _IncompleteRead = http.client.IncompleteRead
except Exception:  # pragma: no cover
    class _IncompleteRead(Exception):
        pass

_SESSION = None


def _session():
    global _SESSION
    if _SESSION is None and requests is not None:
        try:
            _SESSION = requests.Session()
            _SESSION.headers.update({"User-Agent": _UA})
        except Exception:
            _SESSION = None
    return _SESSION


def _http_get_bytes(url, timeout=25):
    try:
        s = _session()
        if s is not None:
            r = s.get(url, timeout=timeout)
            if r.status_code == 200:
                return r.content
            return None
        if requests is not None:
            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:
            try:
                return resp.read()
            except _IncompleteRead as e:
                # 分块响应被截断：用已读到的部分
                return e.partial or None
    except Exception:
        return None


def _api_post(path, params):
    url = _API + "/" + path
    data = json.dumps(params or {}).encode("utf-8")
    raw = None
    try:
        s = _session()
        if s is not None:
            r = s.post(url, data=data,
                       headers={"Content-Type": "application/json"},
                       timeout=8)
            if r.status_code == 200:
                raw = r.content
        elif requests is not None:
            r = requests.post(url, data=data,
                              headers={"User-Agent": _UA,
                                       "Content-Type": "application/json"},
                              timeout=8)
            if r.status_code == 200:
                raw = r.content
        else:
            req = urllib.request.Request(
                url, data=data,
                headers={"User-Agent": _UA, "Content-Type": "application/json"},
                method="POST")
            with urllib.request.urlopen(req, timeout=8) as resp:
                try:
                    raw = resp.read()
                except _IncompleteRead as e:
                    raw = e.partial or None
    except Exception:
        return {}
    if raw is None:
        return {}
    try:
        d = json.loads(raw.decode("utf-8", "ignore"))
    except Exception:
        return {}
    content = _ys_decrypt(d.get("content"))
    if content is None:
        return {}
    # 有的接口解密后还是 {error, content} 双层
    if isinstance(content, dict) and "content" in content and "error" in content:
        return content.get("content") or {}
    return content


def _site_reachable(url, timeout=3):
    _YUESE = b"\xe6\x9c\x88\xe8\x89\xb2"  # 月色 UTF-8
    try:
        if requests is not None:
            r = requests.get(url, headers={"User-Agent": _UA}, timeout=timeout)
            return r.status_code == 200 and (_YUESE in r.content or b"flutter" in r.content.lower())
        req = urllib.request.Request(url, headers={"User-Agent": _UA})
        with urllib.request.urlopen(req, timeout=timeout) as resp:
            if resp.status != 200:
                return False
            b = resp.read(8192)
            return _YUESE in b or b"flutter" in b.lower()
    except Exception:
        return False


def _resolve_latest_site():

    try:
        raw = _http_get_bytes(_LANDING_URL, timeout=5)
        if not raw:
            return None
        html = raw.decode("utf-8", "ignore")
        m = re.search(r"window\.location\.href\s*=\s*['\"](https?://[^'\"]+)['\"]", html)
        if m:
            raw = _http_get_bytes(m.group(1), timeout=5)
            if not raw:
                return None
            html = raw.decode("utf-8", "ignore")
        m = re.search(r"domainsH5Codes\s*=\s*\[\[([0-9,\s]+)\]", html)
        if m:
            codes = [int(x) for x in m.group(1).split(",") if x.strip().isdigit()]
            if codes:
                return "".join(chr(c) for c in codes).rstrip("/")

        m = re.search(r"最新地址[^<]{0,80}(https?://[a-zA-Z0-9.-]+)", html)
        if m:
            return m.group(1).rstrip("/")
    except Exception:
        pass
    return None


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


# ---------------------------------------------------------------- 本机服务：解密封面 + 转播 HLS
_COVER_CACHE = {}
_COVER_LOCK = threading.Lock()
_COVER_STATE = {"port": 0, "server": None}


def _fetch_cover(url):
    raw = _http_get_bytes(url, timeout=20)
    return _decrypt_cover_bytes(raw)


if BaseHTTPRequestHandler is not None:
    _HandlerBase = BaseHTTPRequestHandler
else:
    # http.server 不可用时也别让整个模块导入失败：给个空基类占位，
    # _start_cover_server 会直接返回 0，封面和转播只是回退。
    class _HandlerBase(object):
        pass


class _LocalHandler(_HandlerBase):
    """本机服务：/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
        best_ref, best_bw = None, -1
        lines = mtext.splitlines()
        for i, line in enumerate(lines):
            s = line.strip()
            if s.startswith("#EXT-X-STREAM-INF"):
                m = re.search(r"BANDWIDTH=(\d+)", s)
                bw = int(m.group(1)) if m else 0
                for j in range(i + 1, len(lines)):
                    ref = lines[j].strip()
                    if ref and not ref.startswith("#"):
                        if bw >= best_bw:
                            best_bw, best_ref = bw, ref
                        break
        if best_ref:
            vurl = _abs_url(master, best_ref)
            vraw = _http_get_bytes(vurl)
            if not vraw:
                self._fail(502, b"variant failed")
                return
            vtext = vraw.decode("utf-8", "ignore")
            vbase = vurl
        else:
            vtext, vbase = mtext, master
        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")


def _start_cover_server():
    if BaseHTTPRequestHandler is None or ThreadingHTTPServer is None:
        return 0
    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), _LocalHandler)
            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 <= 0:
        return ""
    if n >= 10000:
        return "%.1f万" % (n / 10000.0)
    return str(n)


# ---------------------------------------------------------------- 分类
_CATS = [
    ("all", "最新视频"),
    ("1", "国产视频"),
    ("16", "欧美情色"),
    ("48", "成人动漫"),
    ("22", "卡通动漫"),
    ("55", "国产传媒"),
    ("66", "国产主播"),
    ("65", "自拍偷拍"),
    ("30", "性情社"),
    ("64", "吃瓜黑料"),
    ("15", "日韩大片"),
    ("74", "AI剧情"),
    ("51", "家庭乱伦"),
    ("59", "直播裸聊"),
    ("2", "麻豆传媒"),
    ("62", "酒店探花"),
    ("5", "国产自拍"),
    ("67", "反差母狗"),
    ("49", "AI换脸"),
    ("52", "伦理影片"),
    ("57", "撸管必看"),
    ("68", "SM调教"),
    ("20", "强奸乱伦"),
    ("73", "短剧"),
    ("24", "黑料热点"),
    ("69", "学生空姐"),
    ("58", "偷情少妇"),
    ("61", "野战车震"),
    ("19", "国产传媒换脸"),
    ("23", "乱伦剧情"),
    ("7", "中文字幕"),
    ("26", "包罗万象"),
    ("4", "国产偷拍"),
    ("63", "百合女同"),
    ("60", "AV明星"),
    ("85", "大神精选"),
    ("56", "日韩无码"),
    ("18", "原创热点"),
    ("17", "日本无码"),
    ("47", "AV解说"),
    ("54", "欧美劲爆"),
    ("70", "SM重味"),
    ("42", "群P换妻"),
    ("36", "换脸"),
    ("41", "自慰系列"),
    ("39", "熟女少妇"),
    ("53", "人妻系列"),
    ("38", "口交视频"),
    ("46", "颜射系列"),
    ("50", "教师学生"),
    ("40", "巨乳尤物"),
    ("45", "制服诱惑"),
    ("43", "日韩精品"),
    ("44", "颜值正义"),
    ("29", "网暴"),
    ("8", "cosplay"),
    ("33", "台湾swag"),
    ("35", "网曝"),
    ("6", "国产裸聊"),
    ("28", "女同"),
    ("10", "主播视频"),
    ("71", "都市"),
    ("37", "主播"),
    ("9", "网友原创"),
    ("78", "出轨"),
    ("76", "禁忌"),
    ("79", "校园"),
    ("82", "古风"),
    ("75", "奇幻"),
    ("11", "国产盗摄"),
    ("3", "动漫"),
    ("77", "首发"),
    ("31", "探花"),
    ("86", "影视魔改"),
    ("72", "办公室"),
    ("21", "水果派解说"),
    ("80", "熟女"),
    ("81", "豪门"),
    ("32", "国产"),
    ("27", "户外"),
]


# ---------------------------------------------------------------- Spider
class Spider(Spider):

    def getName(self):
        return "月色视频"

    _site = _SITE

    def _ensure_site(self):
        if getattr(self, "_site_checked", False):
            return self._site
        self._site = self._pick_site()
        self._site_checked = True
        return self._site

    def _pick_site(self):
        if _site_reachable(_SITE):
            return _SITE
        latest = None
        for _ in range(2):
            latest = _resolve_latest_site()
            if latest:
                break
        return latest or _SITE


    def init(self, extend=""):
        self._cover_port = 0
        self._server_started = False
        try:
            self._ensure_server()
        except Exception:
            pass
        return {"code": 0, "msg": "init ok"}

    def _ensure_server(self):
        if self._server_started:
            return self._cover_port
        self._server_started = True
        try:
            self._cover_port = _start_cover_server()
        except Exception:
            self._cover_port = 0
        return self._cover_port

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

    def _play_url(self, cdn_url):
        if not cdn_url or not cdn_url.startswith("http"):
            return ""
        return cdn_url

    # ---- 列表项 ----
    def _vod(self, v):
        try:
            vid = int(v.get("video_id") or 0)
        except Exception:
            return None
        name = (v.get("title") or "").strip()
        if not vid or not name:
            return None
        remarks = _fmt_len(v.get("duration"))
        if v.get("is_hd"):
            remarks = (remarks + " · 高清") if remarks else "高清"
        return {
            "vod_id": str(vid),
            "vod_name": name,
            "vod_pic": self._pic(v.get("video_img") 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

    def _page(self, content, pg):
        try:
            total = int(content.get("total") or 0)
        except Exception:
            total = 0
        try:
            per = int(content.get("per_page") or _PAGE_LEN)
        except Exception:
            per = _PAGE_LEN
        if per <= 0:
            per = _PAGE_LEN
        pagecount = (total + per - 1) // per if total else 1
        if pagecount > 5000:
            pagecount = 5000
        return {
            "list": self._list(content.get("data") or []),
            "page": pg,
            "pagecount": pagecount,
            "limit": 90,
            "total": total,
        }

    # ---- 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
        tid = str(tid)
        params = {"page": pg, "size": _PAGE_LEN, "sort": "latest"}
        if tid != "all":
            try:
                params["categories"] = int(tid)
            except Exception:
                return {"list": []}
        content = _api_post("videos/index", params)
        if not isinstance(content, dict) or "data" not in content:
            return {"list": []}
        return self._page(content, pg)

    def detailContent(self, ids):
        try:
            vid = int(str(ids[0]).strip())
        except Exception:
            return {"list": []}
        c = _api_post("videos/detail", {"id": vid})
        if not isinstance(c, dict) or not c.get("video_id"):
            return {"list": []}
        name = (c.get("title") or "").strip()
        remarks = []
        length = _fmt_len(c.get("duration"))
        if length:
            remarks.append("时长 " + length)
        if c.get("is_hd"):
            remarks.append("高清")
        if c.get("file_dimensions"):
            remarks.append(str(c.get("file_dimensions")))
        if c.get("vip_required"):
            remarks.append("VIP")
        cats = c.get("categories") or []
        type_name = ""
        if cats:
            type_name = (cats[0].get("title") or "").strip()
            
        play_from = "月色视频"
        play_url = "播放$%d" % vid
        vod = {
            "vod_id": str(vid),
            "vod_name": name,
            "vod_pic": self._pic(c.get("video_img") or ""),
            "type_name": type_name,
            "vod_tag": ",".join(
                str(t) for t in (c.get("tags") or []) if t) if isinstance(c.get("tags"), list) else "",
            "vod_remarks": " · ".join(remarks),
            "vod_actor": "",
            "vod_director": "",
            "vod_content": (c.get("description") or "").strip(),
            "vod_play_from": play_from,
            "vod_play_url": play_url,
        }
        return {"list": [vod]}

    def _js_url(self, vid):

        bucket = (vid // 1000) * 1000
        return ("https://yuese.b-cdn.net/hls/contents/videos/%d/%d/,"
                "%d.mp4,%d_720p.mp4,.urlset/list-f1-v1-a1.m3u8"
                % (bucket, vid, vid, vid))

    def _to_f1(self, url):

        if not url or "master.m3u8" not in url:
            return url
        return url.replace("master.m3u8", "list-f1-v1-a1.m3u8")

    def playerContent(self, flag, id, vipFlags):

        try:
            raw = str(id).strip().split("$")[-1]
            parts = raw.split("|")
            vid = int(parts[0])
            line_idx = int(parts[1]) if len(parts) > 1 else None
        except Exception:
            return {"parse": 1, "url": "", "header": ""}
        
        if line_idx is not None:
            if line_idx == 2:
                return {"parse": 0, "url": self._play_url(self._js_url(vid)),
                        "header": ""}
            try:
                r = _api_post("videos/switch_line",
                              {"video_id": vid, "line_idx": line_idx})
                url = ""
                if isinstance(r, dict):
                    url = (r.get("video_url") or "").strip()
                if url.startswith("http"):
                    return {"parse": 0, "url": self._play_url(self._to_f1(url)), "header": ""}
            except Exception:
                pass
            c = _api_post("videos/detail", {"id": vid})
            if isinstance(c, dict):
                url = (c.get("video_url") or "").strip()
                if url.startswith("http"):
                    return {"parse": 0, "url": self._play_url(self._to_f1(url)), "header": ""}
            return {"parse": 0, "url": self._play_url(self._js_url(vid)),
                    "header": ""}

        js_url = self._js_url(vid)
        return {"parse": 0, "url": self._play_url(js_url), "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": []}
        content = _api_post("videos/search",
                            {"keyword": key, "page": pg, "size": 24,
                             "sort": "latest"})
        if not isinstance(content, dict) or "data" not in content:
            return {"list": []}
        return self._page(content, pg)

    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("cover port:", sp._cover_port)
    hc = sp.homeContent(None)
    print("home classes:", len(hc["class"]), "| list:", len(hc["list"]))
    cat = sp.categoryContent("all", 1, None, None)
    print("最新视频 p1:", len(cat["list"]), "条 | total:", cat.get("total"))
    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("详情:", bool(det["list"]),
              "| 播放源:", det["list"][0]["vod_play_url"] if det["list"] else "")
        pc = sp.playerContent("月色视频", vid, None)
        print("播放 parse:", pc.get("parse"), "| url:", pc.get("url", "")[:90])
        # 本机转播取 master
        if pc.get("parse") == 0 and sp._cover_port:
            import urllib.request as _u
            try:
                with _u.urlopen(pc["url"], timeout=25) as resp:
                    body = resp.read().decode("utf-8", "ignore")
                print("本机转播 master:", resp.status, len(body), "bytes")
                print(body[:300])
            except Exception as e:
                print("本机转播失败:", type(e).__name__, str(e)[:100])
    cat2 = sp.categoryContent("1", 1, None, None)
    print("国产视频 p1:", len(cat2["list"]), "条 | total:", cat2.get("total"))
    sr = sp.searchContent("麻豆", False, 1)
    print("搜索 麻豆:", 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])
