# -*- 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


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


class Spider(BaseSpider):
    def getName(self):
        return '娱乐圈外传'

    def init(self, extend=''):
        self.host = 'https://xn--cl0a.yulequanwaichuan.click'
        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',
            '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
        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=25):
        best = ''
        for _ 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=25):
        headers = dict(self.headers)
        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 _location(self, url, referer=''):
        """拦截 302 重定向获取真实直链"""
        headers = {'User-Agent': self.ua}
        if referer:
            headers['Referer'] = referer
        try:
            r = self.opener_nr.open(
                urllib.request.Request(url, headers=headers), timeout=15)
            try:
                return r.geturl()
            finally:
                r.close()
        except urllib.error.HTTPError as e:
            return e.headers.get('Location') or ''
        except Exception:
            return ''

    def _probe_media(self, url, referer='', timeout=12):
        """轻量探测媒体流有效性：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
        seen = set()

        # 按 KVS 标准的 div.item 切分卡片
        blocks = re.split(r'<div[^>]+class="[^"]*\bitem\b[^"]*"', html)
        for seg in blocks[1:]:
            seg = seg[:4000]

            # 属性解耦提取：先找到主 <a> 标签，独立抽取 href 和 title
            v_url, title = '', ''
            atag = re.search(r'<a\b[^>]*href="([^"]*/video/\d+/[^"]*)"[^>]*>', seg)
            if not atag:
                atag = re.search(r'<a\b[^>]*>', seg)
            if atag:
                hm = re.search(r'href="([^"]+)"', atag.group(0))
                tm = re.search(r'title="([^"]+)"', atag.group(0))
                if hm:
                    v_url = hm.group(1)
                if tm:
                    title = tm.group(1)

            # 兜底：从 strong.title 标签提取标题
            if not title:
                tm2 = re.search(r'<strong[^>]*class="title"[^>]*>(.*?)</strong>', seg, re.S)
                if tm2:
                    title = self._clean(tm2.group(1))

            if not v_url or '/video/' not in v_url:
                continue

            v_path = v_url.replace(self.host, '')
            id_m = re.search(r'/video/(\d+)/', v_path)
            vid = id_m.group(1) if id_m else v_path
            if vid in seen:
                continue
            seen.add(vid)

            # 优先提取懒加载 data-original，过滤 base64 占位图
            pm = re.search(r'<img[^>]+data-original="([^"]+)"', seg)
            if not pm:
                pm = re.search(r'<img[^>]+data-src="([^"]+)"', seg)
            if not pm:
                pm = re.search(r'<img[^>]+src="([^"]+)"', seg)
            pic = pm.group(1) if pm else ''
            if pic.startswith('data:'):
                pic = ''

            # 提取视频时长
            dm = re.search(r'<div[^>]*class="duration"[^>]*>([^<]+)</div>', seg)
            remarks = self._clean(dm.group(1)) if dm else ''

            cards.append({
                'vod_id': v_path,
                'vod_name': self._clean(title),
                'vod_pic': pic,
                'vod_remarks': remarks,
                'style': {'type': 'rect', 'ratio': 1.78},
            })
        return cards

    def _pagecount(self, html, pg, cards):
        # 匹配分页链接最大页码
        nums = [int(x) for x in re.findall(r'/(\d+)/', html or '') if x.isdigit()]
        nums += [int(x) for x in re.findall(r'[?&]from_videos=(\d+)', html or '') if x.isdigit()]
        if nums:
            # 过滤异常大数字，选取合理的页码上限
            valid_nums = [n for n in nums if n <= 2000]
            if valid_nums:
                return max(valid_nums + [pg])
        return pg + 1 if len(cards) >= 15 else pg

    # ---------- 接口 ----------
    def _classes(self):
        if self.classes_cache:
            return self.classes_cache
        # 预设基础核心流
        cats = [
            {'type_id': 'latest-videos', 'type_name': '最新电影'},
            {'type_id': 'mostpopular-videos', 'type_name': '热播电影'},
            {'type_id': 'videos', 'type_name': '全部视频'},
        ]
        seen = {c['type_id'] for c in cats}

        # 动态拉取二级栏目总览页
        # 实测：栏目页的分类不是 <a>直接文本，而是
        # <a class="category-item" href=".../videos/categories/<slug>/"
        #  title="<名>"><div class="category-title"><名></div></a>，
        # 旧正则要求 <a>后直接跟文本，14 个分类一个都匹配不上，
        # 只能回 3 个写死的基础分类，所以分类不全；
        # 另外旧 tid 拼成 categories/<slug>，列表页真实地址是
        # videos/categories/<slug>/，旧 tid 即使匹配上也会走错地址
        html = self._fetch('%s/categories/' % self.host, referer=self.host + '/')
        if html:
            for m in re.finditer(r'<a[^>]+class="category-item"[^>]+href="([^"]*/videos/categories/([^"/]+)/)"[^>]*>', html):
                slug = m.group(2).strip()
                tid = 'videos/categories/%s' % slug
                if tid in seen:
                    continue
                # 名字优先取 title 属性，其次取紧跟的 category-title 块
                am = m.group(0)
                tm = re.search(r'title="([^"]+)"', am)
                name = self._clean(tm.group(1)) if tm else ''
                if not name:
                    tail = html[m.end():m.end() + 300]
                    tm2 = re.search(r'class="category-title"[^>]*>([^<]+)<', tail)
                    name = self._clean(tm2.group(1)) if tm2 else ''
                if name and not name.isdigit():
                    seen.add(tid)
                    cats.append({'type_id': tid, 'type_name': name})
            if len(cats) <= 3:
                # 兜底：category-item 结构变了时，用通用分类链接 + 标题块再扫一遍
                for m in re.finditer(r'href="([^"]*/videos/categories/([^"/]+)/)"[^>]*title="([^"]+)"', html):
                    slug, name = m.group(2).strip(), self._clean(m.group(3))
                    tid = 'videos/categories/%s' % slug
                    if tid not in seen and name and not name.isdigit():
                        seen.add(tid)
                        cats.append({'type_id': tid, '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 + '/welcome/', 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).strip('/')

        # 适配 KVS 列表翻页标准路径
        if pg > 1:
            url = '%s/%s/%d/' % (self.host, tid, pg)
        else:
            url = '%s/%s/' % (self.host, tid)

        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())

        if pg > 1:
            url = '%s/search/%s/%d/' % (self.host, kw, pg)
        else:
            url = '%s/search/%s/' % (self.host, kw)

        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):
        path = str(ids[0]) if isinstance(ids, (list, tuple)) else str(ids)
        if not path.startswith('http'):
            page_url = '%s%s' % (self.host, ('/' + path.lstrip('/')))
        else:
            page_url = path

        html = self._fetch(page_url, referer=self.host + '/')
        title, pic, desc = '', '', ''

        if html:
            tm = re.search(r'property="og:title" content="([^"]+)"', html)
            if not tm:
                tm = re.search(r'<title>([^<]+)</title>', html)
            title = self._clean(tm.group(1)) if tm else ''
            title = re.sub(r'\s*-\s*娱乐圈外传.*$', '', title).strip()

            pm = re.search(r'property="og:image" content="([^"]+)"', html)
            if not pm:
                pm = re.search(r'<video[^>]+poster="([^"]+)"', html)
            pic = pm.group(1) if pm else ''

            dm = re.search(r'property="og:description" content="([^"]+)"', html)
            desc = self._clean(dm.group(1)) if dm else ''

        vod = {
            'vod_id': path,
            'vod_name': title or '视频播放',
            'vod_pic': pic,
            'vod_content': desc,
            'vod_play_from': '娱乐圈外传',
            'vod_play_url': '正片$%s' % page_url,
        }
        return {'list': [vod]}

    def playerContent(self, flag, id, vipFlags):
        url = str(id).strip()
        header = {
            'User-Agent': self.ua,
            'Referer': self.host + '/'
        }

        # 1. 已是直链媒体，探活后直下
        if '.m3u8' in url or '.mp4' in url:
            if self._probe_media(url, referer=self.host + '/'):
                return {'parse': 0, 'jx': 0, 'url': url, 'header': header}

        # 2. 抓取视频详情页，解析 KVS 媒体直链与 get_file 跳转
        html = self._fetch(url, referer=self.host + '/')
        if html:
            flat = html.replace('\\/', '/')
            # 优先提取 get_file 302 地址
            gfs = re.findall(r'https?://[^\s"\'<>]+get_file[^\s"\'<>]*', flat)
            gfs.sort(key=lambda u: 'preview' in u.lower())
            seen_gf = set()
            for gf in gfs:
                gf = html_mod.unescape(gf).rstrip('\\')
                if gf in seen_gf:
                    continue
                seen_gf.add(gf)
                loc = self._location(gf, referer=url)
                cand = loc if loc else gf
                if self._probe_media(cand, referer=url):
                    return {'parse': 0, 'jx': 0, 'url': cand, 'header': header}

            # 提取直写的 source / video 媒体直链
            cands = re.findall(r'<source[^>]+src="([^"]+)"', html)
            cands += re.findall(r'<video[^>]+src="([^"]+)"', html)
            cands += re.findall(r'https?://[^\s"\'<>]+\.(?:m3u8|mp4)[^\s"\'<>]*', flat)
            for cand in cands:
                cand = html_mod.unescape(cand)
                if 'ad' in cand or 'preview' in cand:
                    continue
                if self._probe_media(cand, referer=url):
                    return {'parse': 0, 'jx': 0, 'url': cand, 'header': header}

        # 3. 兜底回退给播放器内置浏览器嗅探
        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):
        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