# -*- coding: utf-8 -*-
import sys
import re
import json
import base64
from urllib.parse import urljoin, quote, unquote
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

sys.path.append('..')
try:
    from base.spider import Spider
except ImportError:
    class Spider:
        def fetch(self, url, headers=None, **kw):
            rq = requests
            kw.pop('timeout', None)
            r = rq.get(url, headers=headers, timeout=15, **kw)
            r.encoding = 'utf-8'
            return r

HOST = "https://www.moxy.top"
UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"

class Spider(Spider):
    def init(self, extend=""):
        global HOST
        try:
            r = self.fetch(HOST, headers={"User-Agent": UA}, timeout=15000)
            if hasattr(r, 'url') and r.url and "moxy" not in r.url:
                HOST = r.url.rstrip("/")
        except:
            pass

    def homeContent(self, filter=False):
        r = {"class": [], "list": [], "filter": {}}
        for k, v in {"1":"电影","2":"连续剧","3":"综艺","4":"动漫","5":"短剧"}.items():
            r["class"].append({"type_id": k, "type_name": v})
        try:
            resp = self.fetch(HOST, headers={"User-Agent": UA}, timeout=30000)
            html = resp.text if hasattr(resp, 'text') else str(resp)
            r["list"] = self._items(html)[:60]
        except:
            pass
        return r

    def homeVideoContent(self):
        return {"list": []}

    def categoryContent(self, tid, pg=1, filter=False, extend=""):
        pn = 1
        try: pn = max(int(str(pg)), 1)
        except: pass
        cid = str(tid) if str(tid) in "12345" else "1"
        try:
            if pn > 1:
                url = f"{HOST}/vodshow/{cid}--------{pn}---.html"
            else:
                url = f"{HOST}/vodshow/{cid}-----------.html"
            resp = self.fetch(url, headers={"User-Agent": UA}, timeout=30000)
            html = resp.text if hasattr(resp, 'text') else str(resp)
            items = self._items(html)
            return {"page": pn, "pagecount": self._pagecount(html), "limit": 50, "total": len(items), "list": items}
        except:
            return {"page": pn, "pagecount": 1, "limit": 50, "total": 0, "list": []}

    def detailContent(self, ids):
        if isinstance(ids, list):
            vid = ids[0] if ids else ""
        else:
            vid = str(ids) if ids else ""
        m = re.search(r'(\d+)', str(vid))
        vid = m.group(1) if m else ""
        if not vid: return {"list": []}
        try:
            resp = self.fetch(f"{HOST}/voddetail{vid}.html", headers={"User-Agent": UA}, timeout=30000)
            h = resp.text if hasattr(resp, 'text') else str(resp)
        except:
            return {"list": []}
        d = {"vod_id": vid, "vod_name": "", "vod_pic": "", "vod_year": "",
             "vod_area": "", "vod_class": "", "vod_director": "", "vod_actor": "",
             "vod_content": "", "vod_remarks": "", "vod_play_from": "", "vod_play_url": ""}
        t1 = re.search(r'<h1[^>]*>(.*?)</h1>', h, re.S)
        if t1: d["vod_name"] = t1.group(1).strip()
        if not d["vod_name"]:
            t2 = re.search(r'<title>(.*?)</title>', h)
            if t2: d["vod_name"] = t2.group(1).split("-")[0].strip()
        p = re.search(r'data-original="([^"]+)"', h)
        if p: d["vod_pic"] = p.group(1)
        for t in re.findall(r'<a[^>]*title="(\d{4})"', h):
            d["vod_year"] = t
        for t in re.findall(r'<a[^>]*title="([^"]*)"', h):
            if t in ("中国大陆","中国","香港","台湾","美国","日本","韩国","英国","法国","泰国","印度"):
                d["vod_area"] = t
        desc = re.search(r'<div[^>]*class="[^"]*module-info-introduction-content[^"]*"[^>]*>\s*<p>(.*?)</p>', h, re.S)
        if desc: d["vod_content"] = re.sub(r'<[^>]+>', '', desc.group(1)).strip()[:500]
        for m in re.finditer(r'<div[^>]*class="[^"]*module-info-item[^"]*"[^>]*>(.*?)</div>', h, re.S):
            t = re.sub(r'<[^>]+>', '', m.group(1)).strip()
            if "导演" in t: d["vod_director"] = t.replace("导演：","").replace("导演:","").strip()
            elif "主演" in t: d["vod_actor"] = t.replace("主演：","").replace("主演:","").strip()
            elif "备注" in t: d["vod_remarks"] = t.replace("备注：","").replace("备注:","").strip()
        try:
            sources = re.findall(r'data-dropdown-value="([^"]+)"', h) or ["默认"]
            blocks = re.findall(r'<div[^>]*class="[^"]*module-play-list[^"]*"[^>]*>(.*?)</div>\s*</div>\s*</div>', h, re.S)
            if not blocks:
                blocks = re.findall(r'<div[^>]*class="[^"]*module-play-list-content[^"]*"[^>]*>(.*?)</div>', h, re.S)
            pf, pu = [], []
            for i, blk in enumerate(blocks):
                eps = re.findall(r'<a[^>]*href="(/vodplay/[^"]+)"[^>]*>(?:<[^>]+>)*([^<]{1,20})(?:</[^>]+>)*</a>', blk, re.S)
                if not eps:
                    eps = re.findall(r'<a[^>]*href="(/vodplay/[^"]+)"[^>]*>.*?<span>(.*?)</span>', blk, re.S)
                if eps:
                    src = sources[i] if i < len(sources) else f"源{i+1}"
                    el = [f"{n.strip()}${urljoin(HOST, u)}" for u, n in eps if n.strip()]
                    if el:
                        pf.append(src)
                        pu.append("#".join(el))
            if pf:
                d["vod_play_from"] = "$$$".join(pf)
                d["vod_play_url"] = "$$$".join(pu)
        except:
            pass
        return {"list": [d]}

    def searchContent(self, key, quick=False, pg="1"):
        try:
            url = f"{HOST}/vodsearch/{quote(str(key))}-------------.html"
            resp = self.fetch(url, headers={"User-Agent": UA}, timeout=15000)
            html = resp.text if hasattr(resp, 'text') else str(resp)
            if len(html) > 200:
                return {"list": self._items(html)[:30]}
        except:
            pass
        return {"list": []}

    def playerContent(self, flag, id, vipFlags=None):
        a, b = str(flag), str(id) if id else ""
        if a.startswith("http") or "/vodplay/" in a:
            url = a
        elif b.startswith("http") or "/vodplay/" in b:
            url = b
        elif a.startswith("/"):
            url = urljoin(HOST, a)
        elif b.startswith("/"):
            url = urljoin(HOST, b)
        else:
            url = a
        try:
            resp = self.fetch(url, headers={"User-Agent": UA}, timeout=30000)
            h = resp.text if hasattr(resp, 'text') else str(resp)
        except:
            return {"url": ""}
        pd = re.search(r'player_data\s*=\s*(\{.*?\})', h, re.S)
        if pd:
            try:
                data = json.loads(pd.group(1))
                u = data.get("url", "")
                if u:
                    try:
                        real_url = unquote(base64.b64decode(u).decode("utf-8"))
                    except:
                        real_url = u
                    if real_url.startswith("http"):
                        return {"url": real_url}
            except:
                pass
        return {"url": ""}

    def localProxy(self, param):
        pass

    def _pagecount(self, html):
        pc = 1
        last = re.search(r'<a[^>]*href="[^"]*vodshow/\d+[^"]*(\d+)---\.html"[^>]*>尾页', html, re.S)
        if last:
            pc = max(pc, int(last.group(1)))
        page_links = re.findall(r'<a[^>]*href="[^"]*vodshow/\d+-(\d+)', html)
        for p in page_links:
            try:
                n = int(p)
                if n <= 100:
                    pc = max(pc, n)
            except:
                pass
        all_nums = re.findall(r'class="[^"]*page-number[^"]*"[^>]*>\s*(\d+)\s*<', html)
        for n in all_nums:
            try: pc = max(pc, int(n))
            except: pass
        return pc

    def _items(self, html):
        items, seen = [], set()
        def ext(href, block):
            v = re.search(r'/voddetail(\d+)\.html', href)
            if not v or v.group(1) in seen: return None
            seen.add(v.group(1))
            t = (re.search(r'title="([^"]*)"', block) or re.search(r'alt="([^"]*)"', block))
            if not t: return None
            p = re.search(r'data-original="([^"]+)"', block)
            n = re.search(r'<div[^>]*class="[^"]*module-item-note[^"]*"[^>]*>([^<]+)</div>', block)
            return {"vod_id": v.group(1), "vod_name": t.group(1),
                    "vod_pic": p.group(1) if p else "",
                    "vod_remarks": n.group(1).strip() if n else "",
                    "vod_url": urljoin(HOST, href)}
        for m in re.finditer(
            r'<a[^>]*href="(/voddetail\d+\.html)"[^>]*title="([^"]*)"[^>]*class="[^"]*module-poster-item[^"]*"[\s\S]*?</a>',
            html
        ):
            item = ext(m.group(1), m.group(0))
            if item: items.append(item)
        for m in re.finditer(
            r'<a[^>]*href="(/voddetail\d+\.html)"[^>]*class="[^"]*module-card-item-poster[^"]*"[\s\S]*?</a>',
            html
        ):
            item = ext(m.group(1), m.group(0))
            if item: items.append(item)
        return items
