#!/usr/bin/env python3
import html
import json
import os
import re
import sys
from urllib.parse import parse_qs, unquote, urlparse

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 augment: adapters/packages/utils/exceptions/mount ---
    class _HTTPAdapterStub:
        def __init__(self, *a, **k):
            pass


    class _RetryStub:
        def __init__(self, *a, **k):
            pass


    class _AdaptersNS:
        HTTPAdapter = _HTTPAdapterStub


    class _U3NS:
        @staticmethod
        def disable_warnings(*a, **k):
            pass


    class _PackagesNS:
        urllib3 = _U3NS


    class _UtilsNS:
        @staticmethod
        def quote(s, safe='/'):
            return _uparse.quote(s, safe=safe)


    class _TooManyRedirects(_ReqExc):
        pass


    _RequestsShim.adapters = _AdaptersNS
    _RequestsShim.packages = _PackagesNS
    _RequestsShim.utils = _UtilsNS
    _RequestsShim.RequestException = _ReqExc
    _RequestsShim.ConnectionError = _ConnectionError
    _RequestsShim.Timeout = _Timeout
    _RequestsShim.HTTPError = _HTTPError
    _RequestsShim.TooManyRedirects = _TooManyRedirects
    _Exceptions.TooManyRedirects = _TooManyRedirects
    _Exceptions.SSLError = _ConnectionError
    _Exceptions.RetryError = _ReqExc


    def _py578_sess_mount(self, prefix, adapter=None):
        pass


    _Session.mount = _py578_sess_mount
    _py578_sess_init = _Session.__init__


    def _py578_sess_init2(self):
        _py578_sess_init(self)
        self.proxies = {}
        self.trust_env = True


    _Session.__init__ = _py578_sess_init2
    _Response.apparent_encoding = property(lambda self: 'utf-8')
    _Response.ok = property(lambda self: self.status_code < 400)
    # --- end py578 shim augment ---

BASE_URL = "https://naixxzy.com"
API_URL = BASE_URL + "/api.php/provide/vod/"

session = requests.Session()
session.headers.update({
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
})

HTTP_URL_RE = re.compile(r'https?://[^\s<>"\']+|//[^\s<>"\']+|www\.[^\s<>"\']+')
MEDIA_HINTS = (".m3u8", ".mp4", ".m4v", ".mov", ".webm", ".flv", ".avi", ".mkv")

def normalize_url(url):
    if not url:
        return ""
    value = str(url).strip()
    value = value.replace("\\/", "/").replace("&amp;", "&")
    value = value.strip(" '\"\t\r\n")
    if value.startswith("//"):
        value = "https:" + value
    elif value.startswith("/"):
        value = BASE_URL.rstrip("/") + value
    elif value.startswith("www."):
        value = "https://" + value
    return value

def split_candidate_urls(text):
    if not text:
        return []
    matches = HTTP_URL_RE.findall(text)
    if matches:
        return matches
    compact = text.strip()
    if compact.startswith("/"):
        return [compact]
    if " " not in compact and "\n" not in compact and "/" in compact:
        return [compact]
    return []

def score_play_url(url):
    lower = url.lower()
    score = 0
    if lower.startswith("https://"):
        score += 40
    elif lower.startswith("http://"):
        score += 30
    if ".m3u8" in lower:
        score += 500
    elif any(ext in lower for ext in (".mp4", ".m4v", ".mov", ".webm")):
        score += 450
    elif any(ext in lower for ext in (".flv", ".avi", ".mkv")):
        score += 350
    if "m3u8" in lower:
        score += 60
    if "index" in lower:
        score += 10
    if "?url=" in lower or "jiexi" in lower or "parser" in lower:
        score -= 80
    if "player/" in lower and not any(ext in lower for ext in MEDIA_HINTS):
        score -= 40
    return score

def extract_nested_media_url(url):
    try:
        parsed = urlparse(url)
        query = parse_qs(parsed.query)
    except Exception:
        return ""
    for key in ("url", "vid", "play", "source"):
        for value in query.get(key, []):
            nested = normalize_url(unquote(value))
            if nested.startswith("http") and nested != url:
                return nested
    return ""

def extract_play_urls(play_url_raw):
    if not play_url_raw:
        return []
    raw = str(play_url_raw).strip()
    groups = [part.strip() for part in raw.split("$$$") if part.strip()] or [raw]
    urls = []
    seen = set()
    for group in groups:
        episodes = [part.strip() for part in group.split("#") if part.strip()] or [group]
        for episode in episodes:
            candidates = episode.split("$")[1:] if "$" in episode else [episode]
            for candidate in candidates:
                for url in split_candidate_urls(candidate):
                    final_url = normalize_url(url)
                    nested_url = extract_nested_media_url(final_url)
                    for picked_url in (nested_url, final_url):
                        if not picked_url or picked_url in seen:
                            continue
                        seen.add(picked_url)
                        urls.append(picked_url)
    urls.sort(key=score_play_url, reverse=True)
    return urls

def get_config():
    try:
        resp = session.get(API_URL, params={"ids": "recommend"}, timeout=10)
        resp.raise_for_status()
        data = resp.json()
        tabs = []
        for item in data.get("class", []):
            type_name = item.get("type_name", "")
            if "精" in type_name:
                continue
            tabs.append({
                "name": type_name,
                "id": str(item.get("type_id", ""))
            })
        if tabs:
            return tabs
    except Exception:
        pass
    return [
        {"name": "电影", "id": "1"},
        {"name": "电视剧", "id": "2"},
        {"name": "动漫", "id": "3"}
    ]

def get_videos(tid=None, page=1, keyword=""):
    params = {"ac": "videolist", "pg": page}
    if keyword:
        params["wd"] = keyword
    elif tid:
        params["t"] = tid
    else:
        return []
    try:
        resp = session.get(API_URL, params=params, timeout=10)
        resp.raise_for_status()
        data = resp.json()
    except Exception as e:
        print(f"请求失败: {e}")
        return []
    videos = []
    for item in data.get("list", []):
        raw_play = item.get("vod_play_url", "") or ""
        play_urls = extract_play_urls(raw_play)
        pic = item.get("vod_pic", "") or ""
        if "?" in pic:
            pic = pic.split("?", 1)[0]
        videos.append({
            "title": item.get("vod_name", "无标题"),
            "img": normalize_url(pic),
            "url": play_urls[0] if play_urls else "",
            "play_urls": play_urls,
            "duration": item.get("vod_duration", "") or "",
            "raw_url": raw_play
        })
    return videos

def clear_screen():
    os.system('cls' if os.name == 'nt' else 'clear')

def print_header(title):
    print("=" * 40)
    print(f"{title:^40}")
    print("=" * 40)

def print_tabs(tabs):
    print("分类列表：")
    for i, tab in enumerate(tabs):
        print(f"  {i+1}. {tab['name']}")
    print("  0. 搜索")
    print("  q. 退出")

def print_videos(videos, page):
    if not videos:
        print("暂无数据。")
        return
    print(f"\n第 {page} 页，共 {len(videos)} 条")
    print("-" * 40)
    for idx, v in enumerate(videos, 1):
        duration = f"[{v['duration']}]" if v['duration'] else ""
        print(f"{idx:2}. {v['title']} {duration}")
    print("-" * 40)
    print("操作：输入序号播放，n下一页，p上一页，s搜索，b返回主菜单，q退出")

def print_video_link(video):
    urls = video.get("play_urls", [])
    if not urls:
        print("没有解析到播放地址。")
        if video.get("raw_url"):
            print(f"原始数据: {video['raw_url'][:200]}")
        return
    if len(urls) == 1:
        print(f"播放链接: {urls[0]}")
    else:
        print("检测到多个播放地址：")
        for i, u in enumerate(urls, 1):
            print(f"  {i}. {u}")
        choice = input("请选择序号 (默认1): ").strip()
        try:
            idx = int(choice) - 1 if choice else 0
            print(f"播放链接: {urls[idx]}")
        except:
            print(f"播放链接: {urls[0]}")

def search_videos():
    keyword = input("请输入搜索关键词: ").strip()
    if not keyword:
        return
    page = 1
    while True:
        videos = get_videos(keyword=keyword, page=page)
        if not videos and page == 1:
            print("未找到相关视频。")
            break
        clear_screen()
        print_header(f"搜索: {keyword}")
        print_videos(videos, page)
        action = input("\n请输入操作: ").strip().lower()
        if action == 'n':
            page += 1
        elif action == 'p' and page > 1:
            page -= 1
        elif action == 'b':
            break
        elif action == 'q':
            sys.exit(0)
        elif action.isdigit():
            idx = int(action) - 1
            if 0 <= idx < len(videos):
                print_video_link(videos[idx])
                input("\n按回车继续...")
            else:
                print("序号无效")
        else:
            break

def browse_category(tab_id, tab_name):
    page = 1
    while True:
        videos = get_videos(tid=tab_id, page=page)
        if not videos and page == 1:
            print("该分类暂无视频。")
            break
        clear_screen()
        print_header(f"{tab_name} - 第{page}页")
        print_videos(videos, page)
        action = input("\n请输入操作: ").strip().lower()
        if action == 'n':
            page += 1
        elif action == 'p' and page > 1:
            page -= 1
        elif action == 's':
            search_videos()
            break
        elif action == 'b':
            break
        elif action == 'q':
            sys.exit(0)
        elif action.isdigit():
            idx = int(action) - 1
            if 0 <= idx < len(videos):
                print_video_link(videos[idx])
                input("\n按回车继续...")
            else:
                print("序号无效")
        else:
            print("无效输入")

def main():
    clear_screen()
    print_header("影视播放命令行版")
    tabs = get_config()
    if not tabs:
        print("无法获取分类，请检查网络。")
        return
    while True:
        clear_screen()
        print_header("主菜单")
        print_tabs(tabs)
        choice = input("\n请选择: ").strip().lower()
        if choice == 'q':
            print("再见！")
            break
        elif choice == '0':
            search_videos()
        elif choice.isdigit():
            idx = int(choice) - 1
            if 0 <= idx < len(tabs):
                browse_category(tabs[idx]['id'], tabs[idx]['name'])
            else:
                print("无效选项")
        else:
            print("无效输入")

# --- py578 适配：命令行脚本补 Spider 包装（映射 get_config/get_videos 的 MacCMS 接口） ---
try:
    from base.spider import Spider as _BaseSpider
except Exception:
    class _BaseSpider(object):
        pass


class Spider(_BaseSpider):
    def getName(self):
        return "影视"

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

    def _fetch(self, params):
        try:
            resp = session.get(API_URL, params=params, timeout=15)
            resp.raise_for_status()
            return resp.json()
        except Exception:
            return {}

    def _to_vod(self, item):
        pic = item.get("vod_pic", "") or ""
        if "?" in pic:
            pic = pic.split("?", 1)[0]
        return {
            "vod_id": str(item.get("vod_id", "")),
            "vod_name": item.get("vod_name", "无标题"),
            "vod_pic": normalize_url(pic),
            "vod_remarks": item.get("vod_remarks", "") or "",
        }

    def homeContent(self, filter=False):
        tabs = get_config()
        classes = [{"type_name": t["name"], "type_id": t["id"]} for t in tabs]
        lst = []
        if classes:
            lst = self.categoryContent(classes[0]["type_id"], "1", False, {}).get("list", [])
        return {"class": classes, "list": lst}

    def homeVideoContent(self):
        return {"list": self.homeContent(False).get("list", [])}

    def categoryContent(self, tid, pg=1, filter=False, extend=None):
        data = self._fetch({"ac": "videolist", "t": tid, "pg": pg})
        lst = [self._to_vod(it) for it in data.get("list", []) if isinstance(it, dict)]
        return {"list": lst, "page": int(pg), "pagecount": int(data.get("pagecount", 1) or 1),
                "limit": len(lst), "total": int(data.get("total", len(lst)) or len(lst))}

    def detailContent(self, ids):
        vod_id = str(ids[0]) if ids else ""
        data = self._fetch({"ac": "detail", "ids": vod_id})
        items = data.get("list", []) if isinstance(data, dict) else []
        if not items:
            data = self._fetch({"ac": "videolist", "ids": vod_id})
            items = data.get("list", []) if isinstance(data, dict) else []
        out = []
        for item in items:
            if not isinstance(item, dict):
                continue
            vod = self._to_vod(item)
            play_from = item.get("vod_play_from", "") or "影视"
            play_url = item.get("vod_play_url", "") or ""
            if not play_url:
                urls = extract_play_urls(item.get("vod_play_url", "") or "")
                play_url = "#".join("第%d集$%s" % (i + 1, u) for i, u in enumerate(urls))
            vod.update({
                "vod_year": item.get("vod_year", "") or "",
                "vod_area": item.get("vod_area", "") or "",
                "vod_actor": item.get("vod_actor", "") or "",
                "vod_director": item.get("vod_director", "") or "",
                "vod_content": item.get("vod_content", "") or "",
                "vod_play_from": play_from,
                "vod_play_url": play_url,
            })
            out.append(vod)
        return {"list": out}

    def searchContent(self, key, quick=False, pg=1):
        data = self._fetch({"ac": "videolist", "wd": key, "pg": pg})
        lst = [self._to_vod(it) for it in data.get("list", []) if isinstance(it, dict)]
        return {"list": lst, "page": int(pg)}

    def playerContent(self, flag, id, vipFlags=None):
        url = normalize_url(str(id or ""))
        nested = extract_nested_media_url(url)
        if nested:
            url = nested
        return {"parse": 0, "url": url, "header": {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"}}
# --- end py578 Spider wrapper ---


if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("\n已退出")
        sys.exit(0)