# 汤头条
# MacCMS 模板站，当前活镜像 cyb.ttt5.best（域名会轮换，失效时找新镜像）
# 游客直拉视频页拿明文 m3u8：const rawUrl = '<m3u8>'，无登录、无签名、无 VIP 墙
# 12 分类 /vodtype/<id>-<pg>.html，72 条/页；搜索 /s/<关键词>.html
# 列表无时长，备注为空；详情页无封面，封面取列表缓存
# 注意：fqm3u8.cc 型清单含约 28 秒广告分片（开头+中间），可接受
try:
    from base.spider import Spider as BaseSpider
except Exception:
    try:
        from base.spider import BaseSpider
    except Exception:
        class BaseSpider(object):
            pass

import gzip
import re
import urllib.parse
import urllib.request
import zlib
from http.client import IncompleteRead

BASE = "https://cyb.ttt5.best"
FALLBACKS = ["https://ttt5.best", "https://www.ttt5.best"]

UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"

# 分类 id: 名称
CATS = [
    ("20", "国产自拍"),
    ("21", "制服丝袜"),
    ("22", "强奸乱伦"),
    ("23", "教师学生"),
    ("24", "素人系列"),
    ("25", "人妻熟女"),
    ("26", "日韩无码"),
    ("27", "日韩有码"),
    ("28", "中文字幕"),
    ("29", "欧美风情"),
    ("30", "经典伦理"),
    ("31", "卡通动漫"),
]

PAGE_SIZE = 72


class Spider(BaseSpider):
    def __init__(self):
        self._base = BASE
        self._cache = {}  # vod_id -> {name, pic}

    def getName(self):
        return "汤头条"

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

    # ---------- http ----------
    def _http(self, url, retry=3):
        last = None
        for _ in range(retry):
            try:
                req = urllib.request.Request(url, headers={
                    "User-Agent": UA,
                    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
                    "Accept-Language": "zh-CN,zh;q=0.9",
                    "Accept-Encoding": "gzip, deflate",
                    "Referer": self._base + "/",
                    "Connection": "keep-alive",
                })
                with urllib.request.urlopen(req, timeout=20) as r:
                    raw = r.read()
            except IncompleteRead as e:
                raw = e.partial
            except Exception as e:
                last = e
                continue
            try:
                if raw[:2] == b"\x1f\x8b":
                    try:
                        raw = gzip.decompress(raw)
                    except Exception:
                        raw = zlib.decompress(raw, 47)
            except Exception:
                pass
            try:
                return raw.decode("utf-8", "ignore")
            except Exception:
                return raw.decode("utf-8", "ignore")
        return ""

    def _get(self, path):
        """先主基址，不行换 fallback。"""
        html = self._http(self._base + path)
        if html and "video-pic" in html:
            return html
        for b in FALLBACKS:
            html = self._http(b + path)
            if html and "video-pic" in html:
                self._base = b
                return html
        return html or ""

    # ---------- 解析 ----------
    def _parse_list(self, html):
        items = []
        for pic, href, title in re.findall(
            r'<a class="video-pic[^"]*"[^>]*data-original="([^"]+)"[^>]*href="([^"]+)"[^>]*title="([^"]*)"',
            html,
        ):
            m = re.search(r"/(\d+)\.html", href)
            if not m:
                continue
            vid = m.group(1)
            title = title.strip()
            if not title:
                continue
            items.append({
                "vod_id": vid,
                "vod_name": title,
                "vod_pic": pic.strip(),
                "vod_remarks": "",
            })
            self._cache[vid] = {"name": title, "pic": pic.strip()}
        # 去重保序
        seen = set()
        out = []
        for it in items:
            if it["vod_id"] not in seen:
                seen.add(it["vod_id"])
                out.append(it)
        return out

    def _pagecount(self, html, catid):
        # 尾页链接 /vodtype/<id>-<N>.html
        pages = re.findall(r"vodtype/%s-(\d+)\.html" % catid, html)
        if pages:
            return max(int(p) for p in pages)
        return 1

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

    def homeVideoContent(self):
        # 首页第一块“最近更新”72 条
        html = self._get("/cn/home/web/")
        items = self._parse_list(html)[:PAGE_SIZE]
        return {"list": items}

    def categoryContent(self, tid, pg, filter, extend):
        pg = int(pg or 1)
        html = self._get("/vodtype/%s-%d.html" % (tid, pg))
        items = self._parse_list(html)
        return {
            "list": items,
            "page": pg,
            "pagecount": self._pagecount(html, tid),
            "limit": PAGE_SIZE,
            "total": 999999,
        }

    def detailContent(self, ids):
        vid = ids[0] if isinstance(ids, list) else ids
        html = self._http(self._base + "/%s.html" % vid)
        if not html or "rawUrl" not in html:
            html = self._get("/%s.html" % vid)
        name = ""
        m = re.search(r"<title>(.*?)</title>", html, re.S)
        if m:
            name = re.sub(r"\s*-\s*汤头条\s*$", "", m.group(1).strip())
        if not name:
            name = self._cache.get(vid, {}).get("name", vid)
        pic = self._cache.get(vid, {}).get("pic", "")
        m = re.search(r"const rawUrl\s*=\s*'([^']+)'", html)
        play_url = m.group(1).strip() if m else ""
        vod = {
            "vod_id": vid,
            "vod_name": name,
            "vod_pic": pic,
            "vod_play_from": "汤头条",
            "vod_play_url": "正片$" + play_url if play_url else "",
        }
        return {"list": [vod]}

    def playerContent(self, flag, id, vipFlags):
        # id 是 detail 给的播放地址，现取现播不缓存
        url = id
        if url.startswith("http"):
            return {"parse": 0, "url": url, "header": {"User-Agent": UA}}
        # 兜底：id 是视频 id 时现拉详情页
        vid = url.split("$")[-1] if "$" in url else url
        html = self._http(self._base + "/%s.html" % vid)
        m = re.search(r"const rawUrl\s*=\s*'([^']+)'", html)
        if m:
            return {"parse": 0, "url": m.group(1).strip(), "header": {"User-Agent": UA}}
        return {"parse": 0, "url": url, "header": {"User-Agent": UA}}

    def searchContent(self, key, quick, pg="1"):
        pg = int(pg or 1)
        q = urllib.parse.quote(key)
        if pg <= 1:
            path = "/s/%s.html" % q
        else:
            path = "/s/%s-%d.html" % (q, pg)
        html = self._get(path)
        items = self._parse_list(html)
        # 搜索页不给总页数：满页时允许再翻一页
        pagecount = pg + 1 if len(items) >= PAGE_SIZE else pg
        return {
            "list": items,
            "page": pg,
            "pagecount": pagecount,
            "limit": PAGE_SIZE,
            "total": 999999,
        }

    def isVideoFormat(self, url):
        pass

    def manualVideoCheck(self):
        pass

    def localProxy(self, param):
        pass
