# -*- coding: utf-8 -*-
import sys
import re
import json
import time
from urllib.parse import quote

sys.path.append('..')
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 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://pomo.mom"
UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
CATEGORIES = {"huayurm": "华语热门", "jiating": "家庭影院", "donghuadadiany": "动画大电影", "lengmenjiapian": "冷门佳片", "paihangbang": "TOP250", "sort/12": "蓝光原盘", "dianshiju": "剧集"}

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

    def _req(self, url, headers=None, method='GET', data=None):
        try:
            try:
                r = self.fetch(url, headers=headers, method=method, data=data, timeout=30000)
            except TypeError:
                try:
                    r = self.fetch(url, headers=headers, method=method, data=data)
                except TypeError:
                    r = self.fetch(url, headers=headers)
            except Exception:
                try:
                    r = self.fetch(url, headers=headers, method=method, data=data)
                except Exception:
                    try:
                        r = self.fetch(url, headers=headers)
                    except Exception:
                        return None
            return r
        except:
            return None

    def _text(self, r):
        if r is None:
            return ""
        return r.text if hasattr(r, 'text') else str(r)

    def _ok(self, r):
        if r is None:
            return False
        if hasattr(r, 'status_code'):
            return r.status_code == 200
        return True

    def _get(self, url, referer=""):
        headers = {"User-Agent": UA, "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"}
        if referer:
            headers["Referer"] = referer
        for attempt in range(3):
            r = self._req(url, headers=headers)
            if r is None:
                time.sleep(1)
                continue
            if hasattr(r, 'status_code') and r.status_code >= 400:
                time.sleep(1)
                continue
            return self._text(r)
        return ""

    def _card(self, block):
        m = re.search(r'<a href="https?://pomo\.mom/(\d+)(?:\.html)?"[^>]*>(.*?)</a>', block, re.DOTALL)
        if not m:
            return None
        vid = m.group(1)
        b = m.group(2)
        nm = re.search(r'<h3[^>]*>(.*?)</h3>', b, re.DOTALL)
        im = re.search(r'<img[^>]*src="(https?://[^"]+)"[^>]*alt="([^"]*)"', b)
        if not im:
            im = re.search(r'<img[^>]*alt="([^"]*)"[^>]*src="(https?://[^"]+)"', b)
        tags = re.findall(r'<div class="tag">(?:IMDB)?<span[^>]*>([^<]+)</span>|class="tag">([^<]+)<', b)
        name = re.sub(r'<[^>]+>', '', nm.group(1)).strip() if nm else ''
        if not name:
            name = im.group(2).strip() if im else ''
        remark = ' '.join([x[0] or x[1] for x in tags])[:60]
        return {"vod_id": vid, "vod_name": name[:80], "vod_pic": (im.group(1) if im else ''), "vod_remarks": remark}

    def _items(self, html):
        items, seen = [], set()
        for m in re.finditer(r'<a href="https?://pomo\.mom/(\d+)(?:\.html)?" class="block h-full flex flex-col">(.*?)</a>', html, re.DOTALL):
            vid = m.group(1)
            if vid in seen:
                continue
            seen.add(vid)
            b = m.group(2)
            nm = re.search(r'<h3[^>]*>(.*?)</h3>', b, re.DOTALL)
            im = re.search(r'<img[^>]*src="(https?://[^"]+)"[^>]*alt="([^"]*)"', b)
            if not im:
                im = re.search(r'<img[^>]*alt="([^"]*)"[^>]*src="(https?://[^"]+)"', b)
            tags = re.findall(r'<div class="tag">(?:IMDB)?<span[^>]*>([^<]+)</span>|class="tag">([^<]+)<', b)
            name = re.sub(r'<[^>]+>', '', nm.group(1)).strip() if nm else ''
            if not name:
                name = im.group(2).strip() if im else ''
            items.append({
                "vod_id": vid,
                "vod_name": name[:80],
                "vod_pic": im.group(1) if im else "",
                "vod_remarks": ' '.join([x[0] or x[1] for x in tags])[:60],
            })
        for m in re.finditer(r'<a href="https?://pomo\.mom/(\d+)" class="hover:text-accent transition">([^<]+)</a>', html):
            vid = m.group(1)
            if vid in seen:
                continue
            seen.add(vid)
            i0 = html.rfind('<img', 0, m.start())
            im = re.search(r'src="(https?://[^"]+)"', html[i0:m.start()]) if i0 >= 0 else None
            items.append({"vod_id": vid, "vod_name": m.group(2).strip()[:80], "vod_pic": im.group(1) if im else "", "vod_remarks": ""})
        return items

    def homeContent(self, filter=False):
        r = {"class": [{"type_id": k, "type_name": v} for k, v in CATEGORIES.items()], "list": []}
        html = self._get(HOST)
        r["list"] = self._items(html)[:50]
        return r

    def homeVideoContent(self):
        return {"list": self._items(self._get(HOST))[:50]}

    def categoryContent(self, tid, pg=1, filter=False, extend=""):
        try:
            pn = max(int(str(pg)), 1)
        except:
            pn = 1
        cat = str(tid)
        if cat not in CATEGORIES:
            cat = "dianshiju"
        url = f"{HOST}/{cat}/page/{pn}" if pn > 1 else f"{HOST}/{cat}"
        html = self._get(url)
        items = self._items(html)
        return {"page": pn, "pagecount": self._pagecount(html, pn), "limit": 24, "total": len(items), "list": items}

    def _routes(self, html):
        routes = re.findall(r'const\s+route(\d+)Data\s*=\s*(\[[^\]]*\])', html)
        has = dict(re.findall(r'const\s+hasRoute(\d+)\s*=\s*(true|false)', html))
        out = []
        for num, data in routes:
            n = int(num)
            if n > 1 and has.get(str(n), 'true') != 'true':
                continue
            try:
                out.append((n, json.loads(data.replace('\\/', '/'))))
            except:
                pass
        return out

    def detailContent(self, ids):
        vid = ids[0] if isinstance(ids, list) else str(ids)
        m = re.search(r'(\d+)', vid)
        if not m:
            return {"list": []}
        vid = m.group(1)
        html = self._get(f"{HOST}/{vid}")
        if not html:
            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": ""}
        tn = re.search(r'<h2[^>]*class="[^"]*x-dbjs-title[^"]*"[^>]*>(.*?)</h2>', html, re.DOTALL)
        if tn:
            d["vod_name"] = re.sub(r'<[^>]+>', '', tn.group(1)).strip()
        else:
            tn = re.search(r'<title>(.*?)</title>', html)
            if tn:
                d["vod_name"] = re.sub(r'\s*-\s*4K原盘免费下载\s*$', '', tn.group(1)).strip()
        pm = re.search(r'<meta[^>]+name="description"[^>]+content="([^"]*)"', html)
        if pm:
            d["vod_content"] = pm.group(1).strip()[:500]
        pi = re.search(r'src="(https?://[^"]*poster_[^"]+\.(?:jpg|jpeg|webp))"', html)
        if not pi:
            pi = re.search(r'src="(https?://[^"]+\.(?:jpg|jpeg|webp))"', html)
        if pi:
            d["vod_pic"] = pi.group(1)
        for key, pat in (("vod_director", r'导演：</span>([^<]+)<'), ("vod_area", r'国家：</span>([^<]+)<'), ("vod_class", r'类型：</span>([^<]+)<')):
            mm = re.search(pat, html)
            if mm:
                d[key] = mm.group(1).strip()
        ym = re.search(r'时间：</span>(\d{4})', html)
        if ym:
            d["vod_year"] = ym.group(1)
        mags = re.findall(r'data-url="(magnet:[^"]+)"', html)
        if mags:
            d["vod_remarks"] = f"{len(mags)}个磁力源"
        ph = self._get(f"{HOST}/?plugin=plyr_player&gid={vid}")
        routes = self._routes(ph)
        if routes:
            pf, pu = [], []
            for n, arr in routes:
                eps = [x.split('$') for x in arr if '$' in x]
                if not eps:
                    continue
                pf.append(f"线路{n}")
                pu.append("#".join([f"{e[0].strip()}${vid}-{n}-{i}" for i, e in enumerate(eps)]))
            if pf:
                d["vod_play_from"] = "$$$".join(pf)
                d["vod_play_url"] = "$$$".join(pu)
        return {"list": [d]}

    def searchContent(self, key, quick=False, pg="1"):
        try:
            html = self._get(f"{HOST}/search/?keyword={quote(key)}")
            return {"list": self._items(html), "page": 1}
        except:
            return {"list": []}

    def playerContent(self, flag, id, vipFlags=None):
        try:
            m = re.search(r'(\d+)-(\d+)-(\d+)', str(id))
            if not m:
                return {"url": ""}
            vid, rn, ei = m.group(1), int(m.group(2)), int(m.group(3))
            ph = self._get(f"{HOST}/?plugin=plyr_player&gid={vid}")
            routes = self._routes(ph)
            for n, arr in routes:
                if n == rn:
                    if ei >= len(arr):
                        return {"url": ""}
                    item = arr[ei]
                    url = item.split('$')[1] if '$' in item else item
                    if not url.startswith('http'):
                        return {"url": ""}
                    return {"parse": 0, "url": url}
            return {"url": ""}
        except:
            return {"url": ""}

    def localProxy(self, param):
        pass

    def _pagecount(self, html, current_page=1):
        pages = re.findall(r'/page/(\d+)', html)
        max_page = current_page
        for p in pages:
            try:
                n = int(p)
                if n > max_page:
                    max_page = n
            except:
                pass
        if max_page == current_page and re.search(r'下一页|page/%d' % (current_page + 1), html):
            max_page = current_page + 1
        return max_page

    def getName(self):
        return "POMO4K"

    def isVideoFormat(self, url):
        pass

    def manualVideoCheck(self):
        pass

    def destroy(self):
        pass
