import sys
import re
import json
try:
    import requests
    from requests.adapters import HTTPAdapter
    from requests.packages.urllib3.util.retry import Retry
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 ---
    class HTTPAdapter:
        def __init__(self, *a, **k):
            pass
    class Retry:
        def __init__(self, *a, **k):
            pass
requests.packages.urllib3.disable_warnings()

from base.spider import Spider

class Spider(Spider):
    # ========== 插件基础配置 ==========
    def getName(self):
        return "黑猫动漫"

    # ========== 初始化全局配置 ==========
    def init(self, extend=""):
        super().init(extend)
        self.site_url = "https://www.bmmdmm.com"
        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.site_url,
            "Accept-Language": "zh-CN,zh;q=0.9"
        }
        self.sess = requests.Session()
        self.sess.mount("https://", HTTPAdapter(max_retries=Retry(total=3, backoff_factor=1, status_forcelist=[500, 502, 503, 504])))
        self.sess.mount("http://", HTTPAdapter(max_retries=Retry(total=3, backoff_factor=1, status_forcelist=[500, 502, 503, 504])))
        self.page_size = 24

    # ========== 通用请求方法 ==========
    def fetch(self, url, timeout=10):
        try:
            res = self.sess.get(url, headers=self.headers, timeout=timeout, verify=False)
            res.encoding = "utf-8"
            return res
        except Exception as e:
            return None

    # ========== 首页分类接口 ==========
    def homeContent(self, filter):
        cate_list = [
            {"type_name": "最新更新", "type_id": "order=更新时间"},
            {"type_name": "日本动漫", "type_id": "region=日本"},
            {"type_name": "国产动漫", "type_id": "region=中国"},
            {"type_name": "美国动漫", "type_id": "region=美国"},
            {"type_name": "剧场版", "type_id": "genre=剧场版"},
            {"type_name": "OVA版", "type_id": "genre=OVA"},
            {"type_name": "连载动漫", "type_id": "status=连载"},
            {"type_name": "完结动漫", "type_id": "status=完结"}
        ]
        return {"class": cate_list}

    # ========== 分类列表接口 ==========
    def categoryContent(self, tid, pg, filter, extend):
        pg = int(pg) if str(pg).isdigit() else 1
        page_index = pg - 1
        list_url = f"{self.site_url}/list/?{tid}&pagesize=24&pageindex={page_index}"
        res = self.fetch(list_url)
        video_list = []
        
        if res and res.ok:
            html = res.text
            lpic_match = re.search(r'<div class="lpic">\s*<ul>(.*?)</ul>\s*</div>', html, re.S)
            if lpic_match:
                ul_html = lpic_match.group(1)
                for li in re.finditer(r'<li>(.*?)</li>', ul_html, re.S):
                    li_html = li.group(1)
                    vod_id = re.search(r'<a href=["\'](/show/\d+\.html)["\']', li_html)
                    vod_name = re.search(r'<h2>.*?<a href=["\'][^"\']*["\'] title=["\']([^"\']+)["\']', li_html, re.S)
                    if not vod_name:
                        vod_name = re.search(r'<h2>.*?>([^<]+)</a>', li_html, re.S)
                    vod_pic = re.search(r'<img[^>]+src=["\'](https?://[^"\']+)["\']', li_html)
                    vod_remarks = re.search(r'<font color="red">(.*?)</font>', li_html)
                    
                    if vod_id and vod_name and vod_pic:
                        video_list.append({
                            "vod_id": self.site_url + vod_id.group(1),
                            "vod_name": vod_name.group(1).strip(),
                            "vod_pic": vod_pic.group(1).strip(),
                            "vod_remarks": vod_remarks.group(1).strip() if vod_remarks else "",
                            "style": {"type": "rect", "ratio": 1.33}
                        })
        
        pagecount = pg + 1 if len(video_list) == self.page_size else pg
        if res and res.ok:
            total_match = re.search(r'pageindex=(\d+)"[^>]*>尾页</a>', res.text)
            if total_match:
                pagecount = int(total_match.group(1)) + 1
        
        return {
            "list": video_list,
            "page": pg,
            "pagecount": pagecount,
            "limit": self.page_size,
            "total": 99999
        }

    # ========== 视频详情接口 ==========
    def detailContent(self, ids):
        vod_id = ids[0] if ids else ""
        if not vod_id:
            return {"list": [{"vod_name": "视频ID为空"}]}
        
        detail_url = vod_id
        res = self.fetch(detail_url)
        if not res or not res.ok:
            return {"list": [{"vod_id": vod_id, "vod_name": "视频详情解析失败"}]}
        
        html = res.text
        
        title_match = re.search(r'<h1>(.*?)</h1>', html, re.S)
        vod_name = title_match.group(1).strip() if title_match else "未知名称"
        vod_name = re.sub(r'<[^>]+>', '', vod_name)
        
        pic_match = re.search(r'<div class="thumb">.*?<img[^>]+src=["\']([^"\']+)["\']', html, re.S)
        vod_pic = pic_match.group(1).strip() if pic_match else ""
        if vod_pic.startswith("//"):
            vod_pic = "https:" + vod_pic
        
        desc_match = re.search(r'<div class="info">(.*?)</div>', html, re.S)
        vod_content = re.sub(r'<[^>]+>', '', desc_match.group(1)).strip() if desc_match else ""
        
        remarks_match = re.search(r'更新至[：:]?\s*(.*?)</p>', html, re.S)
        vod_remarks = remarks_match.group(1).strip() if remarks_match else ""
        vod_remarks = re.sub(r'<[^>]+>', '', vod_remarks)
        
        type_match = re.search(r'<label>类型:</label>.*?>([^<]+)</a>', html, re.S)
        type_name = type_match.group(1).strip() if type_match else ""
        
        # 播放线路与集数解析
        play_from_list = []
        play_url_list = []
        
        menu_matches = re.findall(r'<li[^>]*onClick="setTab\(0,\d+\)"[^>]*>(.*?)</li>', html, re.S)
        movurl_blocks = re.findall(r'<div class="movurl"[^>]*>\s*<ul>(.*?)</ul>\s*</div>', html, re.S)
        
        for idx, block_html in enumerate(movurl_blocks):
            from_name = re.sub(r'<[^>]+>', '', menu_matches[idx]).strip() if idx < len(menu_matches) else f"播放{idx+1}"
            if not from_name:
                from_name = f"播放{idx+1}"
            play_from_list.append(from_name)
            
            ep_list = []
            for ep in re.finditer(r'<a href=["\'](/play/[^"\']+)["\'][^>]*title=["\']([^"\']+)["\']', block_html):
                ep_url = self.site_url + ep.group(1)
                ep_name = ep.group(2).strip()
                ep_list.append(f"{ep_name}${ep_url}")
            
            play_url_list.append("#".join(ep_list))
        
        if not play_from_list:
            return {"list": [{"vod_id": vod_id, "vod_name": "未找到播放线路"}]}
        
        detail_info = {
            "vod_id": vod_id,
            "vod_name": vod_name,
            "vod_pic": vod_pic,
            "vod_remarks": vod_remarks,
            "type_name": type_name,
            "vod_content": vod_content,
            # 核心修复：多线路分隔符必须用 $$$ 而不是 |
            "vod_play_from": "$$$".join(play_from_list),
            "vod_play_url": "$$$".join(play_url_list)
        }
        
        return {"list": [detail_info]}

    # ========== 搜索接口 ==========
    def searchContent(self, key, quick, pg=1):
        pg = int(pg) if str(pg).isdigit() else 1
        page_index = pg - 1
        search_url = f"{self.site_url}/s_all?ex=1&kw={requests.utils.quote(key)}&pageindex={page_index}"
        res = self.fetch(search_url)
        video_list = []
        
        if res and res.ok:
            html = res.text
            lpic_match = re.search(r'<div class="lpic">\s*<ul>(.*?)</ul>\s*</div>', html, re.S)
            if lpic_match:
                ul_html = lpic_match.group(1)
                for li in re.finditer(r'<li>(.*?)</li>', ul_html, re.S):
                    li_html = li.group(1)
                    vod_id = re.search(r'<a href=["\'](/show/\d+\.html)["\']', li_html)
                    vod_name = re.search(r'<h2>.*?<a href=["\'][^"\']*["\'] title=["\']([^"\']+)["\']', li_html, re.S)
                    if not vod_name:
                        vod_name = re.search(r'<h2>.*?>([^<]+)</a>', li_html, re.S)
                    vod_pic = re.search(r'<img[^>]+src=["\'](https?://[^"\']+)["\']', li_html)
                    vod_remarks = re.search(r'<font color="red">(.*?)</font>', li_html)
                    
                    if vod_id and vod_name and vod_pic:
                        video_list.append({
                            "vod_id": self.site_url + vod_id.group(1),
                            "vod_name": vod_name.group(1).strip(),
                            "vod_pic": vod_pic.group(1).strip(),
                            "vod_remarks": vod_remarks.group(1).strip() if vod_remarks else "搜索结果",
                            "style": {"type": "rect", "ratio": 1.33}
                        })
        
        pagecount = pg + 1 if len(video_list) == self.page_size else pg
        return {
            "list": video_list,
            "page": pg,
            "pagecount": pagecount,
            "limit": self.page_size,
            "total": len(video_list) if len(video_list) < 99999 else 99999
        }

    # ========== 播放解析接口 ==========
    def playerContent(self, flag, id, vipFlags):
        play_url = id.split("$")[1] if "$" in id else id
        if not play_url:
            return {"parse": 0, "url": "", "header": self.headers}
        
        return {
            "parse": 1,
            "url": play_url,
            "header": self.headers
        }
