# -*- coding: utf-8 -*-
import re
import sys
import json
import gzip
import html as html_mod
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 Spider(BaseSpider):
    def getName(self):
        return '第一吃瓜网'

    def init(self, extend=''):
        self.host = 'https://chigua18.net'
        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.classes_cache = None

    # ---------- 基础工具 ----------
    def _unescape(self, s):
        if not s:
            return ''
        return html_mod.unescape(s).replace('\xa0', ' ')

    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):
        data = b''
        try:
            req = urllib.request.Request(url, headers=self.headers)
            r = urllib.request.urlopen(req, timeout=25)
            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 _parse_cards(self, html):
        videos = []
        seen = set()
        for block in (html or '').split('<article')[1:]:
            um = re.search(r'href="(https://chigua18\.net/index\.php/archives/'
                           r'(\d+)\.html)"', block)
            if not um:
                continue
            vid = um.group(2)
            if vid in seen:
                continue
            seen.add(vid)
            tm = re.search(r'post-card-title"[^>]*>(.*?)</h2>', block, re.S)
            title = self._clean(tm.group(1)) if tm else ''
            # 卡片标题里混着「热门推荐」之类的角标 span，去掉尾巴角标文本
            title = re.sub(r'(热门推荐|置顶|推荐)$', '', title).strip()
            im = re.search(r"loadBannerDirect\('(https?://[^']+)'", block)
            dm = re.search(r'itemprop="datePublished" content="([0-9-]+)', block)
            videos.append({
                'vod_id': vid,
                'vod_name': title,
                'vod_pic': im.group(1) if im else '',
                'vod_remarks': dm.group(1) if dm else '',
            })
        return videos

    def _pagecount(self, html, pg, marker):
        # 分页器里出现自己下一页的链接就还有下一页
        return pg + 1 if ('%s%d/' % (marker, pg + 1)) in (html or '') else pg

    def _result(self, html, pg, marker):
        pc = self._pagecount(html, pg, marker)
        return {'list': self._parse_cards(html), 'page': pg,
                'pagecount': pc, 'limit': 12, 'total': pc * 12}

    # ---------- 接口 ----------
    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="https://chigua18\.net/index\.php/category/([a-z0-9_-]+)/?"'
                r'[^>]*>([^<]*)</a>', html or ''):
            slug, name = m.group(1), self._clean(m.group(2))
            if slug in seen or not name:
                continue
            seen.add(slug)
            classes.append({'type_id': slug, 'type_name': name})
        if not classes:
            classes = [{'type_id': s, 'type_name': n} for s, n in (
                ('redian', '热点事件'), ('mingxing', '网红明星'),
                ('baitai', '世间百态'), ('lieqi', '海外猎奇'),
                ('fenxiang', '网友分享'), ('fuli', '瓜友福利'))]
        self.classes_cache = classes
        return classes

    def homeContent(self, filter):
        html = self.fetch(self.host + '/')
        try:
            classes = self._classes()
        except Exception:
            classes = []
        return {'class': 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 = '%s/index.php/category/%s/' % (self.host, tid)
        url = base if pg == 1 else '%s%d/' % (base, pg)
        html = self.fetch(url)
        return self._result(html, pg, '/category/%s/' % tid)

    def searchContent(self, key, quick, pg='1'):
        try:
            pg = int(pg)
        except Exception:
            pg = 1
        q = urllib.parse.quote(key)
        base = '%s/index.php/search/%s/' % (self.host, q)
        url = base if pg == 1 else '%s%d/' % (base, pg)
        html = self.fetch(url)
        return self._result(html, pg, '/search/%s/' % q)

    def detailContent(self, ids):
        vid = str(ids[0]).strip()
        page_url = '%s/index.php/archives/%s.html' % (self.host, vid)
        html = self.fetch(page_url)
        name, pic = '', ''
        eps = []
        if html:
            tm = re.search(r'<title>([^<]+)</title>', html)
            name = self._clean(tm.group(1)) if tm else ''
            name = re.sub(r'\s*-\s*第一吃瓜网.*$', '', name).strip()
            pm = re.search(r'og:image" content="([^"]+)"', html)
            if pm:
                pic = pm.group(1)
            for i, m in enumerate(re.finditer(
                    r"""class="dplayer" data-config='([^']+)'""", html)):
                try:
                    cfg = json.loads(m.group(1))
                except Exception:
                    continue
                v = cfg.get('video') or {}
                u = v.get('url') or ''
                if not u:
                    continue
                if not pic and v.get('pic'):
                    pic = v['pic']
                eps.append('视频%d$%s' % (i + 1, u))
            if not pic:
                im = re.search(r'(https://chigua18\.net/usr/uploads/[^"\']+?'
                               r'\.(?:jpg|png|jpeg))', html)
                if im:
                    pic = im.group(1)
        if not eps:
            eps = ['查看原文$%s' % page_url]
        vod = {
            'vod_id': vid,
            'vod_name': name,
            'vod_pic': pic,
            'vod_play_from': '播放',
            'vod_play_url': '#'.join(eps),
        }
        return {'list': [vod]}

    def playerContent(self, flag, id, vipFlags):
        url = id
        if url.startswith('http') and ('.mp4' in url or '.m3u8' in url):
            return {'parse': 0, 'jx': 0, 'url': url,
                    'header': {'User-Agent': self.ua,
                               'Referer': self.host + '/'}}
        return {'parse': 1, 'jx': 1, 'url': url,
                'header': {'User-Agent': self.ua, 'Referer': self.host + '/'}}
