# -*- coding: utf-8 -*-
import re
import sys
import gzip
import html as html_mod
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-23 实测，zh.xhamster2.com，Nuxt SSR）：
# - 必须用桌面 UA：移动 UA 的列表页 SSR 只吐个位数卡片，桌面 UA 才给整页
# - 分类：/categories 索引页 34 个，列表 /categories/{slug}、翻页 /categories/{slug}/{n}
# - 搜索：/search/{词}?page={n}
# - 卡片：div.thumb-list__item.video-thumb--type-video[data-video-id]，内含
#   a[data-role=thumb-link] href + aria-label 标题、img src 封面（webp 直链）、
#   div[data-role=video-duration] 时长
# - 详情/播放：视频页 <head> 有 <link rel="preload" href="...m3u8"> 即 HLS 主清单
#   （签名地址、带 Referer 普通 GET 实测 #EXTM3U）；页内 sources 是加密串不用管
# - 总页数在页内 JSON：paginationProps.lastPageNumber
FALLBACK_CATS = [
    ('amateur', '素人'), ('mature', '成熟'), ('homemade', '家庭自制'),
    ('anal', '肛交'), ('18-year-old', '18岁'), ('granny', '奶奶'),
    ('bbw', '胖美女'), ('american', '美国人'), ('lesbian', '女同'),
    ('asian', '亚洲人'), ('mom', '人母'), ('creampie', '内射'),
    ('3d', '3D'), ('show', 'Show'), ('interactive', '互动'),
    ('cartoon', '卡通'), ('compilation', '合集'), ('softcore', '唯美'),
    ('vintage', '复古'), ('caption', '字幕'), ('behind-the-scenes', '幕后花絮'),
    ('retro', '怀旧'), ('hentai', '成人动漫'), ('funny', '搞笑'),
    ('story', '故事'), ('gonzo', '无剧情'), ('uncensored', '无码'),
    ('jav', '日本AV'), ('close-up', '特写'), ('webcam', '直播'),
]


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

    def init(self, extend=''):
        self.host = 'https://zh.xhamster2.com'
        if extend:
            try:
                import json
                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
        # 桌面 UA 是硬要求（见文件头注释）
        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',
                        'Referer': self.host + '/'}
        self.cj = http.cookiejar.CookieJar()
        self.opener = urllib.request.build_opener(
            urllib.request.HTTPCookieProcessor(self.cj))
        self.classes_cache = None

    # ---------- 基础工具 ----------
    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=25):
        headers = dict(self.headers)
        if referer:
            headers['Referer'] = referer
        data = b''
        try:
            req = urllib.request.Request(url, headers=headers)
            r = self.opener.open(req, timeout=timeout)
            try:
                data = r.read()
            finally:
                r.close()
        except urllib.error.HTTPError as e:
            try:
                data = e.read()
            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(self, url, referer='', timeout=12):
        """普通 GET 读开头字节探活（m3u8 验 #EXTM3U）。"""
        headers = {'User-Agent': self.ua}
        if referer:
            headers['Referer'] = referer
        try:
            req = urllib.request.Request(url, headers=headers)
            r = self.opener.open(req, timeout=timeout)
            try:
                return r.read(1024)
            finally:
                r.close()
        except Exception:
            return b''

    # ---------- 列表解析 ----------
    @staticmethod
    def _jstr(s):
        """解 JSON 字符串片段的转义（\\/ 与 \\uXXXX）。"""
        try:
            import json
            return json.loads('"%s"' % s)
        except Exception:
            return s.replace('\\/', '/')

    @staticmethod
    def _fmt_dur(sec):
        try:
            sec = int(sec)
        except Exception:
            return ''
        if sec >= 3600:
            return '%d:%02d:%02d' % (sec // 3600, (sec % 3600) // 60, sec % 60)
        return '%d:%02d' % (sec // 60, sec % 60)

    def _parse_cards(self, html):
        # 主路：页内 JSON 的视频对象（SSR 只渲染前几张卡的 HTML，其余是
        # 骨架占位；JSON 里 id/duration/title/pageURL/thumbURL 都是全的）
        cards, seen = [], set()
        if not html:
            return cards
        for m in re.finditer(r'"id":(\d+),"duration":(\d+)', html):
            vid = m.group(1)
            if vid in seen:
                continue
            seg = html[m.start():m.start() + 1200]
            um = re.search(r'"pageURL":"((?:[^"\\]|\\.)*)"', seg)
            tm = re.search(r'"title":"((?:[^"\\]|\\.)*)"', seg)
            pm = re.search(r'"thumbURL":"((?:[^"\\]|\\.)*)"', seg)
            if not um or not tm:
                continue
            page = self._jstr(um.group(1))
            if '/videos/' not in page:
                continue
            seen.add(vid)
            cards.append({
                'vod_id': page,
                'vod_name': self._clean(self._jstr(tm.group(1))),
                'vod_pic': self._jstr(pm.group(1)) if pm else '',
                'vod_remarks': self._fmt_dur(m.group(2)),
                'style': {'type': 'rect', 'ratio': 1.78},
            })
        if len(cards) >= 5:
            return cards
        # 兜底：HTML 卡片（只前几张有图，其余骨架卡也要标题/链接）
        cards, seen = [], set()
        for m in re.finditer(
                r'video-thumb--type-video"[^>]*data-video-id="(\d+)"', html):
            vid = m.group(1)
            if vid in seen:
                continue
            seg = html[m.start():m.start() + 7000]
            am = re.search(r'href="(https?://[^"]+/videos/[^"]+)"', seg)
            tm = re.search(r'aria-label="([^"]+)"', seg)
            if not am or not tm:
                continue
            seen.add(vid)
            pm = re.search(r'<img[^>]+src="([^"]+)"', seg)
            dm = re.search(r'data-role="video-duration">(.*?)</div>', seg, re.S)
            cards.append({
                'vod_id': am.group(1),
                'vod_name': self._clean(tm.group(1)),
                'vod_pic': pm.group(1) if pm else '',
                'vod_remarks': self._clean(dm.group(1)) if dm else '',
                'style': {'type': 'rect', 'ratio': 1.78},
            })
        return cards

    def _last_page(self, html, default=0):
        m = re.search(r'"lastPageNumber"\s*:\s*(\d+)', html or '')
        return int(m.group(1)) if m else default

    def _classes(self):
        if self.classes_cache:
            return self.classes_cache
        cats = []
        html = self._fetch(self.host + '/categories')
        for m in re.finditer(
                r'href="https?://[^"]+/categories/([a-z0-9-]+)"[^>]*>'
                r'(?:(?!</a>).)*?<img[^>]+alt="([^"]+)"', html or '', re.S):
            slug, name = m.group(1), self._clean(m.group(2))
            if slug and name and all(c['type_id'] != slug for c in cats):
                cats.append({'type_id': slug, 'type_name': name})
        if len(cats) < 10:
            cats = [{'type_id': s, 'type_name': n} for s, n in FALLBACK_CATS]
        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
        url = '%s/categories/%s' % (self.host, tid)
        if pg > 1:
            url += '/%d' % pg
        html = self._fetch(url)
        cards = self._parse_cards(html)
        last = self._last_page(html)
        pagecount = last if last >= pg else (pg + 1 if cards else pg)
        return {'list': cards, 'page': pg, 'pagecount': pagecount,
                'limit': len(cards), 'total': pagecount * len(cards)}

    def searchContent(self, key, quick, pg='1'):
        try:
            pg = int(pg)
        except Exception:
            pg = 1
        if pg < 1:
            pg = 1
        url = '%s/search/%s' % (self.host, urllib.parse.quote(str(key)))
        if pg > 1:
            url += '?page=%d' % pg
        html = self._fetch(url)
        cards = self._parse_cards(html)
        last = self._last_page(html)
        pagecount = last if last >= pg else (pg + 1 if cards else pg)
        return {'list': cards, 'page': pg, 'pagecount': pagecount,
                'limit': len(cards), 'total': pagecount * len(cards)}

    def detailContent(self, ids):
        if isinstance(ids, (list, tuple)):
            page_url = str(ids[0]) if ids else ''
        else:
            page_url = str(ids)
        if not page_url:
            return {'list': []}
        html = self._fetch(page_url)
        tm = re.search(r'property="og:title" content="([^"]+)"', html or '')
        pm = re.search(r'property="og:image" content="([^"]+)"', html or '')
        remarks = ''
        xi = (html or '').find('xplayerSettings')
        if xi >= 0:
            dm = re.search(r'"duration"\s*:\s*(\d+)', html[xi:xi + 2000])
            if dm:
                remarks = self._fmt_dur(dm.group(1))
        vod = {
            'vod_id': page_url,
            'vod_name': self._clean(tm.group(1)) if tm else page_url,
            'vod_pic': pm.group(1) if pm else '',
            'vod_remarks': remarks,
            'vod_play_from': 'HLS',
            'vod_play_url': '正片$%s' % page_url,
        }
        return {'list': [vod]}

    def playerContent(self, flag, id, vipFlags):
        url = str(id)
        header = {'User-Agent': self.ua, 'Referer': url}
        if '.m3u8' in url or '.mp4' in url:
            return {'parse': 0, 'jx': 0, 'url': url,
                    'header': {'User-Agent': self.ua,
                               'Referer': self.host + '/'}}
        html = self._fetch(url, referer=self.host + '/')
        m3u8 = ''
        m = re.search(r'<link rel="preload" href="([^"]+\.m3u8[^"]*)"',
                      html or '')
        if m:
            m3u8 = m.group(1)
        if not m3u8:
            m2 = re.search(r'(https://video[^"\']+?\.m3u8[^"\']*)', html or '')
            if m2:
                m3u8 = m2.group(1).replace('\\/', '/')
        if m3u8:
            head = self._probe(m3u8, referer=url)
            if head.lstrip().startswith(b'#EXTM3U'):
                return {'parse': 0, 'jx': 0, 'url': m3u8, 'header': header}
            # 探活没过也先给直链（签名地址可能只认用户端 IP）
            return {'parse': 0, 'jx': 0, 'url': m3u8, '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[:4] == b'RIFF' and raw[8:12] == b'WEBP':
                        return [200, 'image/webp', raw]
                    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]
        except Exception:
            pass
        return [404, 'text/plain', b'']

    def destroy(self):
        pass
