# -*- coding: utf-8 -*-
"""
BB短剧 (bb.bbduanju.cc) - MacCMS v10 结构
实测:
- 搜索: /a/index.php/vod/search/wd/{key}.html, p2+ /a/index.php/vod/search/page/{pg}/wd/{key}.html
- 分类: /a/index.php/vod/type/id/{tid}.html, p2+ /a/index.php/vod/type/id/{tid}/page/{pg}.html (12条/页, 默认最新)
- 详情: /a/index.php/vod/detail/id/{id}.html -> 播放页 /a/index.php/vod/play/id/{id}/sid/{sid}/nid/{nid}.html
- 播放页 var player_aaaa = {...} JSON, url 字段即直链 m3u8 (实测 200)
- 封面 data-original 为真实直链 JPEG (data-aes 属性仅为标记, 实测字节为明文 ffd8, 无需解密)
- 卡片结构: div.vodlist-item > a.qx > img.content-img(data-original) + div.listitem-info(标题) + div.time(时长)
"""
import re
import ssl
import gzip
import zlib
import json
import urllib.request
import urllib.parse
import html

try:
    from base.spider import Spider as BaseSpider
except Exception:
    class BaseSpider(object):
        pass


class Spider(BaseSpider):

    def getName(self):
        return "BB短剧"

    def init(self, extend=""):
        pass

    def __init__(self):
        super(Spider, self).__init__()
        self.site_url = "https://bb.bbduanju.cc"
        self.headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
            "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
            "Connection": "keep-alive",
            "Referer": self.site_url + "/a/"
        }

    def _fetch(self, url):
        """urllib 直抓: 忽略证书 + gzip/deflate + 多 charset 回退"""
        req = urllib.request.Request(url, headers=self.headers)
        try:
            ctx = ssl._create_unverified_context()
        except Exception:
            ctx = None
        try:
            if ctx:
                resp = urllib.request.urlopen(req, context=ctx, timeout=12)
            else:
                resp = urllib.request.urlopen(req, timeout=12)
            raw = resp.read()
            enc = resp.headers.get("Content-Encoding", "").lower()
            if "gzip" in enc:
                raw = gzip.decompress(raw)
            elif "deflate" in enc:
                raw = zlib.decompress(raw)
            text = ""
            for charset in ("utf-8", "gbk", "gb2312", "iso-8859-1"):
                try:
                    text = raw.decode(charset)
                    break
                except Exception:
                    continue
            return {"success": True, "html": text, "real_url": resp.geturl()}
        except Exception as e:
            return {"success": False, "html": "", "error": str(e)}

    def homeContent(self, filter):
        classes = [
            {"type_id": "358", "type_name": "番茄资源"}, {"type_id": "359", "type_name": "欧美精品"},
            {"type_id": "360", "type_name": "偷拍自拍"}, {"type_id": "361", "type_name": "国产精品"},
            {"type_id": "362", "type_name": "乱伦系列"}, {"type_id": "363", "type_name": "主播网红"},
            {"type_id": "364", "type_name": "黑料网曝"}, {"type_id": "365", "type_name": "高清无码"},
            {"type_id": "366", "type_name": "中文字幕"}, {"type_id": "369", "type_name": "高清有码"},
            {"type_id": "368", "type_name": "动漫精选"}, {"type_id": "367", "type_name": "学生妹"},
            {"type_id": "244", "type_name": "55资源"}, {"type_id": "245", "type_name": "无码专区"},
            {"type_id": "246", "type_name": "麻豆传媒"}, {"type_id": "247", "type_name": "制服诱惑"},
            {"type_id": "248", "type_name": "三级伦理"}, {"type_id": "249", "type_name": "AI换脸"},
            {"type_id": "250", "type_name": "中文字幕2"}, {"type_id": "251", "type_name": "卡通动漫"},
            {"type_id": "252", "type_name": "欧美系列"}, {"type_id": "119", "type_name": "不卡资源"},
            {"type_id": "120", "type_name": "国产视频"}, {"type_id": "121", "type_name": "中文字幕3"},
            {"type_id": "122", "type_name": "国产传媒"}, {"type_id": "123", "type_name": "日本有码"},
            {"type_id": "124", "type_name": "日本无码"}, {"type_id": "125", "type_name": "欧美无码"},
            {"type_id": "126", "type_name": "强干乱伦"}, {"type_id": "127", "type_name": "制服诱惑2"},
            {"type_id": "286", "type_name": "兔儿资源"}, {"type_id": "304", "type_name": "精品推荐"},
            {"type_id": "305", "type_name": "主播秀色"}, {"type_id": "306", "type_name": "日本有码2"},
            {"type_id": "307", "type_name": "日本无码2"}, {"type_id": "308", "type_name": "中文字幕4"},
            {"type_id": "309", "type_name": "童颜巨乳"}, {"type_id": "310", "type_name": "性感人妻"},
            {"type_id": "311", "type_name": "强歼乱伦"}, {"type_id": "370", "type_name": "森林资源"},
            {"type_id": "371", "type_name": "精品推荐2"}, {"type_id": "372", "type_name": "国产情色"},
            {"type_id": "373", "type_name": "亚洲无码"}, {"type_id": "374", "type_name": "亚洲有码"},
            {"type_id": "375", "type_name": "中文字幕5"}, {"type_id": "376", "type_name": "强*乱伦"},
            {"type_id": "377", "type_name": "欧美精品2"}, {"type_id": "378", "type_name": "萝莉少女"},
            {"type_id": "386", "type_name": "黄瓜资源"}, {"type_id": "387", "type_name": "国产自拍"},
            {"type_id": "388", "type_name": "日本无码3"}, {"type_id": "390", "type_name": "AI短剧"},
            {"type_id": "391", "type_name": "主播系列"}, {"type_id": "329", "type_name": "库库资源"},
            {"type_id": "330", "type_name": "日本有码3"}, {"type_id": "331", "type_name": "无码中文"},
            {"type_id": "332", "type_name": "有码中文"}, {"type_id": "333", "type_name": "日本无码4"},
            {"type_id": "334", "type_name": "国产视频2"}, {"type_id": "335", "type_name": "欧美高清"},
            {"type_id": "336", "type_name": "动漫剧情"},
        ]
        return {"class": classes, "filters": {}}

    def homeVideoContent(self):
        res = self._fetch(self.site_url + "/a/")
        cards = self._parse_vod_list(res.get("html", "")) if res.get("success") else []
        return {"list": cards}

    # ---------------- 统一列表解析 (分类/搜索/首页共用) ----------------
    def _parse_vod_list(self, html_data):
        cards = []
        if not html_data:
            return cards
        blocks = re.findall(
            r'<div[^>]*class=["\'][^"\']*vodlist-item[^"\']*["\'][^>]*>(.*?)</a>\s*</div>',
            html_data, re.I | re.S)
        seen = set()
        for block in blocks:
            m = re.search(r'href=["\'](/a/index\.php/vod/detail/id/\d+\.html)["\']', block, re.I)
            if not m:
                continue
            href = m.group(1)
            vid = re.search(r'/id/(\d+)\.html', href).group(1)
            if vid in seen:
                continue
            seen.add(vid)

            title = ""
            tm = re.search(r'<div[^>]*class=["\'][^"\']*listitem-info[^"\']*["\'][^>]*>(.*?)</div>', block, re.I | re.S)
            if tm:
                title = re.sub(r'<[^>]+>', '', tm.group(1)).strip()
            if not title:
                am = re.search(r'title=["\']([^"\']+)["\']', block, re.I)
                if am:
                    title = am.group(1).strip()
            if not title:
                continue
            title = html.unescape(title)

            pic = ""
            for pat in (r'data-original=["\']([^"\']+)["\']', r'data-src=["\']([^"\']+)["\']',
                        r'data-echo=["\']([^"\']+)["\']', r'src=["\']([^"\']+)["\']'):
                pm = re.search(pat, block, re.I)
                if pm:
                    cand = pm.group(1).strip()
                    if cand and "load.jpg" not in cand and not cand.startswith("data:image"):
                        pic = cand
                        break
            if pic.startswith("//"):
                pic = "https:" + pic
            elif pic.startswith("/"):
                pic = urllib.parse.urljoin(self.site_url, pic)

            dur = ""
            dm = re.search(r'<div[^>]*class=["\'][^"\']*time[^"\']*["\'][^>]*>(.*?)</div>', block, re.I | re.S)
            if dm:
                dur = re.sub(r'<[^>]+>', '', dm.group(1)).strip()
            remarks = "BB短剧 | %s" % dur if dur else "BB短剧"

            cards.append({
                "vod_id": vid,
                "vod_name": title,
                "vod_pic": pic,
                "vod_remarks": remarks,
                "style": {"type": "rect", "ratio": 1.78}
            })
        return cards

    def categoryContent(self, tid, pg, filter, extend):
        pg_int = int(pg) if str(pg).isdigit() else 1
        if pg_int <= 1:
            url = "%s/a/index.php/vod/type/id/%s.html" % (self.site_url, tid)
        else:
            url = "%s/a/index.php/vod/type/id/%s/page/%d.html" % (self.site_url, tid, pg_int)
        res = self._fetch(url)
        cards = self._parse_vod_list(res.get("html", "")) if res.get("success") else []
        return {
            "list": cards,
            "page": pg_int,
            "pagecount": pg_int + 1 if len(cards) >= 12 else pg_int,
            "limit": len(cards),
            "total": 9999
        }

    def detailContent(self, ids):
        vid = ids[0] if isinstance(ids, list) else ids
        res = self._fetch("%s/a/index.php/vod/detail/id/%s.html" % (self.site_url, vid))
        h = res.get("html", "")

        title = ""
        tm = re.search(r'<h1[^>]*>(.*?)</h1>', h, re.I | re.S)
        if tm:
            title = re.sub(r'<[^>]+>', '', tm.group(1)).strip()
        if not title:
            tm = re.search(r'<title>([^<—-]+)', h, re.I)
            title = tm.group(1).strip() if tm else ""

        pic = ""
        pm = re.search(r'<img[^>]+class=["\'][^"\']*content-img[^"\']*["\'][^>]*>', h, re.I)
        if pm:
            tag = pm.group(0)
            om = re.search(r'data-original=["\']([^"\']+)["\']', tag, re.I)
            if om and "load.jpg" not in om.group(1):
                pic = om.group(1).strip()

        episodes = []
        for m in re.finditer(r'href=["\'](/a/index\.php/vod/play/id/\d+/sid/\d+/nid/\d+\.html)["\'][^>]*>([^<]*)</a>', h, re.I):
            name = m.group(2).strip() or "立即播放"
            if "vod/play" in m.group(1):
                episodes.append("%s$%s" % (name, self.site_url + m.group(1)))
        if not episodes:
            episodes.append("立即播放$%s/a/index.php/vod/play/id/%s/sid/1/nid/1.html" % (self.site_url, vid))

        vod = {
            "vod_id": vid,
            "vod_name": html.unescape(title) if title else "BB短剧",
            "vod_pic": pic,
            "type_name": "BB短剧",
            "vod_remarks": "BB短剧",
            "vod_content": "BB短剧",
            "vod_play_from": "BB线路",
            "vod_play_url": "#".join(episodes)
        }
        return {"list": [vod]}

    def _player_aaaa(self, h):
        """平衡括号解析 var player_aaaa = {...}"""
        start = h.find("var player_aaaa")
        if start < 0:
            return None
        start = h.find("{", start)
        if start < 0:
            return None
        depth, i = 0, start
        while i < len(h):
            if h[i] == "{":
                depth += 1
            elif h[i] == "}":
                depth -= 1
                if depth == 0:
                    break
            i += 1
        try:
            return json.loads(h[start:i + 1])
        except Exception:
            return None

    def playerContent(self, flag, id, vipFlags):
        play_url = id if id.startswith("http") else self.site_url + id
        res = self._fetch(play_url)
        h = res.get("html", "")
        target = ""
        if h:
            cfg = self._player_aaaa(h)
            if cfg and cfg.get("url"):
                target = cfg["url"].replace("\\/", "/").strip()
            if not target:
                ms = re.findall(r'["\'](https?://[^"\']+\.m3u8[^"\']*)["\']', h, re.I)
                if ms:
                    target = ms[0]
        return {
            "parse": 0 if target else 1,
            "playUrl": "",
            "url": target if target else play_url,
            "header": json.dumps({
                "User-Agent": self.headers["User-Agent"],
                "Referer": play_url
            })
        }

    def searchContent(self, key, quick, pg="1"):
        pg_int = int(pg) if str(pg).isdigit() else 1
        ek = urllib.parse.quote(key)
        if pg_int <= 1:
            url = "%s/a/index.php/vod/search/wd/%s.html" % (self.site_url, ek)
        else:
            url = "%s/a/index.php/vod/search/page/%d/wd/%s.html" % (self.site_url, pg_int, ek)
        res = self._fetch(url)
        cards = self._parse_vod_list(res.get("html", "")) if res.get("success") else []
        return {
            "list": cards,
            "page": pg_int,
            "pagecount": pg_int + 1 if len(cards) >= 12 else pg_int,
            "limit": len(cards),
            "total": 9999
        }

    def action(self, action):
        return {}

    def liveContent(self):
        return {}

    def localProxy(self, params):
        return [200, "text/plain; charset=utf-8", ""]

    def manualVideoCheck(self):
        return False

    def isVideoFormat(self, url):
        return False

    def destroy(self):
        pass


if __name__ == "__main__":
    sp = Spider()
    sp.init()
    ok = True

    def check(name, cond, extra=""):
        global ok
        print(("PASS " if cond else "FAIL ") + name + (" | " + str(extra) if extra else ""))
        if not cond:
            ok = False

    r = sp.homeVideoContent()
    check("homeVideo", len(r["list"]) > 0, "%d条" % len(r["list"]))

    r = sp.categoryContent("365", "1", True, {})
    check("category p1", len(r["list"]) == 12, "%d条 pagecount=%s" % (len(r["list"]), r["pagecount"]))
    pics = sum(1 for v in r["list"] if v["vod_pic"].startswith("http"))
    check("category 封面率", pics == len(r["list"]), "%d/%d" % (pics, len(r["list"])))

    r2 = sp.categoryContent("365", "2", True, {})
    ids1 = {v["vod_id"] for v in r["list"]}
    ids2 = {v["vod_id"] for v in r2["list"]}
    check("category p2", len(r2["list"]) > 0 and not ids1 & ids2, "%d条 无重叠" % len(r2["list"]))

    r = sp.searchContent("撕烂", False, "1")
    check("search p1", len(r["list"]) == 12, "%d条 pagecount=%s" % (len(r["list"]), r["pagecount"]))
    r = sp.searchContent("撕烂", False, "2")
    check("search p2", len(r["list"]) > 0, "%d条" % len(r["list"]))

    d = sp.detailContent(["365178"])
    v = d["list"][0]
    check("detail", bool(v["vod_name"]) and "立即播放" in v["vod_play_url"], v["vod_name"][:20])
    play_id = v["vod_play_url"].split("#")[0].split("$", 1)[1]
    p = sp.playerContent("BB线路", play_id, [])
    check("player", p["parse"] == 0 and p["url"].endswith(".m3u8"), p["url"][:60])

    print("ALL PASS" if ok else "SOME FAILED")
