# -*- coding: utf-8 -*-
import re
import sys
import json
import gzip
import html as html_mod
import http.client
import http.cookiejar
import urllib.request
import urllib.parse
import urllib.error

sys.path.append('..')
try:
    from base.spider import Spider as BaseSpider
except Exception:
    class BaseSpider:
        def __init__(self):
            pass


# 站点结构（2026-10-24 实测，bdsmstreak.com，自托管 tube）：
# - 分类：/categories 索引页现抓（44 个 /c/{slug}，名称在锚点内的
#   font-semibold span 里）；另加「最新」伪分类走首页
# - 列表：分类页 /c/{slug}?page={n}，每页 48 卡；分页器带末页号，
#   pagecount 取分页链接最大页码。首页只有最新一页（无分页）
# - 卡片：<a href="/video/{id}/{slug}">，封面 img（v3 子域
#   /media/videos/tmb/{id}/1.jpg 直链 JPEG），标题在 img alt / h3，
#   时长在 duration-pill span。卡片里的 -preview.mp4 是悬停预览，
#   不是正片，别拿它当播放地址
# - 详情：视频页 <title> + og:image；播放源在 <source src> /
#   og:video —— cdn1.mespeaks.com/{id}.mp4 直链 mp4
# - 搜索：GET /search?q={词}，翻页 ?q={词}&page={n}
# - 播放：player 现抓视频页取 source 地址，普通 GET 读前缀验
#   ftyp 后 parse=0；取不到退视频页 parse=1


class Spider(BaseSpider):
    def getName(self):
        return 'BDSMStreak'

    def init(self, extend=''):
        self.host = 'https://bdsmstreak.com'
        if extend:
            try:
                cfg = json.loads(extend) if isinstance(extend, str) else extend
                if isinstance(cfg, dict) and cfg.get('host'):
                    self.host = str(cfg['host']).rstrip('/')
            except Exception:
                pass
        self.ua = ('Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
                   'AppleWebKit/537.36 (KHTML, like Gecko) '
                   'Chrome/126.0.0.0 Safari/537.36')
        self.headers = {'User-Agent': self.ua,
                        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8'}
        self.cj = http.cookiejar.CookieJar()
        self.opener = urllib.request.build_opener(
            urllib.request.HTTPCookieProcessor(self.cj))
        self.classes_cache = None
        self._truncated = False

    # ---------- 基础工具 ----------
    def _clean(self, s):
        s = html_mod.unescape(s or '')
        s = re.sub(r'<!--.*?-->', '', s, flags=re.S)
        s = re.sub(r'<[^>]+>', '', s)
        return re.sub(r'\s+', ' ', s).strip()

    def _fetch(self, url, referer='', timeout=30):
        # chunked 响应偶发截断（IncompleteRead）：多抓几次取最完整一份
        best = ''
        for attempt in range(3):
            text = self._fetch_once(url, referer, timeout)
            if len(text) > len(best):
                best = text
            if text and not self._truncated:
                return text
        return best

    def _fetch_once(self, url, referer='', timeout=30):
        headers = {'User-Agent': self.ua,
                   'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8'}
        if referer:
            headers['Referer'] = referer
        data = b''
        self._truncated = False
        try:
            req = urllib.request.Request(url, headers=headers)
            r = self.opener.open(req, timeout=timeout)
            try:
                data = r.read()
            except http.client.IncompleteRead as e:
                data = e.partial or b''
                self._truncated = True
            finally:
                r.close()
        except urllib.error.HTTPError as e:
            try:
                data = e.read()
            except http.client.IncompleteRead as e2:
                data = e2.partial or b''
                self._truncated = True
            except Exception:
                data = b''
        except Exception:
            return ''
        try:
            if data[:2] == b'\x1f\x8b':
                data = gzip.decompress(data)
            return data.decode('utf-8', 'ignore')
        except Exception:
            return ''

    def _probe_media(self, url, referer='', timeout=12):
        """普通 GET 读头部字节判媒体：HLS 看 #EXTM3U，mp4 看 ftyp。"""
        try:
            headers = {'User-Agent': self.ua}
            if referer:
                headers['Referer'] = referer
            req = urllib.request.Request(url, headers=headers)
            r = self.opener.open(req, timeout=timeout)
            try:
                head = r.read(1024)
            finally:
                r.close()
            if head.lstrip().startswith(b'#EXTM3U'):
                return True
            return len(head) >= 8 and head[4:8] == b'ftyp'
        except Exception:
            return False

    # ---------- 卡片解析 ----------
    def _parse_cards(self, html):
        cards = []
        if not html:
            return cards
        anchors = list(re.finditer(r'href="(/video/(\d+)/[a-z0-9-]+)"', html))
        seen = set()
        for i, m in enumerate(anchors):
            vid = m.group(2)
            if vid in seen:
                continue
            seen.add(vid)
            end = anchors[i + 1].start() if i + 1 < len(anchors) else len(html)
            seg = html[m.start():min(end, m.start() + 4000)]
            pm = re.search(r'<img[^>]+src="(https?://[^"]+)"[^>]*alt="([^"]*)"', seg)
            if not pm:
                pm = re.search(r'<img[^>]+alt="([^"]*)"[^>]*src="(https?://[^"]+)"', seg)
                if pm:
                    pic, title = pm.group(2), pm.group(1)
                else:
                    pic, title = '', ''
            else:
                pic, title = pm.group(1), pm.group(2)
            if not title:
                tm = re.search(r'<h3[^>]*>([^<]+)</h3>', seg)
                title = tm.group(1) if tm else ''
            title = self._clean(title)
            if not title:
                continue
            dm = re.search(r'duration-pill">(\d{1,2}:\d{2}(?::\d{2})?)<', seg)
            cards.append({
                'vod_id': m.group(1),
                'vod_name': title,
                'vod_pic': pic,
                'vod_remarks': dm.group(1) if dm else '',
                'style': {'type': 'rect', 'ratio': 1.78},
            })
        return cards

    def _pagecount(self, html, pg, cards, per_page=48):
        nums = [int(x) for x in re.findall(r'[?&]page=(\d+)', html or '')]
        if nums:
            return max(nums + [pg])
        return pg + 1 if len(cards) >= per_page else pg

    # ---------- 接口 ----------
    def _classes(self):
        if self.classes_cache:
            return self.classes_cache
        cats = [{'type_id': 'latest', 'type_name': '最新视频'}]
        seen = {'latest'}
        html = self._fetch(self.host + '/categories')
        if not html:
            html = self._fetch(self.host + '/')
        for m in re.finditer(r'href="(/c/[a-z0-9-]+)"', html or ''):
            slug = m.group(1)
            if slug in seen:
                continue
            seg = html[m.end():m.end() + 600]
            nm = re.search(r'font-semibold[^>]*>([^<]+)<', seg)
            name = self._clean(nm.group(1)) if nm else slug[3:].replace('-', ' ').title()
            seen.add(slug)
            cats.append({'type_id': slug, 'type_name': name})
        self.classes_cache = cats
        return cats

    def homeContent(self, filter):
        return {'class': self._classes(), 'filters': {}}

    def homeVideoContent(self):
        html = self._fetch(self.host + '/')
        return {'list': self._parse_cards(html)}

    def categoryContent(self, tid, pg, filter, extend):
        try:
            pg = int(pg)
        except Exception:
            pg = 1
        if pg < 1:
            pg = 1
        tid = str(tid)
        if tid == 'latest':
            if pg > 1:
                return {'list': [], 'page': pg, 'pagecount': 1,
                        'limit': 0, 'total': 0}
            html = self._fetch(self.host + '/')
            cards = self._parse_cards(html)
            return {'list': cards, 'page': 1, 'pagecount': 1,
                    'limit': len(cards), 'total': len(cards)}
        if not tid.startswith('/c/'):
            tid = '/c/' + tid.strip('/')
        url = self.host + tid + (('?page=%d' % pg) if pg > 1 else '')
        html = self._fetch(url, referer=self.host + '/')
        cards = self._parse_cards(html)
        pc = self._pagecount(html, pg, cards)
        return {'list': cards, 'page': pg, 'pagecount': pc,
                'limit': len(cards), 'total': pc * max(len(cards), 1)}

    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?q=%s' % (self.host, kw)
        if pg > 1:
            url += '&page=%d' % pg
        html = self._fetch(url, referer=self.host + '/')
        cards = self._parse_cards(html)
        pc = self._pagecount(html, pg, cards)
        return {'list': cards, 'page': pg, 'pagecount': pc,
                'limit': len(cards), 'total': pc * max(len(cards), 1)}

    def detailContent(self, ids):
        if isinstance(ids, (list, tuple)):
            vpath = str(ids[0]) if ids else ''
        else:
            vpath = str(ids)
        if not vpath:
            return {'list': []}
        if not vpath.startswith('/'):
            vpath = '/' + vpath
        page = self.host + vpath
        html = self._fetch(page, referer=self.host + '/')
        title = ''
        pic = ''
        desc = ''
        if html:
            tm = re.search(r'<title>([^<]+)</title>', html)
            if tm:
                title = re.sub(r'\s*-\s*Bdsmstreak\s*$', '',
                               self._clean(tm.group(1))).strip()
            pm = re.search(r'property="og:image" content="([^"]+)"', html)
            if pm:
                pic = pm.group(1)
            dm = re.search(r'name="description" content="([^"]+)"', html)
            if dm:
                desc = self._clean(dm.group(1))
        if not title:
            slug = vpath.rstrip('/').split('/')[-1]
            title = slug.replace('-', ' ').title()
        m = re.search(r'/video/(\d+)/', vpath)
        play = 'https://cdn1.mespeaks.com/%s.mp4' % m.group(1) if m else page
        vod = {
            'vod_id': vpath,
            'vod_name': title,
            'vod_pic': pic,
            'vod_content': desc,
            'vod_play_from': 'BDSMStreak',
            'vod_play_url': '正片$%s' % play,
        }
        return {'list': [vod]}

    def playerContent(self, flag, id, vipFlags):
        url = str(id)
        header = {'User-Agent': self.ua, 'Referer': self.host + '/'}
        # detail 给的是公式直链；先探活，活了直接 parse=0
        if 'mespeaks.com' in url and self._probe_media(url, referer=self.host + '/'):
            return {'parse': 0, 'jx': 0, 'url': url, 'header': header}
        # 兜底：抓视频页取 <source src> / og:video 现解再探活
        page = url if '/video/' in url else ''
        if page:
            html = self._fetch(page, referer=self.host + '/')
            if html:
                cands = re.findall(r'<source[^>]+src="(https?://[^"]+)"', html)
                og = re.search(r'property="og:video(?::secure_url)?" content="(https?://[^"]+)"', html)
                if og:
                    cands.insert(0, og.group(1))
                for u in cands:
                    u = html_mod.unescape(u)
                    if '-preview' in u:
                        continue
                    if self._probe_media(u, referer=page):
                        return {'parse': 0, 'jx': 0, 'url': u,
                                'header': {'User-Agent': self.ua, 'Referer': page}}
            return {'parse': 1, 'jx': 1, 'url': page, 'header': header}
        return {'parse': 1, 'jx': 1, 'url': url, 'header': header}

    def isVideoFormat(self, url):
        u = (url or '').lower()
        return '.m3u8' in u or '.mp4' in u

    def localProxy(self, params):
        # 只返 3 段 [状态码, mime, bytes]
        try:
            if isinstance(params, dict) and params.get('type') == 'pic':
                url = params.get('url', '')
                if url:
                    req = urllib.request.Request(
                        url, headers={'User-Agent': self.ua,
                                      'Referer': self.host + '/'})
                    r = self.opener.open(req, timeout=15)
                    try:
                        raw = r.read()
                    finally:
                        r.close()
                    if raw[:3] == b'\xff\xd8\xff':
                        return [200, 'image/jpeg', raw]
                    if raw[:8] == b'\x89PNG\r\n\x1a\n':
                        return [200, 'image/png', raw]
                    if raw[:4] == b'RIFF' and raw[8:12] == b'WEBP':
                        return [200, 'image/webp', raw]
        except Exception:
            pass
        return [404, 'text/plain', b'']

    def destroy(self):
        pass
