# -*- coding: utf-8 -*-
#神秘
import re
import urllib.parse
from base.spider import Spider as BaseSpile
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 ---
    # --- py578 shim compat patches (only run when real requests is missing) ---
    _Response.ok = property(lambda self: self.status_code < 400)
    _Response.apparent_encoding = property(lambda self: "utf-8")
    def _shim_mount(self, *a, **k):
        return None
    _Session.mount = _shim_mount
    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_patched(self):
        _orig_session_init(self)
        self.cookies = _CookieDict(self.cookies)
        self.proxies = {}
    _Session.__init__ = _session_init_patched
    _orig_request = _Session.request
    def _request_patched(self, method, url, headers=None, data=None, files=None, **kw):
        if files:
            boundary = "----py578FormBoundary7MA4YWxkTrZu0gW"
            chunks = []
            items = files.items() if isinstance(files, dict) else files
            for k, v in items:
                if isinstance(v, (tuple, list)):
                    filename = v[0] if len(v) > 0 else None
                    val = v[1] if len(v) > 1 else ""
                    ctype = v[2] if len(v) > 2 else None
                else:
                    filename, val, ctype = None, v, None
                if hasattr(val, "read"):
                    val = val.read()
                if isinstance(val, str):
                    val_b = val.encode("utf-8")
                elif isinstance(val, (bytes, bytearray)):
                    val_b = bytes(val)
                else:
                    val_b = str(val).encode("utf-8")
                head = '--%s\r\nContent-Disposition: form-data; name="%s"' % (boundary, k)
                if filename:
                    head += '; filename="%s"' % filename
                head += "\r\n"
                if ctype:
                    head += "Content-Type: %s\r\n" % ctype
                elif filename:
                    head += "Content-Type: application/octet-stream\r\n"
                head += "\r\n"
                chunks.append(head.encode("utf-8") + val_b + b"\r\n")
            chunks.append(("--%s--\r\n" % boundary).encode("utf-8"))
            body = b"".join(chunks)
            hd = dict(headers or {})
            hd["Content-Type"] = "multipart/form-data; boundary=%s" % boundary
            return _orig_request(self, method, url, headers=hd, data=body, **kw)
        return _orig_request(self, method, url, headers=headers, data=data, **kw)
    _Session.request = _request_patched
    _RequestsShim.RequestException = _ReqExc
    _RequestsShim.Timeout = _Timeout
    _RequestsShim.ConnectionError = _ConnectionError
    _RequestsShim.HTTPError = _HTTPError
    class _ReqUtils:
        quote = staticmethod(_uparse.quote)
        unquote = staticmethod(_uparse.unquote)
        urlencode = staticmethod(_uparse.urlencode)
    _RequestsShim.utils = _ReqUtils
    class _ReqPackages:
        class urllib3:
            @staticmethod
            def disable_warnings(*a, **k):
                pass
    _RequestsShim.packages = _ReqPackages
    # --- end py578 shim compat patches ---
try:
    from bs4 import BeautifulSoup
except Exception:
    # --- embedded minimal BeautifulSoup-compatible shim (lxml based) ---
    from lxml import html as _lxml_html
    from lxml.cssselect import CSSSelector as _CSSSelector
    class _BSTag:
        def __init__(self, el):
            self._el = el
        @property
        def name(self):
            return self._el.tag if isinstance(self._el.tag, str) else None
        def _wrap(self, els):
            return [_BSTag(e) for e in els if isinstance(e.tag, str)]
        def select(self, css):
            if self._el is None:
                return []
            try:
                return self._wrap(_CSSSelector(css)(self._el))
            except Exception:
                return []
        def select_one(self, css):
            r = self.select(css)
            return r[0] if r else None
        def _matches(self, el, name, class_, id_, attrs):
            if name and el.tag != name:
                return False
            if class_:
                classes = (el.get("class") or "").split()
                want = class_.split() if isinstance(class_, str) else list(class_)
                if not all(c in classes for c in want):
                    return False
            if id_ is not None and el.get("id") != id_:
                return False
            for k, v in (attrs or {}).items():
                if el.get(k) != v:
                    return False
            return True
        def find_all(self, name=None, attrs=None, class_=None, id=None, **kw):
            if "class" in kw:
                class_ = kw.pop("class")
            merged = dict(attrs or {})
            merged.update(kw)
            names = set(name) if isinstance(name, (list, tuple)) else None
            out = []
            for el in self._el.iter():
                if el is self._el or not isinstance(el.tag, str):
                    continue
                if names is not None and el.tag not in names:
                    continue
                if self._matches(el, name if names is None else None, class_, id, merged):
                    out.append(_BSTag(el))
            return out
        def find(self, name=None, attrs=None, class_=None, id=None, **kw):
            r = self.find_all(name, attrs, class_, id, **kw)
            return r[0] if r else None
        def get_text(self, separator="", strip=False):
            texts = list(self._el.itertext())
            if strip:
                texts = [t.strip() for t in texts if t.strip()]
            return separator.join(texts)
        @property
        def text(self):
            return self.get_text()
        @property
        def string(self):
            if self._el.tag in ("script", "style"):
                return self._el.text_content()
            if len(self._el) == 0:
                return self._el.text if self._el.text is not None else None
            return None
        def get(self, key, default=None):
            v = self._el.get(key)
            return default if v is None else v
        def has_attr(self, key):
            return key in self._el.attrib
        def __getitem__(self, key):
            return self._el.attrib[key]
        @property
        def attrs(self):
            return dict(self._el.attrib)
        @property
        def parent(self):
            p = self._el.getparent()
            return _BSTag(p) if p is not None else None
        def __bool__(self):
            return True
        def __repr__(self):
            return "<_BSTag %s>" % (self.name,)
    class BeautifulSoup(_BSTag):
        def __init__(self, markup="", features=None, *a, **k):
            if isinstance(markup, (bytes, bytearray)):
                data = bytes(markup)
            else:
                data = str(markup or "").encode("utf-8", "ignore")
            if not data.strip():
                data = b"<html></html>"
            try:
                el = _lxml_html.fromstring(data, parser=_lxml_html.HTMLParser(encoding="utf-8"))
            except Exception:
                el = _lxml_html.fromstring(b"<html></html>")
            super().__init__(el)
    # --- end embedded BeautifulSoup shim ---


class VideoDecryptor:
    """XOR 128 解密"""
    @staticmethod
    def decrypt(text: str) -> str:
        if not text:
            return ""
        try:
            return ''.join(chr(128 ^ ord(c)) for c in text)
        except:
            return text

    @staticmethod
    def from_js(js: str) -> str:
        return VideoDecryptor.decrypt(m.group(1)) if (m := re.search(r"document\.write\(l\('([^']+)'\)\)", js)) else ""


class Spider(BaseSpile):

    def init(self, extend=""):
        self.host = "https://h4ivs.sm431.vip"
        self.video_host = "https://38.je:38"
        self.image_host = "https://36.je:36"
        self.headers = {
            "User-Agent": "Mozilla/5.0 (Linux; Android 13; 22127RK46C Build/TKQ1.220905.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/104.0.5112.97 Mobile Safari/537.36",
            "Referer": self.host,
            "Accept-Language": "zh-CN,zh;q=0.9",
        }
        self.cache = {}

    def get(self, url):
        try:
            r = requests.get(url, headers=self.headers, timeout=15)
            r.raise_for_status()
            r.encoding = "utf-8"
            return r.text
        except:
            return "神秘电影"

    def img_url(self, url):
        """格式化图片URL"""
        if not url:
            return ""
        if url.startswith("//"):
            url = "https:" + url
        elif url.startswith("/"):
            url = self.image_host + url
        return f"{url}@User-Agent={self.headers['User-Agent']}@Referer={self.host}/"

    def parse(self, el):
        """解析卡片"""
        a = el if el.name == 'a' else el.find('a')
        if not a or not (href := a.get("href", "")):
            return None
        
        href = self.host + href if href.startswith("/") else href
        if not (vid := re.search(r"/vid/(\d+)", href)):
            return None
        
        vid = vid.group(1)
        title = ""

        # 解密标题
        if p := el.find('p'):
            if s := p.find('script'):
                if s.string:
                    title = VideoDecryptor.from_js(s.string)
            title = title or p.get_text(strip=True)
        
        if not title:
            for attr in ['data-title', 'data-name', 'title']:
                if el.has_attr(attr) and (val := el[attr]):
                    if (de := VideoDecryptor.decrypt(val)) and len(de) > 3:
                        title = de
                        break
        
        title = title or "未知标题"
        if title != "未知标题":
            self.cache[vid] = title

        # 图片
        img = ""
        if node := el.select_one("img"):
            img = node.get("data-src") or node.get("src") or ""
        img = img or f"{self.image_host}/{vid}.jpg"

        return {
            "vod_id": vid,
            "vod_name": title,
            "vod_pic": self.img_url(img),
            "vod_remarks": "",
        }

    def get_title(self, vid):
        """从缓存或首页获取标题"""
        if vid in self.cache:
            return self.cache[vid]
        
        if html := self.get(self.host):
            soup = BeautifulSoup(html, "html.parser")
            for link in soup.select('a[href*="/vid/"]'):
                if f'/vid/{vid}' in link.get('href', ''):
                    if p := link.find('p'):
                        if s := p.find('script'):
                            if s.string and (t := VideoDecryptor.from_js(s.string)):
                                self.cache[vid] = t
                                return t
                        if t := p.get_text(strip=True):
                            self.cache[vid] = t
                            return t
        return None

    def homeContent(self, filter):
        return {
            "class": [
                {"type_name": "国产", "type_id": "1"},
                {"type_name": "日本", "type_id": "2"},
                {"type_name": "韩国", "type_id": "3"},
                {"type_name": "欧美", "type_id": "4"},
                {"type_name": "三级", "type_id": "5"},
                {"type_name": "动漫", "type_id": "6"},
            ]
        }

    def homeVideoContent(self):
        if not (html := self.get(self.host)):
            return {"list": []}
        
        soup = BeautifulSoup(html, "html.parser")
        videos = [v for v in (self.parse(el) for el in soup.select(".vodbox, .stui-vodlist__box, .vodlist__box, .video-card, .item")) if v]
        
        if not videos:
            videos = [{"vod_id": v, "vod_name": "未知标题", "vod_pic": self.img_url(f"{self.image_host}/{v}.jpg"), "vod_remarks": ""} 
                     for v in re.findall(r'\[]\(/vid/(\d+)\.html\)', html)]
        
        return {"list": videos}

    def categoryContent(self, tid, pg, filter, extend):
        if tid == "0":
            url = self.host if int(pg) == 1 else f"{self.host}/page/{pg}.html"
        else:
            url = f"{self.host}/list/{tid}.html" if int(pg) == 1 else f"{self.host}/list/{tid}/{pg}.html"
        
        if not (html := self.get(url)):
            return {"list": [], "page": pg, "pagecount": 1, "limit": 30, "total": 0}
        
        soup = BeautifulSoup(html, "html.parser")
        videos = [v for v in (self.parse(el) for el in soup.select(".vodbox, .stui-vodlist__box, .vodlist__box, .video-card, .item")) if v]
        
        if not videos:
            videos = [{"vod_id": v, "vod_name": "未知标题", "vod_pic": self.img_url(f"{self.image_host}/{v}.jpg"), "vod_remarks": ""} 
                     for v in re.findall(r'\[]\(/vid/(\d+)\.html\)', html)]
        
        last = max([int(m.group(1)) for a in soup.select("a[href*='list/']") if (m := re.search(r"/list/\d+/(\d+)\.html", a.get("href", "")))], default=int(pg))
        
        return {"list": videos, "page": pg, "pagecount": max(last, 1), "limit": 30, "total": 99999}

    def searchContent(self, key, quick, pg="1"):
        url = f"{self.host}/so.html"
        params = {"wd": key}
        if int(pg) > 1:
            params["page"] = pg
        
        html = ""
        for method in [requests.get, requests.post]:
            try:
                r = method(url, params=params if method == requests.get else None, 
                          data=params if method == requests.post else None, 
                          headers=self.headers, timeout=15)
                r.raise_for_status()
                r.encoding = "utf-8"
                html = r.text
                break
            except:
                continue
        
        if not html:
            return {"list": []}
        
        soup = BeautifulSoup(html, "html.parser")
        videos = [v for v in (self.parse(el) for el in soup.select(".vodbox, .stui-vodlist__box, .vodlist__box, .video-card, .item")) if v]
        
        if not videos:
            videos = [{"vod_id": v, "vod_name": "未知标题", "vod_pic": self.img_url(f"{self.image_host}/{v}.jpg"), "vod_remarks": ""} 
                     for v in re.findall(r'\[]\(/vid/(\d+)\.html\)', html)]
        
        last = max([int(m.group(1)) for a in soup.select("a[href*='so.html'], .pagination a, .page-link") 
                   if (m := re.search(r"[?&]page=(\d+)", a.get("href", "")))], default=int(pg))
        
        return {"list": videos, "page": pg, "pagecount": max(last, 1), "limit": 30, "total": 99999}

    def detailContent(self, ids):
        vid = ids[0]
        if not (html := self.get(f"{self.host}/vid/{vid}.html")):
            return {"list": []}
        
        soup = BeautifulSoup(html, "html.parser")
        
        # 标题
        title = self.get_title(vid)
        if not title:
            if t := soup.find('title'):
                title = re.sub(r'\s*[-_|]\s*.{0,20}$', '', t.get_text(strip=True)).strip()
            
            if not title or len(title) < 5:
                for sel in ['h1', 'h2', '.video-title', '.title']:
                    if (el := soup.select_one(sel)) and (txt := el.get_text(strip=True)) and len(txt) > 5:
                        title = txt
                        break
        
        title = title or f"视频{vid}"
        
        # 图片
        pic = ""
        for sel in ['.picbox img', '.vodimg img', '.video-pic img', '.poster img', 'img[data-id]']:
            if (node := soup.select_one(sel)) and (p := node.get("data-src") or node.get("src")) and 'favicon' not in p.lower():
                pic = p
                break
        
        if not pic or 'favicon' in pic.lower():
            if meta := soup.select_one('meta[property="og:image"]'):
                pic = meta.get('content', '')
        
        pic = pic or f"{self.image_host}/{vid}.jpg"
        
        # 简介
        desc = soup.select_one(".vodinfo, .video-info, .content, .intro, .description")
        desc = desc.get_text(strip=True) if desc else ""
        
        return {"list": [{
            "vod_id": vid,
            "vod_name": title,
            "vod_pic": self.img_url(pic),
            "vod_content": desc,
            "vod_play_from": "神秘线路",
            "vod_play_url": f"全集${vid}@@0@@1",
        }]}

    def playerContent(self, flag, id, vipFlags):
        vid = id.split("@@")[0]
        return {"parse": 0, "url": f"{self.video_host}/{vid}/hls/index.m3u8", "header": self.headers}

    def localProxy(self, param):
        return {"code": 404, "content": ""}

    def isVideoFormat(self, url):
        return ".m3u8" in url.lower()

    def manualVideoCheck(self):
        pass

    def destroy(self):
        pass
