# coding=utf-8
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys
import re
import json
try:
    import requests
except Exception:
    # --- embedded requests-compatible shim (urllib based) for Yingxia adaptation ---
    # Inserted by py578 adaptation: used only when real `requests` is unavailable.
    import json as _json
    import ssl as _ssl
    import urllib.error as _uerr
    import urllib.parse as _uparse
    import urllib.request as _ureq
    import http.cookiejar as _cookiejar


    class _ReqExc(Exception):
        pass


    class _Timeout(_ReqExc):
        pass


    class _ConnectionError(_ReqExc):
        pass


    class _HTTPError(_ReqExc):
        pass


    class _CaseDict(dict):
        def get(self, k, d=None):
            for kk, vv in self.items():
                if kk.lower() == str(k).lower():
                    return vv
            return d

        def __getitem__(self, k):
            v = self.get(k)
            if v is None:
                raise KeyError(k)
            return v


    class _Response:
        def __init__(self, status_code=0, headers=None, content=b"", url="", cookies=None):
            self.status_code = status_code
            self.headers = _CaseDict(headers or {})
            self.content = content or b""
            self.url = url
            self.cookies = cookies or {}
            self.encoding = None
            self._text = None

        @property
        def text(self):
            if self._text is None:
                enc = self.encoding
                if not enc:
                    ct = self.headers.get("Content-Type", "")
                    m = _uparse.parse_qs(ct.replace(";", "&")) if False else None
                    enc = "utf-8"
                    if "charset=" in ct:
                        enc = ct.split("charset=")[-1].split(";")[0].strip() or "utf-8"
                try:
                    self._text = self.content.decode(enc, "ignore")
                except Exception:
                    self._text = self.content.decode("utf-8", "ignore")
            return self._text

        def json(self):
            return _json.loads(self.text)

        def raise_for_status(self):
            if self.status_code >= 400:
                raise _HTTPError("HTTP %s" % self.status_code)

        def iter_content(self, chunk_size=65536):
            for i in range(0, len(self.content), chunk_size):
                yield self.content[i:i + chunk_size]

        def close(self):
            pass


    class _Session:
        def __init__(self):
            self.headers = {"User-Agent": "Mozilla/5.0 (Linux; Android 13) AppleWebKit/537.36 Chrome/120 Mobile Safari/537.36"}
            self.cookies = {}
            self._jar = _cookiejar.CookieJar()
            self._ctx = _ssl._create_unverified_context()
            self._opener = _ureq.build_opener(
                _ureq.HTTPCookieProcessor(self._jar),
                _ureq.HTTPSHandler(context=self._ctx))

        def request(self, method, url, headers=None, timeout=15, data=None,
                    json=None, params=None, cookies=None, verify=False,
                    allow_redirects=True, stream=False, **kw):
            if params:
                qs = _uparse.urlencode(params, doseq=True)
                url = url + ("&" if "?" in url else "?") + qs
            hd = dict(self.headers)
            if headers:
                hd.update(headers)
            body = None
            if json is not None:
                body = _json.dumps(json, ensure_ascii=False).encode("utf-8")
                hd.setdefault("Content-Type", "application/json")
            elif isinstance(data, dict):
                body = _uparse.urlencode(data, doseq=True).encode("utf-8")
                hd.setdefault("Content-Type", "application/x-www-form-urlencoded")
            elif isinstance(data, str):
                body = data.encode("utf-8")
            elif isinstance(data, (bytes, bytearray)):
                body = bytes(data)
            if cookies:
                hd["Cookie"] = "; ".join("%s=%s" % kv for kv in cookies.items())
            elif self.cookies:
                hd.setdefault("Cookie", "; ".join("%s=%s" % kv for kv in self.cookies.items()))
            req = _ureq.Request(url, data=body, headers=hd, method=method.upper())
            try:
                to = timeout
                if isinstance(to, (tuple, list)):
                    to = max(to)
                if to and float(to) > 120:
                    to = float(to) / 1000.0
                with self._opener.open(req, timeout=to or 15) as resp:
                    content = resp.read()
                    hdrs = dict(resp.headers.items())
                    final = resp.geturl()
                    status = resp.status
            except _uerr.HTTPError as e:
                try:
                    content = e.read()
                except Exception:
                    content = b""
                hdrs = dict(e.headers.items()) if e.headers else {}
                final = e.geturl() if hasattr(e, "geturl") else url
                status = e.code
            except Exception as e:
                raise _ConnectionError(str(e))
            for c in self._jar:
                self.cookies[c.name] = c.value
            return _Response(status, hdrs, content, final, dict(self.cookies))

        def get(self, url, **kw):
            return self.request("GET", url, **kw)

        def post(self, url, data=None, **kw):
            return self.request("POST", url, data=data, **kw)

        def head(self, url, **kw):
            return self.request("HEAD", url, **kw)

        def close(self):
            pass


    class _Exceptions:
        RequestException = _ReqExc
        Timeout = _Timeout
        ConnectTimeout = _Timeout
        ReadTimeout = _Timeout
        ConnectionError = _ConnectionError
        HTTPError = _HTTPError
        SSLError = _ConnectionError


    class _RequestsShim:
        Session = _Session
        exceptions = _Exceptions
        Response = _Response

        @staticmethod
        def request(method, url, **kw):
            return _Session().request(method, url, **kw)

        @staticmethod
        def get(url, **kw):
            return _Session().request("GET", url, **kw)

        @staticmethod
        def post(url, data=None, **kw):
            return _Session().request("POST", url, data=data, **kw)

        @staticmethod
        def head(url, **kw):
            return _Session().request("HEAD", url, **kw)


    requests = _RequestsShim
    # --- end embedded requests shim ---
    requests.RequestException = requests.exceptions.RequestException
    requests.Timeout = requests.exceptions.Timeout
    requests.ConnectionError = requests.exceptions.ConnectionError
    requests.HTTPError = requests.exceptions.HTTPError
    requests.SSLError = requests.exceptions.SSLError
    def _req_mount(self, prefix, adapter):
        pass
    requests.Session.mount = _req_mount
    requests.Session.proxies = {}
    requests.Session.trust_env = True
    class _CookieDict(dict):
        def set(self, name, value, **kw):
            self[name] = value
        def get_dict(self):
            return dict(self)
        def clear(self):
            dict.clear(self)
    _orig_sess_init = requests.Session.__init__
    def _sess_init(self, *a, **kw):
        _orig_sess_init(self, *a, **kw)
        self.cookies = _CookieDict(self.cookies)
        self.proxies = {}
    requests.Session.__init__ = _sess_init
    _orig_sess_request = requests.Session.request
    def _sess_request(self, method, url, headers=None, timeout=15, data=None, json=None, params=None, cookies=None, verify=False, allow_redirects=True, stream=False, **kw):
            # 映匣适配：容忍 IncompleteRead（分片传输截断时用已读部分），并自动解 gzip/deflate
            import urllib.parse as _up2
            import urllib.request as _ur2
            import urllib.error as _ue2
            import http.client as _hc2
            import json as _json2
            if params:
                _qs = _up2.urlencode(params, doseq=True)
                url = url + ("&" if "?" in url else "?") + _qs
            _hd = dict(self.headers)
            if headers:
                _hd.update(headers)
            _body = None
            if json is not None:
                _body = _json2.dumps(json, ensure_ascii=False).encode("utf-8")
                _hd.setdefault("Content-Type", "application/json")
            elif isinstance(data, dict):
                _body = _up2.urlencode(data, doseq=True).encode("utf-8")
                _hd.setdefault("Content-Type", "application/x-www-form-urlencoded")
            elif isinstance(data, str):
                _body = data.encode("utf-8")
            elif isinstance(data, (bytes, bytearray)):
                _body = bytes(data)
            if cookies:
                _hd["Cookie"] = "; ".join("%s=%s" % _kv for _kv in cookies.items())
            elif self.cookies:
                _hd.setdefault("Cookie", "; ".join("%s=%s" % _kv for _kv in self.cookies.items()))
            _to = timeout
            if isinstance(_to, (tuple, list)):
                _to = max(_to)
            if _to and float(_to) > 120:
                _to = float(_to) / 1000.0
            _last_exc = None
            for _attempt in range(2):
                _req = _ur2.Request(url, data=_body, headers=_hd, method=method.upper())
                try:
                    with self._opener.open(_req, timeout=_to or 15) as _resp:
                        try:
                            _content = _resp.read()
                        except _hc2.IncompleteRead as _ire:
                            _content = _ire.partial or b""
                        _hdrs = dict(_resp.headers.items())
                        _final = _resp.geturl()
                        _status = _resp.status
                except _ue2.HTTPError as _he:
                    try:
                        _content = _he.read()
                    except _hc2.IncompleteRead as _ire:
                        _content = _ire.partial or b""
                    except Exception:
                        _content = b""
                    _hdrs = dict(_he.headers.items()) if _he.headers else {}
                    _final = _he.geturl() if hasattr(_he, "geturl") else url
                    _status = _he.code
                except Exception as _exc:
                    _last_exc = _exc
                    continue
                try:
                    _ce = (_hdrs.get("Content-Encoding", "") or "").lower()
                    if "gzip" in _ce:
                        import gzip as _gz
                        _content = _gz.decompress(_content)
                    elif "deflate" in _ce:
                        import zlib as _zl
                        _content = _zl.decompress(_content)
                except Exception:
                    pass
                for _c in self._jar:
                    self.cookies[_c.name] = _c.value
                return requests.Response(_status, _hdrs, _content, _final, dict(self.cookies))
            raise requests.exceptions.ConnectionError(str(_last_exc))
    requests.Session.request = _sess_request
    def _resp_apparent_encoding(self):
        _ct = self.headers.get("Content-Type", "") or ""
        return _ct.split("charset=")[-1].split(";")[0].strip() if "charset=" in _ct else "utf-8"
    requests.Response.apparent_encoding = property(_resp_apparent_encoding)
    requests.Response.ok = property(lambda self: self.status_code < 400)
    requests.Response.reason = property(lambda self: "")
    def _resp_apparent_encoding(self):
        _ct = self.headers.get("Content-Type", "") or ""
        return _ct.split("charset=")[-1].split(";")[0].strip() if "charset=" in _ct else "utf-8"
    requests.Response.apparent_encoding = property(_resp_apparent_encoding)
    requests.Response.ok = property(lambda self: self.status_code < 400)
    requests.Response.reason = property(lambda self: "")
    class _ReqUtils:
        @staticmethod
        def quote(s, safe="/"):
            import urllib.parse as _up
            return _up.quote(s, safe=safe)
        @staticmethod
        def unquote(s):
            import urllib.parse as _up
            return _up.unquote(s)
    requests.utils = _ReqUtils
from urllib.parse import quote
sys.path.append('..')
from base.spider import Spider

def format_remarks(brand="蝴蝶影视", meta=""):
    clean_meta = str(meta or "").strip()
    clean_meta = re.sub(r"[\r\n\t]+", " ", clean_meta).strip()
    if clean_meta:
        return f"{brand} | {clean_meta}"
    return brand

class Spider(Spider):

    def html(self, text):
        try:
            from pyquery import PyQuery
            return PyQuery(text)
        except Exception:
            return super().html(text)

    def __init__(self):
        super().__init__()
        self.site = 'https://103.51.147.112:51120'
        self.imgCdn = 'https://103.51.147.112:51120'
        self.tgGroup = 'https://t.me/tvshare23'
        self.brandActor = '🦋 TG群: @tvshare23'
        self.brandDirector = '🦋 蝴蝶影视'

        self.session = requests.Session()
        self.session.headers.update({
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
            'Referer': 'https://103.51.147.112:51120/'
        })
        self.cateManual = {
            '电影': '1',
            '连续剧': '2',
            '动漫': '3',
            '综艺纪录': '4',
            '短剧': '6'
        }

    def init(self, extend=""):
        pass

    def getName(self):
        return "可可影视·蝴蝶版"

    def isVideoFormat(self, url):
        pass

    def manualVideoCheck(self):
        pass

    def _get_clean_title(self, item):
        titles = item.find('.v-item-title')
        for j in range(len(titles)):
            elem = titles.eq(j)
            style = elem.attr('style') or ''
            if 'display: none' in style or 'display:none' in style:
                continue
            t = elem.text().strip()
            if t and 'kekys.com' not in t:
                return t
        return ''

    def _get_clean_pic(self, item):
        pic = ''
        imgs = item.find('img')
        for j in range(len(imgs)):
            img = imgs.eq(j)
            src = img.attr('data-original') or img.attr('src') or ''
            if src and 'placeholder' not in src and 'logo_placeholder' not in src:
                pic = src
                break
        if pic and pic.startswith('/'):
            pic = self.imgCdn + pic
        return pic

    def homeContent(self, filter):
        result = {'class': [], 'filters': {}, 'list': [], 'parse': 0, 'jx': 0}
        for k, v in self.cateManual.items():
            result['class'].append({
                'type_id': str(v),
                'type_name': k
            })
        return result

    def homeVideoContent(self):
        videos = []
        try:
            url = f'{self.site}/channel/1.html'
            r = self.session.get(url, timeout=15, verify=False)
            r.encoding = 'utf-8'
            doc = self.html(r.text)
            items = doc('.module-item')
            seen = set()
            for item in items.items():
                a = item.find('.v-item')
                href = a.attr('href') or ''
                vid = self.getVid(href)
                if not vid or vid in seen:
                    continue
                seen.add(vid)

                title = self._get_clean_title(item)
                pic = self._get_clean_pic(item)

                note = ''
                bottom = item.find('.v-item-bottom span')
                if bottom.length:
                    note = bottom.text().strip()

                if title:
                    videos.append({
                        'vod_id': vid,
                        'vod_name': title,
                        'vod_pic': pic,
                        'vod_remarks': format_remarks("蝴蝶影视", note),
                        'style': {'type': 'rect', 'ratio': 0.75}
                    })
        except Exception as e:
            print(f'homeVideoContent error: {e}')
        return {'list': videos[:24], 'parse': 0, 'jx': 0}

    def categoryContent(self, tid, pg, filter, extend):
        result = {'list': [], 'parse': 0, 'jx': 0}
        page = int(pg) if pg else 1
        try:
            url = f'{self.site}/channel/{tid}.html?page={page}'
            r = self.session.get(url, timeout=15, verify=False)
            r.encoding = 'utf-8'
            doc = self.html(r.text)
            items = doc('.module-item')
            for item in items.items():
                a = item.find('.v-item')
                href = a.attr('href') or ''
                vid = self.getVid(href)
                if not vid:
                    continue

                title = self._get_clean_title(item)
                pic = self._get_clean_pic(item)

                note = ''
                bottom = item.find('.v-item-bottom span')
                if bottom.length:
                    note = bottom.text().strip()

                if title:
                    result['list'].append({
                        'vod_id': vid,
                        'vod_name': title,
                        'vod_pic': pic,
                        'vod_remarks': format_remarks("蝴蝶影视", note),
                        'style': {'type': 'rect', 'ratio': 0.75}
                    })
        except Exception as e:
            print(f'categoryContent error: {e}')

        result['page'] = page
        result['pagecount'] = page + 1 if len(result['list']) > 0 else page
        result['limit'] = len(result['list'])
        result['total'] = len(result['list'])
        return result

    def detailContent(self, ids):
        result = {'list': [], 'parse': 0, 'jx': 0}
        vid = ids[0] if ids else ''
        if not vid:
            return result
        try:
            url = f'{self.site}/detail/{vid}.html'
            r = self.session.get(url, timeout=15, verify=False)
            r.encoding = 'utf-8'
            html = r.text

            title = ''
            title_match = re.search(r'<title>(.+?)</title>', html)
            if title_match:
                title = title_match.group(1).split('-')[0].strip()
                title = re.sub(r'[𝕜𝕜𝕪𝕤𝟘𝟙𝕔𝕠𝕞.\s]+', ' ', title).strip()
                title = re.sub(r'\s+', ' ', title).strip()

            pic = ''
            og_img = re.search(r'<meta\s+property="og:image"\s+content="([^"]+)"', html)
            if og_img:
                pic = og_img.group(1)
                if pic.startswith('/'):
                    pic = self.imgCdn + pic

            desc = ''
            desc_match = re.search(r'<meta\s+name="description"\s+content="([^"]+)"', html)
            if desc_match:
                desc = desc_match.group(1).strip()

            play_from = []
            play_url = []
            episodes_by_sid = {}
            sids_in_order = []
            seen_sids = set()

            all_play = re.findall(r'<a[^>]+href="(/play/\d+-(\d+)-(\d+)\.html)"[^>]*class="episode-item"[^>]*>(.*?)</a>', html, re.DOTALL)
            if not all_play:
                all_play = re.findall(r'<a[^>]+class="episode-item"[^>]+href="(/play/\d+-(\d+)-(\d+)\.html)"[^>]*>(.*?)</a>', html, re.DOTALL)
            for href, sid, nid, link_html in all_play:
                text = re.sub(r'<[^>]+>', '', link_html).strip()
                if not text:
                    continue
                if sid not in episodes_by_sid:
                    episodes_by_sid[sid] = []
                episodes_by_sid[sid].append(f'{text}${href}')
                if sid not in seen_sids:
                    seen_sids.add(sid)
                    sids_in_order.append(sid)

            source_labels = []
            all_labels = re.findall(r'class="source-item-label"[^>]*>([^<]+)</', html)
            for label in all_labels:
                label = label.strip()
                if label:
                    source_labels.append(label)

            for i, sid in enumerate(sids_in_order):
                if sid in episodes_by_sid and episodes_by_sid[sid]:
                    if i < len(source_labels):
                        line_name = source_labels[i]
                    else:
                        line_name = f'线路{sid}'
                    if line_name == '4K':
                        continue
                    play_from.append(line_name)
                    play_url.append('#'.join(episodes_by_sid[sid]))

            full_desc = (
                f"【🔥 官方交流群: {self.tgGroup}】\n"
                f"━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n"
                f"{desc}"
            )

            vod = {
                'vod_id': vid,
                'vod_name': title,
                'vod_pic': pic,
                'type_name': '',
                'vod_year': '',
                'vod_area': '',
                'vod_remarks': '蝴蝶影视',
                'vod_actor': self.brandActor,
                'vod_director': self.brandDirector,
                'vod_content': full_desc,
                'vod_play_from': '$$$'.join(play_from) if play_from else '',
                'vod_play_url': '$$$'.join(play_url) if play_url else ''
            }
            result['list'].append(vod)
        except Exception as e:
            print(f'detailContent error: {e}')
        return result

    def playerContent(self, flag, id, vipFlags):
        result = {}
        try:
            play_url = id
            if id and not id.startswith('http'):
                play_url = self.site + id

            r = self.session.get(play_url, timeout=15, verify=False)
            r.encoding = 'utf-8'

            video_url = ''
            patterns = [
                r'src:\s*["\']([^"\']+\.(m3u8|mp4)[^"\']*)["\']',
                r'"url"\s*:\s*"([^"]+\.(m3u8|mp4)[^"]*)"',
                r"url\s*:\s*'([^']+\.(m3u8|mp4)[^']*)'",
            ]
            for pat in patterns:
                m = re.search(pat, r.text, re.DOTALL)
                if m:
                    video_url = m.group(1)
                    break
            
            if not video_url:
                all_urls = re.findall(r'https?://[^\s"\'<>]+\.(m3u8|mp4)[^\s"\'<>]*', r.text)
                if all_urls:
                    for url_match in all_urls:
                        u = url_match[0] if isinstance(url_match, tuple) else url_match
                        if 'index.m3u8' in u or 'video.m3u8' in u or '.mp4' in u:
                            video_url = u
                            break
                    if not video_url:
                        video_url = all_urls[0][0] if isinstance(all_urls[0], tuple) else all_urls[0]

            if video_url:
                result['parse'] = 0
                result['url'] = video_url
                result['jx'] = 0
                result['header'] = {
                    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
                    'Referer': self.site + '/'
                }
            else:
                result['parse'] = 1
                result['url'] = play_url
                result['jx'] = 0
                result['header'] = {
                    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
                    'Referer': self.site + '/'
                }
        except Exception as e:
            print(f'playerContent error: {e}')
            result['parse'] = 1
            result['url'] = id if id.startswith('http') else self.site + id
            result['jx'] = 0
            result['header'] = {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
                'Referer': self.site + '/'
            }
        return result

    def searchContent(self, key, quick, pg='1'):
        result = {'list': [], 'parse': 0, 'jx': 0}
        page = int(pg) if pg else 1
        try:
            search_url = f'{self.site}/search?k={quote(key)}'
            r = self.session.get(search_url, timeout=15, verify=False)
            r.encoding = 'utf-8'
            t_match = re.search(r'name="t" value="([^"]+)"', r.text)
            t = t_match.group(1) if t_match else ''
            
            if t:
                url = f'{self.site}/search?k={quote(key)}&t={quote(t)}'
                if page > 1:
                    url += f'&page={page}'
                r = self.session.get(url, timeout=15, verify=False)
                r.encoding = 'utf-8'

            doc = self.html(r.text)
            items = doc('.search-result-item')
            for item in items.items():
                href = item.attr('href') or ''
                vid = self.getVid(href)
                if not vid:
                    continue

                title = ''
                title_elem = item.find('.title')
                if title_elem.length:
                    title = title_elem.text().strip()
                if not title:
                    img = item.find('img')
                    if img.length:
                        title = img.attr('alt') or img.attr('title') or ''
                        title = title.strip()

                pic = self._get_clean_pic(item)

                if title:
                    result['list'].append({
                        'vod_id': vid,
                        'vod_name': title,
                        'vod_pic': pic,
                        'vod_remarks': '蝴蝶影视',
                        'style': {'type': 'rect', 'ratio': 0.75}
                    })
        except Exception as e:
            print(f'searchContent error: {e}')

        result['page'] = page
        result['pagecount'] = page + 1 if len(result['list']) > 0 else page
        result['limit'] = len(result['list'])
        result['total'] = len(result['list'])
        return result

    def localProxy(self, params):
        return [200, "video/MP2T", {}, ""]

    def getVid(self, url):
        if not url:
            return ''
        m = re.search(r'/detail/(\d+)\.html', url)
        if m:
            return m.group(1)
        m = re.search(r'/play/(\d+)-', url)
        if m:
            return m.group(1)
        return ''