# -*- coding: utf-8 -*-
import re
import sys
import json
import gzip
import base64
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.assoass.com/zh/，外链聚合站）：
# - 本站不托管视频：卡片全部外链到来源站的视频页。卡片链接是
#   /out/?l=<载荷>，载荷解开后内嵌来源页明文地址；/out/ 本身对
#   部分地区 IP 会跳地区封锁页，故源内直接解出目标地址用，
#   不走 /out/ 跳转
# - 列表：/zh/new、/zh/popular、/zh/category/{slug}、/zh/search/{词}，
#   分页统一 ?page=N，每页 120 条；分类目录在首页（约 490 个，
#   名称后带计数需剥掉）
# - 卡片：div.card[data-public-id]，标题在 a.item-link 的 title，
#   封面 img（ttcache），时长/画质在 badge，来源站在 item-source
# - 播放：来源站多为 KVS 系，视频页带 get_file 的 source——
#   player 现抓目标页解 get_file（302 探活内容认），解不到退
#   parse=1 让壳嗅探目标页
FEEDS = [('new', '最新'), ('popular', '热门')]


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


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

    def init(self, extend=''):
        self.host = 'https://www.assoass.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.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):
        # 空响应重试；本站对部分地区出口 IP 会跳地区封锁页
        # （/blocked-us-*/），探到封锁页也重试（换出口可能放行）
        last = ''
        for attempt in range(3):
            text = self._fetch_once(url, referer, timeout)
            if not text:
                continue
            last = text
            if 'Blocked due to legislation' in text or '/blocked-' in text:
                continue
            return text
        return last

    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''
        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=''):
        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_media(self, url, timeout=12):
        """普通 GET 读头部字节判媒体：HLS 看 #EXTM3U，mp4 看 ftyp。"""
        try:
            req = urllib.request.Request(url, headers={'User-Agent': self.ua})
            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 _decode_target(self, out_href):
        """从 /out/?l= 载荷里解出来源页明文地址。"""
        try:
            q = urllib.parse.urlparse(
                html_mod.unescape(out_href)).query
            blob = urllib.parse.parse_qs(q).get('l', [''])[0]
            if not blob:
                return ''
            raw = base64.urlsafe_b64decode(blob + '=' * (-len(blob) % 4))
            text = raw.decode('latin-1')
            for m in re.finditer(r'https?://[A-Za-z0-9\-._~:/?#@!$&()*+,;=%\[\]]+',
                                 text):
                u = m.group(0)
                if 'assoass.com' not in u:
                    return u
        except Exception:
            pass
        return ''

    def _parse_cards(self, html):
        cards = []
        if not html:
            return cards
        parts = re.split(r'data-public-id="', html)
        for seg in parts[1:]:
            seg = seg[:12000]
            tm = re.search(r'class="item-link[^"]*" href="([^"]+)"[^>]*title="([^"]+)"', seg)
            if not tm:
                tm = re.search(r'href="(/out/\?[^"]+)"[^>]*title="([^"]+)"', seg)
            if not tm:
                continue
            title = self._clean(tm.group(2))
            target = self._decode_target(tm.group(1))
            if not title or not target:
                continue
            pm = re.search(r'<img[^>]+src="(https?://[^"]+)"', seg)
            dur = ''
            qual = ''
            bi = seg.find('class="badge')
            if bi >= 0:
                gt = seg.find('>', bi)
                btxt = self._clean(seg[gt + 1:gt + 800]) if gt > bi else ''
                dm = re.search(r'(\d{1,2}:\d{2}(?::\d{2})?)', btxt)
                if dm:
                    dur = dm.group(1)
                    q = btxt[:dm.start()].strip()
                    qual = q if 0 < len(q) <= 8 else ''
            sm = re.search(r'class="item-source[^"]*"[^>]*>(.*?)</a>', seg, re.S)
            source = self._clean(sm.group(1)) if sm else ''
            remarks = ' '.join(x for x in (qual, dur) if x) or source
            payload = {'t': title, 'p': pm.group(1) if pm else '',
                       'u': target, 's': source, 'd': dur}
            token = 'E1.' + base64.urlsafe_b64encode(
                json.dumps(payload, ensure_ascii=False).encode('utf-8')
            ).decode('ascii')
            cards.append({
                'vod_id': token,
                'vod_name': title,
                'vod_pic': payload['p'],
                'vod_remarks': remarks,
                'style': {'type': 'rect', 'ratio': 1.78},
            })
        return cards

    def _pagecount(self, pg, cards):
        return pg + 1 if len(cards) >= 120 else pg

    def _fetch_list(self, url):
        """列表页抓取：首抓没有卡片标记时再抓一次（站方偶发挑战页）。"""
        html = self._fetch(url)
        if 'data-public-id' not in (html or ''):
            html2 = self._fetch(url)
            if 'data-public-id' in (html2 or ''):
                return html2
        return html

    # ---------- 接口 ----------
    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}
        html = self._fetch(self.host + '/zh/')
        for m in re.finditer(r'href="/zh/category/([a-z0-9-]+)"[^>]*>(.*?)</a>',
                             html or '', re.S):
            slug = m.group(1)
            name = self._clean(m.group(2))
            name = re.sub(r'\s*\d[\d.]*\s*万?\s*$', '', name).strip()
            if slug not in seen and name:
                seen.add(slug)
                cats.append({'type_id': slug, 'type_name': name})
        self.classes_cache = cats
        return cats

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

    def homeVideoContent(self):
        html = self._fetch_list(self.host + '/zh/new')
        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
        if tid in ('new', 'popular'):
            url = '%s/zh/%s' % (self.host, tid)
        else:
            url = '%s/zh/category/%s' % (self.host, tid)
        if pg > 1:
            url += '?page=%d' % pg
        html = self._fetch_list(url)
        cards = self._parse_cards(html)
        return {'list': cards, 'page': pg,
                'pagecount': self._pagecount(pg, cards),
                'limit': len(cards), 'total': self._pagecount(pg, cards) * len(cards)}

    def searchContent(self, key, quick, pg='1'):
        try:
            pg = int(pg)
        except Exception:
            pg = 1
        if pg < 1:
            pg = 1
        if pg == 1:
            url = '%s/zh/search/%s' % (
                self.host, urllib.parse.quote(str(key).strip(), safe=''))
        else:
            # 本站搜索是「词→同名分类」的解析式搜索：第 1 页走
            # /zh/search/{词}，翻页在 /zh/category/{slug} 下，
            # search 路径本身带 ?page 会被忽略恒返第 1 页
            slug = re.sub(r'[^a-z0-9]+', '-', str(key).strip().lower()).strip('-')
            if not slug:
                return {'list': [], 'page': pg, 'pagecount': pg,
                        'limit': 0, 'total': 0}
            url = '%s/zh/category/%s?page=%d' % (self.host, slug, pg)
        html = self._fetch_list(url)
        cards = self._parse_cards(html)
        return {'list': cards, 'page': pg,
                'pagecount': self._pagecount(pg, cards),
                'limit': len(cards), 'total': self._pagecount(pg, cards) * len(cards)}

    def detailContent(self, ids):
        if isinstance(ids, (list, tuple)):
            token = str(ids[0]) if ids else ''
        else:
            token = str(ids)
        info = {}
        if token.startswith('E1.'):
            try:
                info = json.loads(base64.urlsafe_b64decode(
                    token[3:] + '=' * (-len(token[3:]) % 4)).decode('utf-8'))
            except Exception:
                info = {}
        if not info.get('u'):
            return {'list': []}
        vod = {
            'vod_id': token,
            'vod_name': info.get('t', ''),
            'vod_pic': info.get('p', ''),
            'vod_remarks': info.get('d', ''),
            'vod_actor': info.get('s', ''),
            'vod_play_from': '来源站',
            'vod_play_url': '正片$%s' % info['u'],
        }
        return {'list': [vod]}

    def playerContent(self, flag, id, vipFlags):
        url = str(id)
        header = {'User-Agent': self.ua, 'Referer': url}
        host = urllib.parse.urlparse(url).netloc
        referer = 'https://%s/' % host
        html = self._fetch(url, referer=referer)
        if html:
            # 来源站多为 KVS 系：get_file 地址可能写在 source 标签里，
            # 也可能在 JS 里以 \/ 转义拼出——先脱转义再全页提取
            flat = html.replace('\\/', '/')
            gfs = re.findall(r'https?://[^\s"\'<>]+get_file[^\s"\'<>]*', flat)
            # 预览片地址排最后：优先能解出正片的候选
            gfs.sort(key=lambda u: 'preview' in u.lower())
            seen = set()
            for gf in gfs:
                gf = html_mod.unescape(gf).rstrip('\\')
                if gf in seen:
                    continue
                seen.add(gf)
                loc = self._location(gf, referer=url)
                cand = loc if loc else gf
                if self._probe_media(cand):
                    return {'parse': 0, 'jx': 0, 'url': cand,
                            'header': {'User-Agent': self.ua,
                                       'Referer': referer}}
            # 页面直写的 m3u8 / mp4（跳过广告位地址）
            for m in re.finditer(r'https?://[^\s"\'<>]+\.(?:m3u8|mp4)[^\s"\'<>]*',
                                 flat):
                u = html_mod.unescape(m.group(0))
                if '/ads/' in u or '/ad/' in u:
                    continue
                if self._probe_media(u):
                    return {'parse': 0, 'jx': 0, 'url': u,
                            'header': {'User-Agent': self.ua,
                                       'Referer': referer}}
        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
