import sys
import json
import re
# --- 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 ---

# --- py578 shim compat additions (RequestException/utils/cookies/mount) ---
try:
    _RequestsShim.RequestException = _ReqExc
    _RequestsShim.Timeout = _Timeout
    _RequestsShim.ConnectionError = _ConnectionError
    _RequestsShim.HTTPError = _HTTPError
    _Response.apparent_encoding = property(lambda self: "utf-8")

    class _ReqUtils(object):
        @staticmethod
        def quote(s, safe="/"):
            return _uparse.quote(str(s), safe=safe)

        @staticmethod
        def unquote(s):
            return _uparse.unquote(str(s))

    _RequestsShim.utils = _ReqUtils

    class _CookieDict(dict):
        def set(self, name, value, domain=None, path=None, **kw):
            self[name] = value

        def get_dict(self):
            return dict(self)

    _orig_session_init = _Session.__init__

    def _session_init(self):
        _orig_session_init(self)
        self.cookies = _CookieDict(self.cookies)

    _Session.__init__ = _session_init
    if not hasattr(_Session, "mount"):
        _Session.mount = lambda self, prefix, adapter=None: None
except Exception:
    pass
# --- end py578 shim compat additions ---
try:
    import requests
except Exception:
    requests = _RequestsShim

# --- embedded bs4-compatible shim (pyquery/lxml based) for Yingxia adaptation ---
# Used only when real `bs4` is unavailable; covers find/find_all/select/
# select_one/get_text/text/get/[]/name/parent/find_previous used by this spider.
class _BS4Tag(object):
    def __init__(self, el):
        self._el = el

    @property
    def name(self):
        t = self._el.tag
        return t if isinstance(t, str) else None

    @property
    def attrs(self):
        return dict(self._el.attrib)

    @property
    def parent(self):
        p = self._el.getparent()
        return _BS4Tag(p) if p is not None else None

    @property
    def text(self):
        return self.get_text()

    def get_text(self, separator="", strip=False):
        parts = list(self._el.itertext())
        if strip:
            parts = [p.strip() for p in parts if p and p.strip()]
        return separator.join(parts)

    def get(self, attr, default=None):
        v = self._el.get(attr)
        return default if v is None else v

    def has_attr(self, attr):
        return attr in self._el.attrib

    def __getitem__(self, attr):
        return self._el.attrib[attr]

    def __bool__(self):
        return True

    __nonzero__ = __bool__

    def __str__(self):
        try:
            from lxml import html as _lh
            return _lh.tostring(self._el, encoding="unicode")
        except Exception:
            return self.get_text()

    def _css(self, name, attrs, class_, kwargs):
        names = []
        if name:
            names = list(name) if isinstance(name, (list, tuple)) else [name]
        classes = []
        if class_:
            classes = str(class_).split()
        all_attrs = {}
        if attrs:
            all_attrs.update(attrs)
        for k, v in (kwargs or {}).items():
            if k == "recursive":
                continue
            kk = "class" if k == "class_" else ("id" if k == "id_" else k)
            all_attrs[kk] = v
        if "class" in all_attrs:
            classes += str(all_attrs.pop("class")).split()
        attr_sels = []
        for k, v in all_attrs.items():
            if v is True:
                attr_sels.append("[%s]" % k)
            elif v is False or v is None:
                continue
            else:
                attr_sels.append('[%s="%s"]' % (k, str(v).replace('"', "\\\"")))
        cls = "".join("." + c for c in classes)
        at = "".join(attr_sels)
        if names:
            return ", ".join("%s%s%s" % (n, cls, at) for n in names)
        return "*%s%s" % (cls, at) if (cls or at) else "*"

    def _select(self, css, recursive=True):
        from pyquery import PyQuery as _pq
        q = _pq(self._el)
        res = q(css) if recursive else q.children(css)
        return [_BS4Tag(e) for e in res]

    def select(self, css):
        try:
            return self._select(css, True)
        except Exception:
            return []

    def select_one(self, css):
        r = self.select(css)
        return r[0] if r else None

    def find_all(self, name=None, attrs=None, recursive=True, class_=None, **kwargs):
        return self._select(self._css(name, attrs, class_, kwargs), recursive)

    def find(self, name=None, attrs=None, recursive=True, class_=None, **kwargs):
        r = self.find_all(name, attrs, recursive, class_, **kwargs)
        return r[0] if r else None

    def find_previous(self, name=None, attrs=None, class_=None, **kwargs):
        try:
            from pyquery import PyQuery as _pq
            root = self._el.getroottree().getroot()
            css = self._css(name, attrs, class_, kwargs)
            matches = list(_pq(root)(css))
            last = None
            for e in _pq(root)("*"):
                if e is self._el:
                    break
                if any(e is m for m in matches):
                    last = e
            return _BS4Tag(last) if last is not None else None
        except Exception:
            return None


def _BS4_parse(markup):
    from lxml import html as _lh
    if markup is None:
        markup = ""
    if isinstance(markup, bytes):
        markup = markup.decode("utf-8", "ignore")
    markup = str(markup)
    if not markup.strip():
        return _lh.fromstring("<html><body></body></html>")
    try:
        return _lh.fromstring(markup)
    except Exception:
        try:
            return _lh.fromstring("<html><body>%s</body></html>" % markup)
        except Exception:
            return _lh.fromstring("<html><body></body></html>")


class _BeautifulSoupShim(_BS4Tag):
    def __init__(self, markup="", parser=None, *a, **kw):
        _BS4Tag.__init__(self, _BS4_parse(markup))
# --- end embedded bs4 shim ---
try:
    from bs4 import BeautifulSoup
except Exception:
    BeautifulSoup = _BeautifulSoupShim
from base.spider import Spider

class Spider(Spider):
    def getName(self):
        return "周六影库"

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

    def isVideoFormat(self, url):
        pass

    def manualVideoCheck(self):
        pass

    def homeContent(self, filter):
        result = {}
        # 手动配置主分类，适配TVBox大类菜单
        cateManual = {
            "电影": "1",
            "电视剧": "2",
            "综艺": "3",
            "动漫": "4",
            "动画片": "25",
            "体育赛事": "28"
        }
        classes = []
        for k in cateManual:
            classes.append({
                'type_name': k,
                'type_id': cateManual[k]
            })
        result['class'] = classes
        if filter:
            result['filters'] = {}
        return result

    def homeVideoContent(self):
        # 首页推荐视频，默认留空或获取最新
        return {"list": []}

    def jar_list_from_html(self, html_text):
        """
        核心解析模组：借鉴海阔影视规则，完美适配TVBox格式
        """
        soup = BeautifulSoup(html_text, 'html.parser')
        vods = []
        # 获取海阔规则对应的 .stui-vodlist 里面的 li 标签
        items = soup.select('.stui-vodlist li')
        for item in items:
            a_tag = item.select_one('a.stui-vodlist__thumb')
            if not a_tag:
                continue
            
            href = a_tag.get('href', '')
            title = a_tag.get('title', '')
            
            # 过滤广告位与无效链接
            if not href or href == '#' or '红包' in title or '广告' in title:
                continue
                
            # 兼容处理未在a标签写标题的情况
            if not title:
                h4_a = item.select_one('.stui-vodlist__title a')
                if h4_a:
                    title = h4_a.get_text(strip=True)
            
            # 提取图片路径
            img = a_tag.get('data-original', '')
            if img.startswith('//'):
                img = 'https:' + img
            elif img.startswith('/'):
                img = 'https://www.zlykw.com' + img
                
            # 提取更新状态 / 备注（对应海阔里的 .pic-text&&Text）
            remarks = ''
            remark_tag = a_tag.select_one('.pic-text')
            if remark_tag:
                remarks = remark_tag.get_text(strip=True)
                
            vods.append({
                "vod_id": href,
                "vod_name": title,
                "vod_pic": img,
                "vod_remarks": remarks
            })
        return vods

    def categoryContent(self, tid, pg, filter, extend):
        # MacCMS标准分类页处理
        if int(pg) <= 1:
            url = f"https://www.zlykw.com/vodtype/{tid}.html"
        else:
            url = f"https://www.zlykw.com/vodtype/{tid}-{pg}.html"
            
        headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36"
        }
        try:
            res = requests.get(url, headers=headers, timeout=10)
            res.encoding = 'utf-8'
            vods = self.jar_list_from_html(res.text)
            return {
                "page": pg,
                "pagecount": int(pg) + 1,
                "limit": len(vods),
                "total": len(vods) * int(pg),
                "list": vods
            }
        except Exception as e:
            return {"list": []}

    def detailContent(self, array):
        # 详情页模组
        vod_id = array[0]
        if not vod_id.startswith('http'):
            url = "https://www.zlykw.com" + vod_id
        else:
            url = vod_id
            
        headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36"
        }
        try:
            res = requests.get(url, headers=headers, timeout=10)
            res.encoding = 'utf-8'
            soup = BeautifulSoup(res.text, 'html.parser')
            
            title_tag = soup.select_one('.stui-content__detail .title')
            title = title_tag.get_text(strip=True) if title_tag else ""
            
            pic_tag = soup.select_one('.stui-content__thumb img')
            pic = pic_tag.get('data-original', '') if pic_tag else ""
            if pic.startswith('//'):
                pic = 'https:' + pic
            elif pic.startswith('/'):
                pic = 'https://www.zlykw.com' + pic
                
            actor, director, remarks, desc = "", "", "", ""
            detail_p = soup.select('.stui-content__detail p')
            for p in detail_p:
                text = p.get_text(strip=True)
                if "主演" in text:
                    actor = text.replace("主演：", "").replace("主演:", "")
                elif "导演" in text:
                    director = text.replace("导演：", "").replace("导演:", "")
                elif "类型" in text or "分类" in text:
                    remarks = text
                    
            desc_tag = soup.select_one('.stui-pannel_detail .detail') or soup.select_one('.detail-content')
            if desc_tag:
                desc = desc_tag.get_text(strip=True)
                
            vod = {
                "vod_id": vod_id,
                "vod_name": title,
                "vod_pic": pic,
                "type_name": remarks,
                "vod_remarks": remarks,
                "vod_actor": actor,
                "vod_director": director,
                "vod_content": desc
            }
            
            # 解析选集列表（MacCMS 的 stui-content__playlist 标签）
            play_froms = []
            play_urls = []
            panels = soup.select('.stui-pannel')
            source_idx = 1
            for panel in panels:
                playlist_ul = panel.select_one('ul.stui-content__playlist')
                if playlist_ul:
                    head = panel.select_one('.stui-pannel__head .title')
                    from_name = head.get_text(strip=True) if head else f"播放源 {source_idx}"
                    source_idx += 1
                    
                    links = playlist_ul.select('li a')
                    urls = []
                    for link in links:
                        name = link.get_text(strip=True)
                        href = link.get('href', '')
                        urls.append(f"{name}${href}")
                    
                    if urls:
                        play_froms.append(from_name)
                        play_urls.append("#".join(urls))
                        
            vod['vod_play_from'] = "$$$".join(play_froms)
            vod['vod_play_url'] = "$$$".join(play_urls)
            return {"list": [vod]}
        except Exception as e:
            return {"list": []}

    def searchContent(self, key, quick):
        """
        修复后的搜索模组：
        使用 requests.Session() 保持会话，先 GET 建立会话，再通过标准的 POST 传参提交
        """
        search_url = "https://www.zlykw.com/vodsearch/-------------.html"
        headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36",
            "Origin": "https://www.zlykw.com",
            "Referer": "https://www.zlykw.com/vodsearch/-------------.html"
        }
        data = {
            "wd": key,
            "submit": ""
        }
        try:
            session = requests.Session()
            # 1. 第一步先访问搜索主页获取关键的 PHPSESSID 等安全 Cookie 校验
            session.get(search_url, headers=headers, timeout=10)
            # 2. 第二步带上会话 Cookie 发送 POST 搜索数据
            res = session.post(search_url, headers=headers, data=data, timeout=10)
            res.encoding = 'utf-8'
            
            # 调用核心解析模组，完美提取搜索结果
            vods = self.jar_list_from_html(res.text)
            return {"list": vods}
        except Exception as e:
            return {"list": []}

    def playerContent(self, flag, id, vip):
        # 播放解析模组
        if not id.startswith('http'):
            url = "https://www.zlykw.com" + id
        else:
            url = id
            
        headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36"
        }
        try:
            res = requests.get(url, headers=headers, timeout=10)
            res.encoding = 'utf-8'
            
            # 正则匹配 MacCMS 播放页自带的 MacPlayer 变量
            match = re.search(r'var\s+MacPlayer\s*=\s*({.*?});', res.text)
            if match:
                player_json = json.loads(match.group(1))
                play_url = player_json.get('url', '')
                
                # 判断是否是直链视频，如果是直链让TVBox自主嗅探/播放 (parse=0)，否则交由内置解析处理 (parse=1)
                parse = 1
                if play_url.startswith('http') and ('.m3u8' in play_url or '.mp4' in play_url):
                    parse = 0
                    
                return {
                    "parse": parse,
                    "url": play_url,
                    "header": {
                        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36"
                    }
                }
            return {"parse": 1, "url": url, "header": ""}
        except Exception as e:
            return {"parse": 1, "url": url, "header": ""}

if __name__ == '__main__':
    # 测试搜索结果
    spider = Spider()
    print(spider.searchContent("主角", False))
