# -*- coding: utf-8 -*-
"""
xx6nj (xx6njgzcba.lol) - hunt 标签站, xx6nj 模板
实测:
- 列表: <div class="col-6 col-md-3"><a href='/info/id/{id}.html'>
        <img class="card-img-top" src="{pic}" alt="{title}"><p>{title}</p></a></div>
- 标签页: /hunt/{tag}.html (p1), p2+ /hunt/{tag}/h/{pg}.html, 20条/页
- 详情: /info/id/{id}.html -> 播放链接 /play/id/{id}.html
- 播放页: playUrl = 'https://...m3u8' 直链 (实测 200)
- 注意: 页内大量广告外链, 只认 /info/id/ 链接; img src 即真实封面直链
"""
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 "xx6nj"

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

    def __init__(self):
        super(Spider, self).__init__()
        self.site_url = "https://xx6njgzcba.lol"
        self._last_req = 0.0  # 请求节流: 本站限连续请求频率
        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 + "/"
        }

    def _fetch(self, url, timeout=15, retries=2):
        import time as _time
        gap = _time.time() - self._last_req
        if gap < 4:
            _time.sleep(4 - gap)
        self._last_req = _time.time()
        req = urllib.request.Request(url, headers=self.headers)
        try:
            ctx = ssl._create_unverified_context()
        except Exception:
            ctx = None
        last_err = ""
        for _ in range(retries + 1):
            try:
                if ctx:
                    resp = urllib.request.urlopen(req, context=ctx, timeout=timeout)
                else:
                    resp = urllib.request.urlopen(req, timeout=timeout)
                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:
                last_err = str(e)
        return {"success": False, "html": "", "error": last_err}

    def homeContent(self, filter):
        tags = ['91-吃瓜', '中文剧情', '中文字幕', '为国争光', '主播网红', '乱伦三观', '乱伦呦女',
                '人兽典藏', '偷拍自拍', '偷窥', '六年级萝莉', '初一小萝莉', '制服', '呻吟',
                '国产制作', '国产小学生', '国产高清', '多P', '大奶', '大屁股', '女儿9岁',
                '姐姐', '娇小', '媚黑母狗', '嫖妓过程', '学生', '小学6年级', '小学六年级',
                '小学生', '小学生口交', '小学生尿尿', '小学生性交', '小学生色情', '少女破处',
                '性感', '成人综艺', '换妻', '操小学生', '无套', '日本小萝莉', '欣儿宝贝',
                '淫乱学妹', '淫母乱伦', '爆乳', '白丝学妹口球调教', '白嫩', '白浆',
                '监控摄像', '眼镜', '神乳', '精品国产', '网上聊天', '网曝热门', '美乳',
                '美少女', '美臀', '翘臀', '肥逼', '腹泻视频18', '自慰', '苗条', '荡妇',
                '萝莉', '萝莉学生', '贫乳', '长腿', '高清无码', '黑丝修女', '黑料偷拍+', '黑料打烊']
        classes = [{"type_id": t, "type_name": t} for t in tags]
        return {"class": classes, "filters": {}}

    def homeVideoContent(self):
        res = self._fetch(self.site_url + "/hunt/美乳.html")
        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'<a[^>]*href=[\'"]/info/id/(\d+)\.html[\'"][^>]*>(.*?)</a>',
            html_data, re.I | re.S)
        seen = set()
        for vid, inner in blocks:
            if vid in seen:
                continue
            seen.add(vid)

            title = ""
            pm = re.search(r'<p[^>]*>(.*?)</p>', inner, re.I | re.S)
            if pm:
                title = re.sub(r'<[^>]+>', '', pm.group(1)).strip()
            if not title:
                am = re.search(r'alt=[\'"]([^\'"]+)[\'"]', inner, re.I)
                if am:
                    title = am.group(1).strip()
            if not title:
                continue
            title = html.unescape(title)

            pic = ""
            for pat in (r'src=[\'"]([^\'"]+)["\']', r'data-src=[\'"]([^\'"]+)["\']',
                        r'data-original=[\'"]([^\'"]+)["\']'):
                im = re.search(pat, inner, re.I)
                if im:
                    cand = im.group(1).strip()
                    if 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)

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

    def _hunt_url(self, tag, pg_int):
        ek = urllib.parse.quote(tag)
        if pg_int <= 1:
            return "%s/hunt/%s.html" % (self.site_url, ek)
        return "%s/hunt/%s/h/%d.html" % (self.site_url, ek, pg_int)

    def categoryContent(self, tid, pg, filter, extend):
        pg_int = int(pg) if str(pg).isdigit() else 1
        res = self._fetch(self._hunt_url(tid, pg_int))
        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) >= 20 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/info/id/%s.html" % (self.site_url, vid))
        h = res.get("html", "")

        title = ""
        tm = re.search(r'<title>(.*?)</title>', h, re.I | re.S)
        if tm:
            title = tm.group(1).split("视频数据详情")[0].split("-")[0].strip()

        pic = ""
        pm = re.search(r'<img[^>]+class=[\'"]card-img-top[\'"][^>]+src=[\'"]([^\'"]+)[\'"]', h, re.I)
        if not pm:
            pm = re.search(r'(?:data-original|data-src|src)=[\'"](https?://[^\'"]+\.(?:jpg|jpeg|png|webp)[^\'"]*)[\'"]', h, re.I)
        if pm:
            pic = pm.group(1).strip()

        episodes = []
        for m in re.finditer(r'href=[\'"](/play/id/\d+\.html)[\'"]', h, re.I):
            episodes.append("正片$%s%s" % (self.site_url, m.group(1)))
            break
        if not episodes:
            episodes.append("正片$%s/play/id/%s.html" % (self.site_url, vid))

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

    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:
            m = re.search(r"""playUrl\s*=\s*['"]([^'"]+)['"]""", h)
            if m:
                target = m.group(1).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"):
        # 本站无独立搜索, hunt 标签即搜索
        pg_int = int(pg) if str(pg).isdigit() else 1
        res = self._fetch(self._hunt_url(key, pg_int))
        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) >= 20 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.categoryContent("美乳", "1", True, {})
    check("category p1", len(r["list"]) == 20, "%d条" % len(r["list"]))
    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("美乳", "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"]))

    s = sp.searchContent("美乳", False, "1")
    check("search p1", len(s["list"]) > 0, "%d条" % len(s["list"]))

    vid = r["list"][0]["vod_id"]
    d = sp.detailContent([vid])
    v = d["list"][0]
    check("detail", bool(v["vod_name"]) and v["vod_name"] != "xx6nj", v["vod_name"][:24])
    play_id = v["vod_play_url"].split("#")[0].split("$", 1)[1]
    p = sp.playerContent("xx6nj线路", play_id, [])
    check("player", p["parse"] == 0 and p["url"].endswith(".m3u8"), p["url"][:70])

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