# -*- coding: utf-8 -*-
import sys
import ssl
import time
import json
import re
import urllib.request
import urllib.parse
from http.cookiejar import CookieJar

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

class Spider(BaseSpider):
    def __init__(self):
        self.site_url = "https://91porny.com"
        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,*/*;q=0.8",
            "Accept-Language": "zh-CN,zh;q=0.9",
            "Referer": "https://91porny.com/",
            "Connection": "keep-alive",
        }
        self.cookie_jar = CookieJar()
        self.opener = self._build_opener()
        self.cats = [
            ("home", "首页推荐"),
            ("madou", "麻豆传媒"),
            ("swag", "SWAG"),
            ("videos", "最高评分"),
            ("vod", "精选视频"),
        ]
        self._throttle = 0.4
        self._last_req = 0.0

    def _build_opener(self):
        ctx = ssl.create_default_context()
        ctx.check_hostname = False
        ctx.verify_mode = ssl.CERT_NONE
        https_handler = urllib.request.HTTPSHandler(context=ctx)
        cookie_handler = urllib.request.HTTPCookieProcessor(self.cookie_jar)
        return urllib.request.build_opener(https_handler, cookie_handler)

    def getName(self):
        return "九色"

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

    # ============ 网络层 ============
    def _decode_body(self, raw, enc=""):
        if not raw:
            return ""
        if isinstance(raw, str):
            return raw
        if "gzip" in enc:
            try:
                import gzip
                raw = gzip.decompress(raw)
            except Exception:
                pass
        elif "deflate" in enc:
            try:
                import zlib
                raw = zlib.decompress(raw)
            except Exception:
                pass
        for cs in ("utf-8", "gbk", "gb2312"):
            try:
                return raw.decode(cs)
            except Exception:
                continue
        return raw.decode("utf-8", errors="ignore")

    def _fetch(self, url, timeout=12, retries=2, referer=None):
        import http.client
        gap = time.time() - self._last_req
        if gap < self._throttle:
            time.sleep(self._throttle - gap)
        self._last_req = time.time()
        headers = dict(self.headers)
        if referer:
            headers["Referer"] = referer
        req = urllib.request.Request(url, headers=headers)
        for attempt in range(retries + 1):
            try:
                resp = self.opener.open(req, timeout=timeout)
                raw = resp.read()
                enc = resp.headers.get("Content-Encoding", "").lower()
                return {"success": True, "html": self._decode_body(raw, enc)}
            except http.client.IncompleteRead as e:
                if e.partial:
                    return {"success": True, "html": self._decode_body(e.partial)}
            except Exception:
                if attempt < retries:
                    time.sleep(0.4)
        return {"success": False, "html": ""}

    def _fetch_html(self, url, must_contain=None, timeout=12, referer=None):
        html_data = ""
        for _ in range(3):
            res = self._fetch(url, timeout=timeout, referer=referer)
            html_data = res.get("html", "")
            if res.get("success") and (not must_contain or must_contain in html_data):
                return html_data
        return html_data

    @staticmethod
    def _clean(text):
        if not text:
            return ""
        import html as html_mod
        text = html_mod.unescape(text)
        return re.sub(r"<[^>]+>", "", text).strip()

    # ============ 封面代理 ============
    @staticmethod
    def _img_mime(data):
        if not data or len(data) < 12:
            return ""
        if data[:2] == b"\xff\xd8":
            return "image/jpeg"
        if data[:8] == b"\x89PNG\r\n\x1a\n":
            return "image/png"
        if data[:4] == b"RIFF" and data[8:12] == b"WEBP":
            return "image/webp"
        return ""

    def _fetch_bytes(self, url, timeout=15):
        import http.client
        req = urllib.request.Request(url, headers={
            "User-Agent": self.headers["User-Agent"],
            "Referer": self.site_url + "/"})
        best = b""
        for _ in range(3):
            try:
                resp = self.opener.open(req, timeout=timeout)
                return resp.read()
            except http.client.IncompleteRead as e:
                if e.partial and len(e.partial) > len(best):
                    best = e.partial
            except Exception:
                pass
        return best

    def _pic_url(self, pic):
        return pic if pic else ""

    def localProxy(self, params):
        try:
            if params.get("type") == "pic":
                url = params.get("url", "")
                if url:
                    raw = self._fetch_bytes(url)
                    mime = self._img_mime(raw)
                    if mime:
                        return [200, mime, raw, ""]
        except Exception:
            pass
        return [200, "text/plain;charset=utf-8", ""]

    # ============ 列表解析 ============
    def _parse_vod_list(self, html_data):
        cards, seen = [], set()
        if not html_data:
            return cards
        # 三种卡片格式：
        # 1) <a href="/video/view/{hex}">...background-image... </a><a class="title" href="/video/view/{hex}">标题</a>
        # 2) <a href="/videos/view/{id}/{slug}/">...
        # 3) <a href="/vod/view/{id}">...
        for m in re.finditer(
                r'href="((?:/video/view/[a-f0-9]+|/videos/view/\d+/[^"]*?|/vod/view/[^"]+?))"[^>]*>.*?'
                r'background-image:\s*url\([\'"]?((?:https?:)?//[^)\'"]+)[\'"]?\).*?</a>.*?',
                html_data, re.S):
            url, pic = m.group(1), m.group(2)
            # 找同卡片标题
            seg = html_data[m.start():m.start()+2000]
            tm = re.search(r'class="title[^"]*"[^>]*>([^<]{4,120})</a>', seg)
            title = tm.group(1).strip() if tm else ""
            vid = url  # 用完整URL做ID
            if vid in seen:
                continue
            seen.add(vid)
            if pic.startswith("//"):
                pic = "https:" + pic
            cards.append({
                "vod_id": vid,
                "vod_name": self._clean(title) or vid.split("/")[-2][:20],
                "vod_pic": pic,
                "vod_remarks": "",
            })
        return cards

    def _extract_play_url(self, html_data):
        """data-src 直链（m3u8/mp4，带签名）；过滤 sample/test"""
        if not html_data:
            return ""
        m = re.search(r'data-src="(https?://[^"]+)"', html_data)
        if m:
            u = m.group(1).replace("&amp;", "&").strip()
            if u.startswith("http") and "sample" not in u and "test" not in u:
                return u
        for mm in re.finditer(r'["\'](https?://[^"\']+\.m3u8[^"\']*)["\']', html_data, re.I):
            u = mm.group(1).replace("&amp;", "&")
            if "sample" not in u and "test" not in u:
                return u
        return ""

    # ============ 标准接口 ============
    def _cat_url(self, tid, pg):
        base = self.site_url + ("" if tid == "home" else "/" + tid)
        return "%s?page=%d" % (base, pg) if pg > 1 else base + "/"

    def homeContent(self, filter):
        return {"class": [{"type_id": tid, "type_name": name}
                          for tid, name in self.cats],
                "filters": {}}

    def homeVideoContent(self):
        html_data = self._fetch_html(self.site_url + "/", must_contain="/video/view/")
        return {"list": self._parse_vod_list(html_data)[:20]}

    def categoryContent(self, tid, pg, filter, extend):
        try:
            pg = int(pg)
        except Exception:
            pg = 1
        if pg < 1:
            pg = 1
        tid = str(tid).strip() or "home"
        html_data = self._fetch_html(self._cat_url(tid, pg), must_contain="/video/view/")
        cards = self._parse_vod_list(html_data)
        return {"list": cards, "page": pg,
                "pagecount": pg + 1 if len(cards) >= 10 else pg,
                "limit": len(cards), "total": 0}

    def detailContent(self, ids):
        vid = str(ids[0]).strip() if ids else ""
        if not vid:
            return {"list": []}
        # vid 可能是完整路径（/video/view/xxx）或纯hex
        if vid.startswith("/"):
            detail_url = self.site_url + vid
        elif vid.startswith("http"):
            detail_url = vid
        else:
            detail_url = "%s/video/view/%s" % (self.site_url, vid)
        vod = {"vod_id": vid, "vod_name": vid, "vod_pic": "",
               "vod_remarks": "", "vod_content": "",
               "vod_play_from": "在线播放",
               "vod_play_url": "正片$%s" % detail_url}
        try:
            html_data = self._fetch_html(detail_url, must_contain="data-src")
            tm = re.search(r"<title>(.*?)</title>", html_data, re.S | re.I)
            if tm:
                t = self._clean(tm.group(1)).split("-")[0].split("|")[0].strip()
                if t:
                    vod["vod_name"] = t
            pm = re.search(r'data-poster="([^"]+)"', html_data)
            if pm:
                pic = pm.group(1).strip()
                if pic.startswith("//"):
                    pic = "https:" + pic
                vod["vod_pic"] = pic
            play_url = self._extract_play_url(html_data)
            if play_url:
                vod["vod_play_url"] = "正片$%s" % play_url
        except Exception:
            pass
        return {"list": [vod]}

    def playerContent(self, flag, id, vipFlags):
        raw_id = str(id).strip()
        header = {"User-Agent": self.headers["User-Agent"],
                  "Referer": self.site_url + "/"}
        if raw_id.startswith("http"):
            return {"parse": 0, "url": raw_id, "header": header}
        # 重新抓详情拿新鲜签名直链
        try:
            if raw_id.startswith("/"):
                durl = self.site_url + raw_id
            else:
                vid = re.sub(r"[^a-f0-9]", "", raw_id)
                durl = "%s/video/view/%s" % (self.site_url, vid) if vid else ""
            if durl:
                html_data = self._fetch_html(durl, must_contain="data-src")
                play_url = self._extract_play_url(html_data)
                if play_url:
                    return {"parse": 0, "url": play_url, "header": header}
        except Exception:
            pass
        return {"parse": 1, "url": raw_id, "header": header}

    def searchContent(self, key, quick, pg="1"):
        try:
            pg = int(pg)
        except Exception:
            pg = 1
        if pg < 1:
            pg = 1
        kw = urllib.parse.quote(str(key).strip())
        url = "%s/search?keywords=%s" % (self.site_url, kw)
        if pg > 1:
            url += "&page=%d" % pg
        html_data = self._fetch_html(url)
        cards = self._parse_vod_list(html_data)
        return {"list": cards, "page": pg,
                "pagecount": pg + 1 if len(cards) >= 10 else pg,
                "limit": len(cards), "total": 0}

    def action(self, action):
        return None

    def liveContent(self):
        return {}

    def isVideoFormat(self, url):
        u = (url or "").lower()
        return u.endswith(".m3u8") or ".m3u8?" in u

    def manualVideoCheck(self):
        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

    hc = sp.homeContent(True)
    check("homeContent", len(hc["class"]) == 5, "%d分类" % len(hc["class"]))

    r = sp.categoryContent("madou", "1", None, None)
    check("category", len(r["list"]) > 0, "%d条" % len(r["list"]))
    pics = sum(1 for v in r["list"] if v["vod_pic"].startswith("http"))
    check("covers", pics == len(r["list"]) and pics > 0,
          "%d/%d" % (pics, len(r["list"])))
    titles = sum(1 for v in r["list"] if v["vod_name"] and not v["vod_name"] == v["vod_id"])
    check("titles", titles == len(r["list"]), "%d/%d" % (titles, len(r["list"])))

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

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

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

    if r["list"]:
        vid = r["list"][0]["vod_id"]
        d = sp.detailContent([vid])
        v = d["list"][0]
        has_url = v["vod_play_url"].startswith("正片$http")
        check("detail", v["vod_name"] != vid and has_url and v["vod_pic"].startswith("http"),
              "%s | 封面%s | 直链%s" % (v["vod_name"][:25],
                  "有" if v["vod_pic"] else "无", "有" if has_url else "无"))
        if has_url:
            ep = v["vod_play_url"].split("$", 1)[1]
            p = sp.playerContent("在线播放", ep, [])
            check("player", p["parse"] == 0 and isinstance(p.get("header"), dict)
                  and "playUrl" not in p, p["url"][:70])
    else:
        check("detail", False, "无列表跳过")

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