# -*- coding: utf-8 -*-
"""
换|妻|网 (tv.huanqiwang8.cc) - MacCMS v10, hqw 模板
与 bbduanju 同路由不同模板:
- 卡片: <a class="vod-item" href="/a/index.php/vod/detail/id/{id}.html">
        <div class="vod-thumb"><img class="lazyload" src="load.png" data-original="{pic}" alt="{title}"></div>
        <div class="vod-name">{title}</div></a>  (无时长)
- 分类: /a/index.php/vod/type/id/{tid}.html, p2+ /a/index.php/vod/type/id/{tid}/page/{pg}.html, 12条/页
- 搜索: p1 /a/index.php/vod/search.html?wd={key}, p2+ /a/index.php/vod/search/page/{pg}/wd/{key}.html
- 详情页直接渲染为播放页, 另有 /a/index.php/vod/play/id/{id}/sid/{sid}/nid/{nid}.html
- 播放页 var player_aaaa = {...} JSON, url 即直链 m3u8 (实测 200)
"""
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 "酒店偷拍"

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

    def __init__(self):
        super(Spider, self).__init__()
        self.site_url = "https://4g.jdtp10.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, timeout=12, retries=4):
        import time as _time
        import http.client as _http_client
        req = urllib.request.Request(url, headers=self.headers)
        try:
            ctx = ssl._create_unverified_context()
        except Exception:
            ctx = None
        last_err = ""
        for attempt in range(retries + 1):
            try:
                if ctx:
                    resp = urllib.request.urlopen(req, context=ctx, timeout=timeout)
                else:
                    resp = urllib.request.urlopen(req, timeout=timeout)
                try:
                    raw = resp.read()
                except _http_client.IncompleteRead as ie:
                    # 本站 CDN 随机截断: partial 足够长就直接用
                    raw = ie.partial if ie.partial and len(ie.partial) > 5000 else b""
                if not raw:
                    raise ValueError("empty body")
                enc = resp.headers.get("Content-Encoding", "").lower()
                if "gzip" in enc:
                    try:
                        raw = gzip.decompress(raw)
                    except Exception:
                        pass
                elif "deflate" in enc:
                    try:
                        raw = zlib.decompress(raw)
                    except Exception:
                        pass
                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)
                if attempt < retries:
                    _time.sleep(2)
        return {"success": False, "html": "", "error": last_err}

    def homeContent(self, filter):
        classes = [
            {"type_id": "119", "type_name": "不卡资源"}, {"type_id": "120", "type_name": "国产视频"},
            {"type_id": "121", "type_name": "中文字幕"}, {"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": "制服诱惑"}, {"type_id": "128", "type_name": "国产主播"},
            {"type_id": "129", "type_name": "激情动漫"}, {"type_id": "130", "type_name": "明星换脸"},
            {"type_id": "131", "type_name": "抖阴视频"}, {"type_id": "245", "type_name": "无码专区"},
            {"type_id": "246", "type_name": "麻豆传媒"}, {"type_id": "248", "type_name": "三级伦理"},
            {"type_id": "249", "type_name": "AI换脸"}, {"type_id": "251", "type_name": "卡通动漫"},
            {"type_id": "252", "type_name": "欧美系列"}, {"type_id": "253", "type_name": "美女主播"},
            {"type_id": "254", "type_name": "国产自拍"}, {"type_id": "255", "type_name": "熟女人妻"},
            {"type_id": "256", "type_name": "萝莉少女"}, {"type_id": "257", "type_name": "百合剧情"},
            {"type_id": "258", "type_name": "美乳巨乳"}, {"type_id": "259", "type_name": "强歼乱伦"},
            {"type_id": "260", "type_name": "抖音视频"}, {"type_id": "261", "type_name": "韩国主播"},
            {"type_id": "262", "type_name": "网红头条"}, {"type_id": "263", "type_name": "网曝黑料"},
            {"type_id": "266", "type_name": "AV解说"}, {"type_id": "286", "type_name": "兔儿资源"},
            {"type_id": "304", "type_name": "精品推荐"}, {"type_id": "305", "type_name": "主播秀色"},
            {"type_id": "309", "type_name": "童颜巨乳"}, {"type_id": "310", "type_name": "性感人妻"},
            {"type_id": "312", "type_name": "欧美情色"}, {"type_id": "315", "type_name": "丝袜OL"},
            {"type_id": "329", "type_name": "库库资源"}, {"type_id": "331", "type_name": "无码中文"},
            {"type_id": "332", "type_name": "有码中文"}, {"type_id": "335", "type_name": "欧美高清"},
            {"type_id": "336", "type_name": "动漫剧情"}, {"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": "367", "type_name": "学生妹"},
            {"type_id": "368", "type_name": "动漫精选"}, {"type_id": "369", "type_name": "高清有码"},
            {"type_id": "370", "type_name": "森林资源"}, {"type_id": "372", "type_name": "国产情色"},
            {"type_id": "373", "type_name": "亚洲无码"}, {"type_id": "374", "type_name": "亚洲有码"},
            {"type_id": "376", "type_name": "强*乱伦"}, {"type_id": "379", "type_name": "日本精品"},
            {"type_id": "380", "type_name": "Cosplay"}, {"type_id": "381", "type_name": "野外露出"},
            {"type_id": "382", "type_name": "网红流出"}, {"type_id": "388", "type_name": "主播系列"},
            {"type_id": "389", "type_name": "AI短剧"}, {"type_id": "391", "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}

    # ---------------- 统一列表解析 (hqw 模板) ----------------
    def _parse_vod_list(self, html_data):
        cards = []
        if not html_data:
            return cards
        blocks = re.findall(
            r'<a[^>]*class=["\']vod-item["\'][^>]*href=["\'](/a/index\.php/vod/detail/id/(\d+)\.html)["\'][^>]*>(.*?)</a>',
            html_data, re.I | re.S)
        if not blocks:
            blocks = re.findall(
                r'<a[^>]*href=["\'](/a/index\.php/vod/detail/id/(\d+)\.html)["\'][^>]*class=["\']vod-item["\'][^>]*>(.*?)</a>',
                html_data, re.I | re.S)
        seen = set()
        for href, vid, inner in blocks:
            if vid in seen:
                continue
            seen.add(vid)

            title = ""
            nm = re.search(r'<div[^>]*class=["\']vod-name["\'][^>]*>(.*?)</div>', inner, re.I | re.S)
            if nm:
                title = re.sub(r'<[^>]+>', '', nm.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'data-original=["\']([^"\']+)["\']', r'data-src=["\']([^"\']+)["\']',
                        r'src=["\']([^"\']+)["\']'):
                pm = re.search(pat, inner, re.I)
                if pm:
                    cand = pm.group(1).strip()
                    if cand and "load.png" not in 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)

            cards.append({
                "vod_id": vid,
                "vod_name": title,
                "vod_pic": pic,
                "vod_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 _player_aaaa(self, h):
        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 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'<title>(.*?)</title>', h, re.I | re.S)
        if tm:
            t = tm.group(1).strip()
            # "正在播放：{片名}" 或 "{片名} - 换|妻|网"
            t = re.sub(r'^正在播放[：:]\s*', '', t)
            title = t.split(" - ")[0].strip()

        pic = ""
        pm = re.search(r'data-original=["\'](https?://[^"\']+\.(?:jpg|jpeg|png|webp)[^"\']*)["\']', h, re.I)
        if pm:
            pic = pm.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 "HD"
            episodes.append("%s$%s" % (name, self.site_url + m.group(1)))
        # 详情页本身就是播放页: 直接解析 player_aaaa 拿直链
        direct = ""
        cfg = self._player_aaaa(h)
        if cfg and cfg.get("url"):
            direct = cfg["url"].replace("\\/", "/").strip()
        if direct and not episodes:
            episodes.append("HD$%s/a/index.php/vod/detail/id/%s.html" % (self.site_url, vid))
        if not episodes:
            episodes.append("HD$%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 "酒店偷拍",
            "vod_pic": pic,
            "type_name": "酒店偷拍",
            "vod_remarks": "酒店偷拍",
            "vod_content": "酒店偷拍",
            "vod_play_from": "酒店线路",
            "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:
            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("360", "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("360", "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"]))
    s2 = sp.searchContent("旅馆", False, "2")
    check("search p2", len(s2["list"]) > 0, "%d条" % len(s2["list"]))

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

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