# -*- coding: utf-8 -*-
import re
import json
import base64
# --- py578 adaptation: requests/urllib3 soft-import with embedded shim (Yingxia may lack requests) ---
class _Py578Retry:
    def __init__(self, *a, **kw):
        pass


class _Py578HTTPAdapter:
    def __init__(self, *a, **kw):
        pass

    def init_poolmanager(self, *a, **kw):
        pass

    def build_connection_pool_key_attributes(self, *a, **kw):
        return ({}, {})


class _Py578Urllib3Stub:
    class exceptions:
        class InsecureRequestWarning(Warning):
            pass

    @staticmethod
    def disable_warnings(*a, **kw):
        pass


class _Py578AdaptersNS:
    HTTPAdapter = _Py578HTTPAdapter


class _Py578PackagesNS:
    urllib3 = _Py578Urllib3Stub
try:
    import requests
    from requests.adapters import HTTPAdapter
    from requests.packages.urllib3.util.retry import Retry
except Exception:
    requests = None
if requests is None:
    # --- 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 ---

    _Session.mount = lambda self, prefix, adapter=None: None
    _Session.put = lambda self, url, data=None, **kw: self.request("PUT", url, data=data, **kw)
    _Session.delete = lambda self, url, **kw: self.request("DELETE", url, **kw)
    _RequestsShim.adapters = _Py578AdaptersNS
    _RequestsShim.packages = _Py578PackagesNS
    _RequestsShim.RequestException = _ReqExc
    _RequestsShim.Timeout = _Timeout
    _RequestsShim.ConnectionError = _ConnectionError
    _RequestsShim.HTTPError = _HTTPError
    _RequestsShim.put = staticmethod(lambda url, data=None, **kw: _Session().request("PUT", url, data=data, **kw))
    _RequestsShim.delete = staticmethod(lambda url, **kw: _Session().request("DELETE", url, **kw))
    _Response.apparent_encoding = property(lambda self: "utf-8")
    _Response.ok = property(lambda self: self.status_code < 400)
    _Response.history = []
    _Response.reason = ""
    _Response.elapsed = None

    class _Py578CookieJar(dict):
        def set(self, name, value, **kw):
            self[name] = value

        def get_dict(self):
            return dict(self)

    _py578_sess_init = _Session.__init__

    def _py578_session_init(self):
        _py578_sess_init(self)
        self.cookies = _Py578CookieJar(self.cookies)
        self.verify = False

    _Session.__init__ = _py578_session_init
    _py578_resp_init = _Response.__init__

    def _py578_response_init(self, *a, **kw):
        _py578_resp_init(self, *a, **kw)
        self.cookies = _Py578CookieJar(self.cookies or {})

    _Response.__init__ = _py578_response_init

    class _Py578Utils:
        quote = staticmethod(_uparse.quote)
        unquote = staticmethod(_uparse.unquote)
        urlencode = staticmethod(_uparse.urlencode)

    _RequestsShim.utils = _Py578Utils
    _py578_orig_request = _Session.request

    def _py578_request(self, method, url, headers=None, auth=None, files=None,
                       allow_redirects=True, **kw):
        hd = dict(headers or {})
        if isinstance(auth, (tuple, list)) and len(auth) == 2:
            import base64 as _b64
            hd["Authorization"] = "Basic " + _b64.b64encode(
                ("%s:%s" % (auth[0], auth[1])).encode("utf-8")).decode("ascii")
        data = kw.pop("data", None)
        if files:
            import uuid as _uuid
            boundary = "----py578" + _uuid.uuid4().hex
            chunks = []
            for fname, fval in files.items():
                if isinstance(fval, (tuple, list)):
                    fn = fval[0] if len(fval) > 0 else fname
                    content = fval[1] if len(fval) > 1 else b""
                    ctype = fval[2] if len(fval) > 2 else "application/octet-stream"
                else:
                    fn, content, ctype = fname, fval, "application/octet-stream"
                if isinstance(content, str):
                    content = content.encode("utf-8")
                chunks.append(("--%s\r\nContent-Disposition: form-data; name=\"%s\"; filename=\"%s\"\r\nContent-Type: %s\r\n\r\n"
                               % (boundary, fname, fn, ctype)).encode("utf-8") + bytes(content or b"") + b"\r\n")
            if isinstance(data, dict):
                for k, v in data.items():
                    chunks.append(("--%s\r\nContent-Disposition: form-data; name=\"%s\"\r\n\r\n%s\r\n"
                                   % (boundary, k, v)).encode("utf-8"))
            chunks.append(("--%s--\r\n" % boundary).encode("utf-8"))
            hd["Content-Type"] = "multipart/form-data; boundary=%s" % boundary
            return _py578_orig_request(self, method, url, headers=hd,
                                       data=b"".join(chunks), allow_redirects=allow_redirects, **kw)
        if not allow_redirects:
            class _NoRedirect(_ureq.HTTPRedirectHandler):
                def redirect_request(self, req, fp, code, msg, headers, newurl):
                    return None

            _saved = self._opener
            try:
                self._opener = _ureq.build_opener(
                    _ureq.HTTPCookieProcessor(self._jar),
                    _ureq.HTTPSHandler(context=self._ctx),
                    _NoRedirect())
                return _py578_orig_request(self, method, url, headers=hd, data=data,
                                           allow_redirects=False, **kw)
            finally:
                self._opener = _saved
        return _py578_orig_request(self, method, url, headers=hd, data=data,
                                   allow_redirects=allow_redirects, **kw)

    _Session.request = _py578_request
    HTTPAdapter = _Py578HTTPAdapter
    Retry = _Py578Retry
# --- end requests adaptation ---
from urllib.parse import quote, unquote, urlsplit, urljoin

requests.packages.urllib3.disable_warnings()

from base.spider import Spider


class Spider(Spider):
    def getName(self):
        return "STUI急救版"

    def init(self, extend=""):
        super().init(extend)

        # 入口地址（可带 ?）
        self.home_url = "https://xn---lunlizhancom-9x6wp54cjk3f481e0ksb.www-lunlizhan.com/?fulione"
        sp = urlsplit(self.home_url)
        self.base_url = f"{sp.scheme}://{sp.netloc}"
        self.site_url = self.base_url

        self.headers = {
            "User-Agent": "Mozilla/5.0 (Linux; Android 10; Mobile) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Mobile Safari/537.36",
            "Referer": self.home_url,
            "Accept-Language": "zh-CN,zh;q=0.9"
        }

        self.sess = requests.Session()
        retry = Retry(total=2, backoff_factor=0.5, status_forcelist=[500, 502, 503, 504])
        self.sess.mount("https://", HTTPAdapter(max_retries=retry))
        self.sess.mount("http://", HTTPAdapter(max_retries=retry))

        self.page_size = 20
        self.total = 9999

        # 预热cookie
        try:
            self.sess.get(self.home_url, headers=self.headers, timeout=4, verify=False)
        except Exception:
            pass

    def fetch(self, url, timeout=10):
        try:
            r = self.sess.get(url, headers=self.headers, timeout=timeout, verify=False, allow_redirects=True)
            r.encoding = r.apparent_encoding or "utf-8"
            return r
        except Exception as e:
            print("fetch error:", url, e)
            return None

    def _abs(self, u):
        if not u:
            return ""
        u = u.strip()
        if u.startswith("//"):
            return "https:" + u
        return urljoin(self.base_url + "/", u)

    def _clean(self, s):
        if not s:
            return ""
        s = re.sub(r"<.*?>", "", s, flags=re.S)
        s = s.replace("&nbsp;", " ")
        return re.sub(r"\s+", " ", s).strip()

    def _is_img(self, u):
        if not u:
            return False
        u2 = u.lower().split("?")[0]
        return u2.endswith((".jpg", ".jpeg", ".png", ".webp", ".gif", ".avif"))

    def _fix_bad_url(self, u):
        u = (u or "").strip()
        m = re.search(r'^(https?://[^/]+).*/(content/\d+\.html)', u, re.I)
        if m:
            return f"{m.group(1)}/{m.group(2)}"
        m2 = re.search(r'^(https?://[^/]+).*/(play/[^?#"\']+)', u, re.I)
        if m2:
            return f"{m2.group(1)}/{m2.group(2)}"
        return u

    def _parse_stui_list(self, html):
        out = []
        for m in re.finditer(r'<a[^>]*class="[^"]*stui-vodlist__thumb[^"]*"[^>]*>', html, re.I | re.S):
            tag = m.group(0)
            h = re.search(r'href="([^"]+)"', tag, re.I)
            t = re.search(r'title="([^"]+)"', tag, re.I)
            p = (re.search(r'data-original="([^"]+)"', tag, re.I)
                 or re.search(r'data-src="([^"]+)"', tag, re.I)
                 or re.search(r'src="([^"]+)"', tag, re.I))
            if not (h and t and p):
                continue
            pic = p.group(1).strip()
            if not self._is_img(pic):
                continue

            seg = html[m.start():m.start() + 600]
            d = re.search(r'<span[^>]*class="[^"]*vodtime[^"]*"[^>]*>(.*?)</span>', seg, re.I | re.S)

            out.append({
                "vod_id": self._abs(h.group(1).strip()),
                "vod_name": self._clean(t.group(1)),
                "vod_pic": self._abs(pic),
                "vod_remarks": self._clean(d.group(1)) if d else "",
                "style": {"type": "rect", "ratio": 1.33}
            })
        return out

    def homeContent(self, filter):
        # 固定分类，先保证可用
        return {
            "class": [
                {"type_name": "韩国伦理", "type_id": "585"},
            ]
        }

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

    def categoryContent(self, tid, pg, filter, extend):
        try:
            pg = int(pg) if str(pg).isdigit() else 1
            urls = []
            if pg == 1:
                urls.append(f"{self.base_url}/list/{tid}.html")
            urls += [
                f"{self.base_url}/list/{tid}-{pg}.html",
                f"{self.base_url}/list/{tid}.html?page={pg}",
            ]

            html = ""
            for u in urls:
                r = self.fetch(u)
                if r and r.ok:
                    html = r.text
                    if "stui-vodlist__thumb" in html:
                        break

            lst = self._parse_stui_list(html) if html else []
            return {
                "list": lst,
                "page": pg,
                "pagecount": pg + 1 if lst else pg,
                "limit": self.page_size,
                "total": self.total
            }
        except Exception as e:
            print("categoryContent error:", e)
            return {"list": [], "page": 1, "pagecount": 1, "limit": self.page_size, "total": 0}

    def detailContent(self, ids):
        try:
            vod_id = ids[0] if ids else ""
            vod_id = self._fix_bad_url(vod_id)
            if not vod_id:
                return {"list": [{"vod_name": "视频ID为空"}]}

            r = self.fetch(vod_id)
            if not (r and r.ok):
                return {"list": [{"vod_id": vod_id, "vod_name": "视频详情解析失败"}]}
            html = r.text

            name = re.search(r'<h4[^>]*class="[^"]*title[^"]*"[^>]*>(.*?)</h4>', html, re.I | re.S) \
                   or re.search(r'<h1[^>]*>(.*?)</h1>', html, re.I | re.S) \
                   or re.search(r'<title>(.*?)</title>', html, re.I | re.S)
            vod_name = self._clean(name.group(1)) if name else "未知名称"

            pic = ""
            p1 = re.search(r'var\s+postimg\s*=\s*"([^"]+)"', html, re.I)
            p2 = re.search(r'var\s+posterImg\s*=\s*"([^"]+)"', html, re.I)
            if p1 and self._is_img(p1.group(1)):
                pic = self._abs(p1.group(1))
            elif p2 and self._is_img(p2.group(1)):
                pic = self._abs(p2.group(1))

            play_url = ""
            mu = re.search(r'var\s+mac_url\s*=\s*unescape\([\'"]([^\'"]+)[\'"]\)\s*;', html, re.I | re.S)
            if mu:
                dec = unquote(mu.group(1))  # 第1集$https://xxx.m3u8
                play_url = dec if "$" in dec else f"正片${dec}"
            else:
                dm = re.search(r'(https?://[^\s\'"]+\.(?:m3u8|mp4|flv|mp3)[^\s\'"]*)', html, re.I)
                if dm:
                    play_url = f"正片${dm.group(1)}"

            return {
                "list": [{
                    "vod_id": vod_id,
                    "vod_name": vod_name,
                    "vod_pic": pic,
                    "vod_remarks": "",
                    "type_name": "",
                    "vod_content": "",
                    "vod_play_from": "主线路",
                    "vod_play_url": play_url
                }]
            }
        except Exception as e:
            print("detailContent error:", e)
            return {"list": [{"vod_name": "详情异常"}]}

    def searchContent(self, key, quick, pg=1):
        try:
            pg = int(pg) if str(pg).isdigit() else 1
            wd = quote(key)
            urls = [
                f"{self.base_url}/search/{wd}----------{pg}---.html",
                f"{self.base_url}/search.php?wd={wd}&page={pg}"
            ]
            html = ""
            for u in urls:
                r = self.fetch(u)
                if r and r.ok:
                    html = r.text
                    if "stui-vodlist__thumb" in html:
                        break
            lst = self._parse_stui_list(html) if html else []
            return {
                "list": lst,
                "page": pg,
                "pagecount": pg + 1 if lst else pg,
                "limit": self.page_size,
                "total": len(lst)
            }
        except Exception as e:
            print("searchContent error:", e)
            return {"list": [], "page": 1, "pagecount": 1, "limit": self.page_size, "total": 0}

    def playerContent(self, flag, id, vipFlags):
        try:
            play_url = id.split("$", 1)[1] if "$" in id else id
            play_url = self._fix_bad_url(play_url)

            if not play_url:
                return {"parse": 0, "url": "", "header": self.headers}

            if play_url.startswith("/"):
                play_url = self.base_url + play_url
            elif play_url.startswith("//"):
                play_url = "https:" + play_url

            low = play_url.lower()
            if any(x in low for x in [".m3u8", ".mp4", ".flv", ".mp3"]):
                return {"parse": 0, "url": play_url, "header": {"Referer": self.base_url + "/"}}

            r = self.fetch(play_url)
            if r and r.ok:
                html = r.text

                # 核心：mac_url=unescape(...)
                mu = re.search(r'var\s+mac_url\s*=\s*unescape\([\'"]([^\'"]+)[\'"]\)\s*;', html, re.I | re.S)
                if mu:
                    dec = unquote(mu.group(1))
                    real = dec.split("$", 1)[1] if "$" in dec else dec
                    real = real.strip()
                    if real.startswith("//"):
                        real = "https:" + real
                    if real.startswith(("http://", "https://")):
                        return {"parse": 0, "url": real, "header": {"Referer": self.base_url + "/"}}

                # 兼容 player_aaaa
                p = re.search(r'player_aaaa\s*=\s*(\{.*?\})\s*;', html, re.S)
                if p:
                    try:
                        data = json.loads(p.group(1))
                        u = data.get("url", "")
                        enc = str(data.get("encrypt", "0"))
                        if enc == "1":
                            u = unquote(u)
                        elif enc == "2":
                            u = unquote(base64.b64decode(u).decode("utf-8", "ignore"))
                        if u.startswith("//"):
                            u = "https:" + u
                        if u.startswith(("http://", "https://")):
                            return {"parse": 0 if any(x in u.lower() for x in [".m3u8", ".mp4", ".flv", ".mp3"]) else 1,
                                    "url": u, "header": {"Referer": self.base_url + "/"}}
                    except Exception:
                        pass

                dm = re.search(r'(https?://[^\s\'"]+\.(?:m3u8|mp4|flv|mp3)[^\s\'"]*)', html, re.I)
                if dm:
                    return {"parse": 0, "url": dm.group(1), "header": {"Referer": self.base_url + "/"}}

            return {"parse": 1, "url": play_url, "header": {"Referer": self.base_url + "/"}}
        except Exception as e:
            print("playerContent error:", e)
            return {"parse": 1, "url": "", "header": self.headers}
