# -*- coding: utf-8 -*-
# pektino - https://pektino.com/zh-CN
# Twitter 短视频聚合站
# 列表: /zh-CN/{daily|weekly|monthly|all}，翻页 ?page=
# 卡片: a[href="/zh-CN/movies/{vid}"] 或 /shorts/（详情页 canonical 是单数 /movie/）
# 播放: 详情页明文给出 video.twimg.com 的 mp4（JSON-LD contentUrl / 播放遮罩 <a href>）
# 连刷: feed_stream 分类，点进拼 150 集选集，feed_fetch@@ 懒加载

import re
import sys
import os
import ssl
import json
import time
import random
sys.path.insert(0, os.path.dirname(__file__))

try:
    from base.spider import Spider as BaseSpider
except ImportError:
    from spider import Spider as BaseSpider


class Spider(BaseSpider):
    def getName(self):
        return "pektino"

    def init(self, extend=""):
        self.host = "https://pektino.com"
        self.ua = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
        self.headers = {
            "User-Agent": self.ua,
            "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-US;q=0.8,en;q=0.7",
            "Referer": self.host + "/zh-CN",
        }
        self.ctx = ssl.create_default_context()
        self.ctx.check_hostname = False
        self.ctx.verify_mode = ssl.CERT_NONE
        self.cats = [
            ("feed_stream", "🔥 沉浸连刷"),
            ("daily", "每日精选"),
            ("weekly", "每周热门"),
            ("monthly", "每月排行"),
            ("all", "历史最佳"),
        ]
        self.sections = ["weekly", "monthly", "all", "daily"]
        self.style = {"type": "rect", "ratio": 1.78}

    # ---------- 抓取：双通道 + 内容校验 ----------
    def _get(self, url, expect=(), timeout=10):
        """先走 App 自带的 fetch，再走 urllib 直抓；
        expect 是页面必备标记（如详情页必含 video.twimg.com），
        抓到坏页（验证墙/空页）就当没抓到，自动换通道再试"""
        if isinstance(expect, str):
            expect = (expect,)
        cands = []
        try:
            r = self.fetch(url, headers=self.headers)
            t = r.text or ""
            if t:
                cands.append(t)
        except Exception:
            pass
        try:
            import urllib.request
            for _ in range(2):
                try:
                    req = urllib.request.Request(url, headers=self.headers)
                    with urllib.request.urlopen(req, timeout=timeout, context=self.ctx) as resp:
                        t = resp.read().decode("utf-8", errors="ignore")
                        if t:
                            cands.append(t)
                        break
                except Exception:
                    time.sleep(0.2)
        except Exception:
            pass
        for t in cands:
            if len(t) > 1000 and (not expect or any(k in t for k in expect)):
                return t
        best = max(cands, key=len) if cands else ""
        return best if len(best) > 1000 else ""

    def _movie_url(self, vid):
        # 站内 canonical 是单数 /movie/，优先用它
        return "%s/zh-CN/movie/%s" % (self.host, vid)

    def _section_url(self, sec, pg=1):
        base = "%s/zh-CN" % self.host if sec == "daily" else "%s/zh-CN/%s" % (self.host, sec)
        return base if pg <= 1 else "%s?page=%s" % (base, pg)

    # ---------- 解析 ----------
    def _pic(self, url):
        if not url:
            return ""
        if url.startswith("//"):
            url = "https:" + url
        if "twimg.com" in url:
            from urllib.parse import quote
            return "https://wsrv.nl/?url=%s" % quote(url, safe="")
        return url

    def _cards(self, html):
        vods = []
        seen = set()
        for m in re.finditer(
            r'<a[^>]+href="([^"]*(?:/zh-CN)?/(?:movies?|shorts)/([^"/]+)/?)"[^>]*>(.*?)</a>',
            html, re.S | re.I,
        ):
            href, vid, block = m.groups()
            if vid in seen:
                continue
            seen.add(vid)
            pm = re.search(r'(?:src|data-src|poster)="([^"]+)"', block, re.I)
            pic = self._pic(pm.group(1)) if pm else ""
            dm = re.search(r'(\d+:\d+(?::\d+)?)', block)
            dur = dm.group(1) if dm else ""
            am = re.search(r'alt="([^"]+)"', block)
            title = am.group(1).replace("X (Twitter) adult video ", "").strip() if am else vid
            if title == vid:
                title = "影片 " + vid
            vods.append({
                "vod_id": vid,
                "vod_name": title,
                "vod_pic": pic,
                "vod_remarks": dur,
            })
        return vods

    def _stream(self, html, vid=""):
        """详情页明文提取 video.twimg.com 的 mp4"""
        if not html:
            return ""
        clean = html.replace(r'\/', '/').replace('\\"', '"').replace('\\\\', '\\')
        mp4s = re.findall(r'(https?://video\.twimg\.com/[^"\'\s<>\\]+\.mp4(?:\?[^"\'\s<>\\]*)?)', clean)
        valid = []
        for u in mp4s:
            u = u.replace('\\', '').strip()
            if u.startswith("http") and u not in valid:
                valid.append(u)
        if vid:
            for u in valid:
                if vid in u:
                    return u
        return valid[0] if valid else ""

    def _stream_of(self, vid):
        """拿一个 vid 的可播直链，单数/复数详情页都试"""
        html = self._get(self._movie_url(vid), expect="video.twimg.com")
        u = self._stream(html, vid)
        if u:
            return u
        html = self._get("%s/zh-CN/movies/%s" % (self.host, vid), expect="video.twimg.com")
        return self._stream(html, vid)

    def _fallback_stream(self):
        """实在解不出就从 weekly 捞一条现成的，保证不返回空地址"""
        try:
            html = self._get("%s/zh-CN/weekly" % self.host, expect=("movies/", "shorts/"))
            for c in self._cards(html)[:5]:
                u = self._stream_of(c["vod_id"])
                if u:
                    return u
        except Exception:
            pass
        return ""

    # ---------- TVBox 接口 ----------
    def homeContent(self, filter):
        cats = [{"type_id": tid, "type_name": name} for tid, name in self.cats]
        return {"class": cats, "list": []}

    def homeVideoContent(self):
        return {"list": []}

    def _item(self, c):
        d = {
            "vod_id": c["vod_id"],
            "vod_name": c["vod_name"],
            "vod_pic": c["vod_pic"],
            "vod_remarks": c["vod_remarks"],
        }
        return d

    def categoryContent(self, tid, pg, filter, extend):
        pg = int(pg) if str(pg).isdigit() else 1
        if tid == "feed_stream":
            secs = self.sections[:]
            random.shuffle(secs)
            cards = []
            for sec in secs:
                html = self._get(self._section_url(sec, random.randint(1, 5)),
                                 expect=("movies/", "shorts/"))
                cards = self._cards(html)
                if cards:
                    break
            if not cards:
                cards = self._cards(self._get("%s/zh-CN" % self.host, expect=("movies/", "shorts/")))
            random.shuffle(cards)
            items = [{
                "vod_id": "feed@@%s" % c["vod_id"],
                "vod_name": c["vod_name"],
                "vod_pic": c["vod_pic"],
                "vod_remarks": "连刷起播",
            } for c in cards[:40]]
            return {"list": items, "page": 1, "pagecount": 1, "limit": 40, "total": 40}
        html = self._get(self._section_url(tid, pg), expect=("movies/", "shorts/"))
        items = [self._item(c) for c in self._cards(html)]
        return {"list": items, "page": pg, "pagecount": 999, "limit": 20, "total": 9999}

    def detailContent(self, ids):
        raw = ids[0]
        # ---- 沉浸连刷：150 集选集 ----
        if raw.startswith("feed@@"):
            start_vid = raw.split("@@", 1)[1]
            stream = self._stream_of(start_vid)
            pool, seen = [], {start_vid}
            tasks = []
            for sec in self.sections:
                for p in random.sample(range(1, 8), 2):
                    tasks.append((sec, p))
            random.shuffle(tasks)
            for sec, p in tasks:
                html = self._get(self._section_url(sec, p), expect=("movies/", "shorts/"))
                for c in self._cards(html):
                    if c["vod_id"] not in seen:
                        seen.add(c["vod_id"])
                        pool.append(c["vod_id"])
                if len(pool) >= 150:
                    break
            random.shuffle(pool)
            first = stream if stream else "feed_fetch@@%s" % start_vid
            episodes = ["$%s" % first]
            for v in pool[:150]:
                episodes.append("$feed_fetch@@%s" % v)
            return {"list": [{
                "vod_id": raw,
                "vod_name": "🔥 沉浸连刷",
                "vod_pic": "",
                "vod_play_from": "pektino",
                "vod_play_url": "#".join(episodes),
            }]}
        # ---- 普通详情 ----
        vid = raw
        html = self._get(self._movie_url(vid), expect="video.twimg.com")
        if not html:
            html = self._get("%s/zh-CN/movies/%s" % (self.host, vid), expect="video.twimg.com")
        m = re.search(r'<title>([^<]+)</title>', html)
        title = m.group(1).split(" - ")[0].strip() if m else "影片"
        pm = re.search(r'property="og:image"\s+content="([^"]+)"', html)
        pic = self._pic(pm.group(1)) if pm else ""
        stream = self._stream(html, vid)
        target = stream if stream else "rec_fetch@@%s" % vid
        episodes = ["正片$%s" % target]
        idx = 1
        for c in self._cards(html):
            if c["vod_id"] != vid and idx <= 30:
                t = c["vod_name"].replace("$", "").replace("#", "")[:16]
                episodes.append("%02d·%s$rec_fetch@@%s" % (idx, t, c["vod_id"]))
                idx += 1
        return {"list": [{
            "vod_id": vid,
            "vod_name": title,
            "vod_pic": pic,
            "vod_play_from": "pektino",
            "vod_play_url": "#".join(episodes),
        }]}

    def playerContent(self, flag, id, vipFlags):
        raw = str(id).strip()
        url = ""
        if "@@" in raw:
            # feed_fetch@@ / rec_fetch@@ / fetch@@：懒加载解直链
            url = self._stream_of(raw.split("@@", 1)[1])
        elif raw.startswith("http"):
            url = raw
        else:
            url = self._stream_of(raw)
        if not url:
            # 宁可从 weekly 捞一条能播的，也不返回空地址
            url = self._fallback_stream()
        return {
            "parse": 0,
            "playUrl": "",
            "url": url,
            "header": json.dumps({"User-Agent": self.ua}),
        }

    def searchContent(self, key, quick, pg="1"):
        from urllib.parse import quote
        pg = int(pg) if str(pg).isdigit() else 1
        url = "%s/zh-CN/search?tag=%s" % (self.host, quote(key))
        if pg > 1:
            url += "&page=%s" % pg
        items = [self._item(c) for c in self._cards(self._get(url, expect=("movies/", "shorts/")))]
        return {"list": items, "page": pg, "pagecount": 999, "limit": 24, "total": 9999}

    def isVideoFormat(self, url):
        return False

    def manualVideoCheck(self):
        return False

    def localProxy(self, param):
        return [404, "text/plain", b"", {}]

    def destroy(self):
        pass
