# -*- 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 实测，www.perfectgirls.xxx，KVS）：
# - 无分类栏目，分类用：三条主线（最新 /、热门 /popular/、趋势 /trending/）
#   + 频道索引前 100 个频道（/channels/{slug}/）；分页统一 /{n}/ 后缀，
#   分页器带末页号，pagecount 取分页链接最大页码
# - 搜索：/search/{词}/、翻页 /search/{词}/{n}/
# - 卡片：a[href=/video/{id}/][title] 锚点（带 data-preview），封面在
#   img[data-original]（懒加载），时长在 ul.video-meta 的 fa-clock-o span
# - 播放：视频页 video 的 source 是 get_file 地址（多档同指一个出口），
#   请求它 302 到 cdn 的 HLS 主清单（签名带时效，player 现取现解），
#   普通 GET 实测 #EXTM3U、多档 variant
FEEDS = [('', '最新'), ('popular', '热门'), ('trending', '趋势')]


class _NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None


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

    def init(self, extend=''):
        self.host = 'https://www.perfectgirls.xxx'
        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
        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': 'en-US,en;q=0.9',
                        'Referer': self.host + '/'}
        self.cj = http.cookiejar.CookieJar()
        self.opener = urllib.request.build_opener(
            urllib.request.HTTPCookieProcessor(self.cj))
        self.opener_nr = urllib.request.build_opener(
            urllib.request.HTTPCookieProcessor(self.cj), _NoRedirect)
        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=30):
        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 _location(self, url, referer=''):
        """请求 get_file 类地址只取 302 Location（不跟随下载）。"""
        headers = {'User-Agent': self.ua}
        if referer:
            headers['Referer'] = referer
        try:
            r = self.opener_nr.open(
                urllib.request.Request(url, headers=headers), timeout=20)
            try:
                return r.geturl()
            finally:
                r.close()
        except urllib.error.HTTPError as e:
            return e.headers.get('Location') or ''
        except Exception:
            return ''

    def _probe_m3u8(self, url, timeout=12):
        try:
            req = urllib.request.Request(url, headers={'User-Agent': self.ua})
            r = self.opener.open(req, timeout=timeout)
            try:
                return r.read(1024).lstrip().startswith(b'#EXTM3U')
            finally:
                r.close()
        except Exception:
            return False

    # ---------- 列表解析 ----------
    def _parse_cards(self, html):
        cards, seen = [], set()
        if not html:
            return cards
        for m in re.finditer(r'<a href="(/video/\d+/)" title="([^"]+)"', html):
            path, title = m.group(1), self._clean(m.group(2))
            if path in seen or not title:
                continue
            seen.add(path)
            seg = html[m.start():m.start() + 4500]
            pm = re.search(r'data-original="([^"]+)"', seg)
            dm = re.search(r'fa-clock-o"></i>\s*<span>([^<]+)</span>', seg)
            cards.append({
                'vod_id': self.host + path,
                'vod_name': title,
                '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 _pagecount(self, html, pg, cards, pat):
        nums = [int(x) for x in re.findall(pat, html or '')]
        if nums:
            return max(max(nums), pg)
        return pg + 1 if cards else pg

    def _classes(self):
        if self.classes_cache:
            return self.classes_cache
        cats = [{'type_id': t, 'type_name': n} for t, n in FEEDS]
        seen = {t for t, _ in FEEDS}
        for idx in ('', '2/'):
            html = self._fetch(self.host + '/channels/' + idx)
            for m in re.finditer(
                    r'<a title="([^"]+)" href="(/channels/[a-z0-9-]+/)">',
                    html or ''):
                name, path = self._clean(m.group(1)), m.group(2)
                slug = path.strip('/').split('/')[-1]
                tid = 'c/' + slug
                if name and tid not in seen:
                    seen.add(tid)
                    cats.append({'type_id': tid, 'type_name': name})
        self.classes_cache = cats
        return cats

    def _list_url(self, tid, pg):
        if tid.startswith('c/'):
            base = '/channels/%s/' % tid[2:]
        elif tid:
            base = '/%s/' % tid
        else:
            base = '/'
        if pg > 1:
            base += '%d/' % pg
        return self.host + base

    def _list_pat(self, tid):
        if tid.startswith('c/'):
            return r'href="/channels/%s/(\d+)/"' % re.escape(tid[2:])
        if tid:
            return r'href="/%s/(\d+)/"' % re.escape(tid)
        return r'href="/(\d+)/"'

    # ---------- 接口 ----------
    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
        html = self._fetch(self._list_url(tid, pg))
        cards = self._parse_cards(html)
        pagecount = self._pagecount(html, pg, cards, self._list_pat(tid))
        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
        kw = urllib.parse.quote(str(key).strip(), safe='')
        url = '%s/search/%s/' % (self.host, kw)
        if pg > 1:
            url += '%d/' % pg
        html = self._fetch(url)
        cards = self._parse_cards(html)
        pagecount = self._pagecount(
            html, pg, cards, r'href="/search/[^"/]+/(\d+)/"')
        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 '')
        if not tm:
            tm = re.search(r'<title>([^<]+)</title>', html or '')
        pm = re.search(r'<video[^>]+poster="([^"]+)"', html or '')
        if not pm:
            pm = re.search(r'property="og:image" content="([^"]+)"', html or '')
        dm = re.search(r'fa-clock-o"></i>\s*<span>([^<]+)</span>', html or '')
        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': self._clean(dm.group(1)) if dm else '',
            '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 'get_file' in url or '.m3u8' in url:
            loc = self._location(url, referer=self.host + '/') or url
            return {'parse': 0, 'jx': 0, 'url': loc,
                    'header': {'User-Agent': self.ua,
                               'Referer': self.host + '/'}}
        html = self._fetch(url, referer=self.host + '/')
        gfs = re.findall(r'<source src="([^"]*get_file[^"]+)"', html or '')
        for gf in gfs:
            # get_file 302 到 HLS 主清单（地址本身可能不带 .m3u8 后缀，
            # 以探活内容为准，不按后缀判）
            loc = self._location(html_mod.unescape(gf), referer=url)
            if loc:
                self._probe_m3u8(loc)
                return {'parse': 0, 'jx': 0, 'url': loc, '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
