# -*- coding: utf-8 -*-
import re
import sys
import gzip
import urllib.request
import urllib.parse
import urllib.error
import http.cookiejar

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


class Spider(BaseSpider):
    def getName(self):
        return '蘑菇视频'

    def init(self, extend=''):
        self.host = 'http://moguds.cc'
        self.ua = ('Mozilla/5.0 (Linux; Android 13; Redmi K70) '
                   'AppleWebKit/537.36 (KHTML, like Gecko) '
                   'Chrome/120.0 Mobile Safari/537.36')
        self.headers = {'User-Agent': self.ua, 'Referer': self.host + '/'}
        self.cj = http.cookiejar.CookieJar()
        self.opener = urllib.request.build_opener(
            urllib.request.HTTPCookieProcessor(self.cj))
        self.classes_cache = None

    # ---------- 基础工具 ----------
    def _unescape(self, s):
        if not s:
            return ''
        s = (s.replace('&amp;', '&').replace('&lt;', '<').replace('&gt;', '>')
             .replace('&quot;', '"').replace('&#039;', "'").replace('&apos;', "'")
             .replace('&nbsp;', ' '))
        return re.sub(r'&#(\d+);', lambda m: chr(int(m.group(1))), s)

    def _clean(self, s):
        s = self._unescape(s or '')
        s = re.sub(r'<[^>]+>', '', s)
        return re.sub(r'\s+', ' ', s).strip()

    def fetch(self, url):
        try:
            req = urllib.request.Request(url, headers=self.headers)
            with self.opener.open(req, timeout=20) as r:
                data = r.read()
            if data[:2] == b'\x1f\x8b':
                data = gzip.decompress(data)
            return data.decode('utf-8', 'ignore')
        except Exception:
            return ''

    def _parse_cards(self, html):
        videos = []
        seen = set()
        pat = re.compile(
            r'<a class="cinema-card__link" href="/video/(\d+)/" title="([^"]*)">')
        for m in pat.finditer(html or ''):
            vid = m.group(1)
            if vid in seen:
                continue
            seen.add(vid)
            tail = html[m.end():m.end() + 1200]
            pm = re.search(r'data-original="([^"]+)"', tail)
            dm = re.search(r'cinema-card__duration">([^<]+)</span>', tail)
            videos.append({
                'vod_id': vid,
                'vod_name': self._clean(m.group(2)),
                'vod_pic': self._unescape(pm.group(1)) if pm else '',
                'vod_remarks': self._clean(dm.group(1)) if dm else '',
            })
        return videos

    def _pagecount(self, html, base):
        pages = [int(x) for x in re.findall(
            re.escape(base) + r'(\d+)/', html or '')]
        return max(pages) if pages else 0

    # ---------- 接口 ----------
    def _classes(self):
        if self.classes_cache is not None:
            return self.classes_cache
        classes = []
        seen = set()
        html = self.fetch(self.host + '/')
        for m in re.finditer(
                r'href="/category/(cate\d+)/"[^>]*>([^<]*)</a>', html or ''):
            tid, name = m.group(1), self._clean(m.group(2))
            # cate1「推荐」分类页本身是空的（内容只在首页），不收录
            if tid in seen or tid == 'cate1' or not name:
                continue
            seen.add(tid)
            classes.append({'type_id': tid, 'type_name': name})
        self.classes_cache = classes
        return classes

    def homeContent(self, filter):
        html = self.fetch(self.host + '/')
        return {'class': self._classes(), 'list': self._parse_cards(html)}

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

    def categoryContent(self, tid, pg, filter, extend):
        pg = int(pg)
        base = '/category/%s/' % tid
        url = self.host + base if pg <= 1 else '%s%s%d/' % (self.host, base, pg)
        html = self.fetch(url)
        videos = self._parse_cards(html)
        pagecount = self._pagecount(html, base) or pg
        return {'list': videos, 'page': pg, 'pagecount': pagecount,
                'limit': 20, 'total': pagecount * 20}

    def searchContent(self, key, quick, pg='1'):
        try:
            pg = int(pg)
        except Exception:
            pg = 1
        base = '/search/%s/' % urllib.parse.quote(key)
        url = self.host + base if pg <= 1 else '%s%s%d/' % (self.host, base, pg)
        html = self.fetch(url)
        videos = self._parse_cards(html)
        pagecount = self._pagecount(html, base) or pg
        return {'list': videos, 'page': pg, 'pagecount': pagecount,
                'limit': 20, 'total': pagecount * 20}

    def detailContent(self, ids):
        vid = str(ids[0])
        html = self.fetch('%s/video/%s/' % (self.host, vid))
        if not html:
            return {'list': []}
        tm = re.search(r'og:title" content="([^"]+)"', html)
        name = self._clean(tm.group(1)) if tm else ''
        name = re.sub(r'\s*-\s*蘑菇视频.*$', '', name)
        pm = re.search(r'og:image" content="([^"]+)"', html)
        pic = self._unescape(pm.group(1)) if pm else ''

        froms, urls = [], []
        vpos = html.find('id="article-videos"')
        data_url = default_cdn = ''
        if vpos >= 0:
            seg = html[vpos:vpos + 500]
            um = re.search(r'data-url="([^"]+)"', seg)
            cm = re.search(r'data-cdnline="([^"]+)"', seg)
            data_url = um.group(1) if um else ''
            default_cdn = cm.group(1) if cm else ''
        if data_url:
            lines = []
            seen_cdn = set()
            for bm in re.finditer(r'<button[^>]*cinema-line-option[^>]*>', html):
                tag = bm.group(0)
                vm2 = re.search(r'data-cinema-line-value="([^"]*)"', tag)
                tm2 = re.search(r'data-cinema-line-title="([^"]*)"', tag)
                cdn = (vm2.group(1).strip() if vm2 else '') or default_cdn
                # 站方个别线路地址少写一个斜杠，补正
                cdn = re.sub(r'^(https?:/)([^/])', r'\1/\2', cdn)
                if not cdn or cdn in seen_cdn:
                    continue
                seen_cdn.add(cdn)
                lname = self._clean(tm2.group(1)) if tm2 else ''
                lines.append((lname or '线路', cdn))
            if default_cdn not in seen_cdn:
                lines.insert(0, ('智能线路', default_cdn))
            for title, cdn in lines:
                froms.append(title)
                urls.append('正片$%s%s' % (cdn.rstrip('/'), data_url))
        vod = {
            'vod_id': vid,
            'vod_name': name,
            'vod_pic': pic,
            'vod_play_from': '$$$'.join(froms),
            'vod_play_url': '$$$'.join(urls),
        }
        return {'list': [vod]}

    def playerContent(self, flag, id, vipFlags):
        return {'parse': 0, 'jx': 0, 'url': id,
                'header': {'User-Agent': self.ua, 'Referer': self.host + '/'}}
