# -*- coding: utf-8 -*-
import re
import sys
import json
import gzip
import base64
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 实测，www.heavy-r.com，自研 PHP tube 站）：
# - 列表分三类 URL 形态：
#   ① 板块流：/videos/recent_favorites/（今日最爱，首页即此流），
#      分页 /videos/recent_favorites/{n}/，后缀 0 起（/1/ 是第 2 页）；
#      /porn_videos/most_viewed/{n}/、/bizarre_porn_videos/most_viewed/{n}/
#      后缀 1 起
#   ② 分类：/free_porn/{slug}.html，分页 /free_porn/{slug}_{n}.html
#      后缀 0 起（_1 是第 2 页）；分类表在 /categories/（14 个）
#   ③ 搜索：GET /search/{词}.html（空格 %20 可），分页同分类 _{n}
#   pagecount 一律取分页器里同形态链接的最大页码
# - 卡片：div.video-item，a.image 指向 /video/{id}/{slug}/，封面是
#   static.heavy-r.com 的 jpg 直链（魔数已验），h4.title 是标题，
#   span.duration 是时长；每页 28 条（板块流页含侧栏共约 40 个 id，
#   只认 video-item 块内的）
# - 详情：视频页 <source> 是自托管单文件（多为 b-cdn 的 mp4，
#   部分片是 object-storage 的 hls m3u8，取第一个 source 探活认）；
#   og:image 是封面、og:title 是标题
# - 注意：分类列表排序不稳，同一页间隔复抓顺序会变（站方有轮换
#   位），相邻页偶有一两条交叉属站方固有，不是解析问题
# - 播放：mp4 直链裸取回 Access Denied，必须带 Referer=视频页，
#   且与抓视频页共用同一会话（源内同一 CookieJar opener 串全链）；
#   player 先重抓一次视频页热会话再普通 GET 探活（ftyp）出 parse=0
SECTIONS = [
    ('sec:fav', '今日最爱'),
    ('sec:viewed', '最热视频'),
    ('sec:bizarre', '猎奇视频'),
]
FALLBACK_CATS = [
    'amateur', 'anal', 'asian', 'ass', 'bdsm', 'big-dick', 'big-tits',
    'creampie', 'dp', 'fisting', 'hardcore', 'lesbian', 'milf', 'shemale',
]


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

    def init(self, extend=''):
        self.host = 'https://www.heavy-r.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 _list_url(self, kind, key, pg):
        if kind == 'sec':
            if key == 'fav':
                base = '/videos/recent_favorites/'
                return self.host + base + (('%d/' % (pg - 1)) if pg > 1 else '')
            if key == 'viewed':
                return '%s/porn_videos/most_viewed/%d/' % (self.host, pg)
            if key == 'bizarre':
                return '%s/bizarre_porn_videos/most_viewed/%d/' % (self.host, pg)
        if kind == 'cat':
            if pg > 1:
                return '%s/free_porn/%s_%d.html' % (self.host, key, pg - 1)
            return '%s/free_porn/%s.html' % (self.host, key)
        if kind == 'search':
            kw = urllib.parse.quote(str(key).strip(), safe='')
            if pg > 1:
                return '%s/search/%s_%d.html' % (self.host, kw, pg - 1)
            return '%s/search/%s.html' % (self.host, kw)
        return self.host + '/'

    def _parse_cards(self, html):
        cards = []
        if not html:
            return cards
        blocks = re.split(r'<div class="video-item', html)
        seen = set()
        for seg in blocks[1:]:
            seg = seg[:4000]
            m = re.search(r'href="(/video/(\d+)/[^"]+/)"', seg)
            if not m:
                continue
            vid = m.group(2)
            if vid in seen:
                continue
            seen.add(vid)
            tm = re.search(r'<h4 class="title"><a[^>]*>(.*?)</a>', seg, re.S)
            title = self._clean(tm.group(1)) if tm else ''
            if not title:
                slug = m.group(1).rstrip('/').split('/')[-1]
                title = slug.replace('_', ' ').strip()
            pm = re.search(r'<img[^>]+src="(https?://[^"]+)"', seg)
            dm = re.search(r'class="duration"[^>]*>.*?(\d{1,2}:\d{2}(?::\d{2})?)',
                           seg, re.S)
            cards.append({
                'vod_id': m.group(1),
                'vod_name': title,
                'vod_pic': pm.group(1) if pm else '',
                'vod_remarks': dm.group(1) if dm else '',
                'style': {'type': 'rect', 'ratio': 1.78},
            })
        return cards

    def _pagecount(self, html, kind, pg, cards):
        nums = []
        if kind == 'cat' or kind == 'search':
            nums = [int(x) + 1 for x in re.findall(r'_(\d+)\.html', html or '')]
        elif kind == 'sec':
            nums = [int(x) for x in re.findall(
                r'/(?:most_viewed|recent_favorites)/(\d+)/', html or '')]
            # recent_favorites 后缀 0 起、most_viewed 1 起，统一偏保守：
            # fav 的链接最大后缀 k 表示至少 k+1 页
            if nums and '/videos/recent_favorites/' in (html or ''):
                nums = [n + 1 for n in nums]
        if nums:
            return max(nums + [pg])
        return pg + 1 if len(cards) >= 20 else pg

    def _list_result(self, kind, key, pg):
        url = self._list_url(kind, key, pg)
        html = self._fetch(url, referer=self.host + '/')
        cards = self._parse_cards(html)
        pc = self._pagecount(html, kind, pg, cards)
        return {'list': cards, 'page': pg, 'pagecount': pc,
                'limit': len(cards), 'total': pc * max(len(cards), 1)}

    # ---------- 接口 ----------
    def _classes(self):
        if self.classes_cache:
            return self.classes_cache
        cats = [{'type_id': t, 'type_name': n} for t, n in SECTIONS]
        seen = set()
        html = self._fetch(self.host + '/categories/')
        slugs = []
        for m in re.finditer(r'href="/free_porn/([a-z0-9-]+)\.html"', html or ''):
            if m.group(1) not in seen:
                seen.add(m.group(1))
                slugs.append(m.group(1))
        if not slugs:
            slugs = FALLBACK_CATS
        for slug in slugs:
            name = slug.replace('-', ' ').title()
            cats.append({'type_id': 'cat:' + slug, 'type_name': name})
        self.classes_cache = cats
        return cats

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

    def homeVideoContent(self):
        url = self._list_url('sec', 'fav', 1)
        html = self._fetch(url, referer=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.startswith('sec:'):
            return self._list_result('sec', tid[4:], pg)
        if tid.startswith('cat:'):
            return self._list_result('cat', tid[4:], pg)
        return {'list': [], 'page': pg, 'pagecount': pg, 'limit': 0, 'total': 0}

    def searchContent(self, key, quick, pg='1'):
        try:
            pg = int(pg)
        except Exception:
            pg = 1
        if pg < 1:
            pg = 1
        return self._list_result('search', str(key), pg)

    def detailContent(self, ids):
        if isinstance(ids, (list, tuple)):
            path = str(ids[0]) if ids else ''
        else:
            path = str(ids)
        if not path:
            return {'list': []}
        page = path if path.startswith('http') else self.host + path
        html = self._fetch(page, referer=self.host + '/')
        if not html:
            return {'list': []}
        tm = re.search(r'property="og:title" content="([^"]+)"', html)
        title = self._clean(tm.group(1)) if tm else ''
        if not title:
            tm = re.search(r'<title>([^<]+)</title>', html)
            title = self._clean(tm.group(1)) if tm else ''
        pm = re.search(r'property="og:image" content="([^"]+)"', html)
        pic = pm.group(1) if pm else ''
        sm = re.search(r'<source[^>]+src="(https?://[^"]+)"', html)
        if sm:
            play = '%s@@%s' % (sm.group(1), page)
        else:
            play = page
        vod = {
            'vod_id': path,
            'vod_name': title,
            'vod_pic': pic,
            'vod_play_from': 'HeavyR',
            'vod_play_url': '正片$%s' % play,
        }
        return {'list': [vod]}

    def playerContent(self, flag, id, vipFlags):
        raw = str(id)
        if '@@' in raw:
            mp4, page = raw.split('@@', 1)
        else:
            mp4, page = '', raw
        header = {'User-Agent': self.ua, 'Referer': page}
        if mp4:
            # 先重抓视频页热会话（CDN 校验 Referer + 会话），再探活
            self._fetch(page, referer=self.host + '/')
            if self._probe_media(mp4, referer=page):
                return {'parse': 0, 'jx': 0, 'url': mp4, 'header': header}
        return {'parse': 1, 'jx': 1, 'url': page, '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()
                    except http.client.IncompleteRead as e:
                        raw = e.partial or b''
                    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
