# -*- coding: utf-8 -*-
# 奇点影视（新站 qdys3.cc Nuxt/API v2 重写，2026-12-06）
import json
import re
import urllib.parse
import urllib.request

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=""):
        self.hosts = ["https://www.qdys3.cc", "https://www.qdys2.cc", "https://www.qdys4.cc"]
        self.base = self.hosts[0]
        self.ua = "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1"
        self.classes = [
            {"type_id": "1", "type_name": "电影"},
            {"type_id": "2", "type_name": "电视剧"},
            {"type_id": "3", "type_name": "综艺"},
            {"type_id": "4", "type_name": "动漫"},
            {"type_id": "20", "type_name": "纪录片"},
            {"type_id": "36", "type_name": "短剧"},
            {"type_id": "38", "type_name": "体育"},
        ]

    def _headers(self, referer=None):
        return {"User-Agent": self.ua, "Referer": referer or (self.base + "/"),
                "Origin": self.base,
                "Accept": "text/html,application/xhtml+xml,application/json,*/*;q=0.8"}

    def _get(self, url, referer=None):
        try:
            r = BaseSpider.fetch(self, url, headers=self._headers(referer), timeout=15)
            txt = getattr(r, "text", "") or ""
            if txt:
                return txt
        except Exception:
            pass
        try:
            req = urllib.request.Request(url, headers=self._headers(referer))
            return urllib.request.urlopen(req, timeout=15).read().decode("utf-8", "ignore")
        except Exception:
            return ""

    def _post_json(self, url, obj, referer=None):
        data = json.dumps(obj).encode("utf-8")
        try:
            r = BaseSpider.post(self, url, data=data, headers=dict(self._headers(referer), **{"Content-Type": "application/json"}), timeout=15)
            txt = getattr(r, "text", "") or ""
            if txt:
                return json.loads(txt)
        except Exception:
            pass
        try:
            req = urllib.request.Request(url, data=data, headers=dict(self._headers(referer), **{"Content-Type": "application/json"}), method="POST")
            return json.loads(urllib.request.urlopen(req, timeout=15).read().decode("utf-8", "ignore"))
        except Exception:
            return {}

    def _cards(self, html):
        out, seen = [], set()
        for m in re.finditer(r'<a href="/v/(\d+)-[^"]*\.html" title="([^"]+)"><div class="ewave-img-wrapper"><img src="([^"]+)"', html or ""):
            vid, title, pic = m.group(1), m.group(2), m.group(3).replace("&amp;", "&")
            if vid in seen:
                continue
            seen.add(vid)
            out.append({"vod_id": vid, "vod_name": title.strip(), "vod_pic": pic, "vod_remarks": ""})
        if not out:
            for m in re.finditer(r'href="/v/(\d+)-[^"]*\.html" title="([^"]+)"', html or ""):
                vid, title = m.group(1), m.group(2)
                if vid in seen:
                    continue
                seen.add(vid)
                out.append({"vod_id": vid, "vod_name": title.strip(), "vod_pic": "", "vod_remarks": ""})
        return out

    def homeContent(self, filter):
        return {"class": self.classes, "list": self._cards(self._get(self.base + "/?_rt=1"))}

    def homeVideoContent(self):
        return {"list": self._cards(self._get(self.base + "/?_rt=1"))}

    def categoryContent(self, tid, pg, filter, extend):
        pg = int(pg or 1)
        url = "%s/t/%s/?_rt=1" % (self.base, tid) if pg <= 1 else "%s/t/%s/?page=%d&_rt=1" % (self.base, tid, pg)
        cards = self._cards(self._get(url))
        return {"list": cards, "page": pg, "pagecount": pg + 1 if cards else pg,
                "limit": len(cards), "total": 999999}

    def _catalog(self, vid):
        try:
            d = json.loads(self._get("%s/api/v2/vods/%s/play" % (self.base, vid),
                                     referer="%s/v/%s-v.html" % (self.base, vid)))
            return (d.get("data") or {}).get("lines") or []
        except Exception:
            return []

    def detailContent(self, ids):
        vid = str(ids[0] if isinstance(ids, list) else ids).split("$")[0]
        vid = re.sub(r"\D", "", vid)
        h = self._get("%s/v/%s-v.html?_rt=1" % (self.base, vid))
        title, pic, content = vid, "", ""
        m = re.search(r'property="og:title" content="([^"]+)"', h)
        if m:
            title = re.sub(r"（.*?）\s*-\s*奇点影视.*$", "", m.group(1)).strip() or m.group(1)
        m = re.search(r'property="og:image" content="([^"]+)"', h)
        if m:
            pic = m.group(1).replace("&amp;", "&")
        m = re.search(r'property="og:description" content="([^"]+)"', h)
        if m:
            content = m.group(1)[:500]
        lines = self._catalog(vid)
        lines = sorted(lines, key=lambda ln: (0 if (ln.get("line_id") or 0) >= 900000000 else 1, -(ln.get("health_score") or 0), -(ln.get("episode_count") or 0)))
        froms, urls = [], []
        for ln in lines[:6]:
            eps = ln.get("episodes") or []
            if not eps:
                continue
            froms.append(ln.get("line_name") or ln.get("play_from") or "线路")
            urls.append("#".join("%s$%s@@%s@@%s@@%s" % (
                e.get("episode_name") or ("第%s集" % e.get("episode_no", 1)), vid,
                ln.get("line_id"), e.get("url_id"), ln.get("source_vod_id") or vid) for e in eps))
        vod = {"vod_id": vid, "vod_name": title, "vod_pic": pic, "vod_content": content,
               "vod_play_from": "$$$".join(froms) or "在线播放",
               "vod_play_url": "$$$".join(urls) or ("播放$%s@@0@@0@@%s" % (vid, vid))}
        return {"list": [vod]}

    def searchContent(self, key, quick=False, pg="1"):
        pg = int(pg or 1)
        url = "%s/search?wd=%s&_rt=1" % (self.base, urllib.parse.quote(str(key)))
        if pg > 1:
            url += "&page=%d" % pg
        return {"list": self._cards(self._get(url)), "page": pg}

    def playerContent(self, flag, id, vipFlags):
        raw = str(id).rsplit("$", 1)[-1]
        parts = raw.split("@@")
        vid = parts[0]
        line_id = int(parts[1]) if len(parts) > 1 and str(parts[1]).isdigit() else 0
        url_id = int(parts[2]) if len(parts) > 2 and str(parts[2]).isdigit() else 0
        src_vid = int(parts[3]) if len(parts) > 3 and str(parts[3]).isdigit() else int(vid or 0)
        ref = "%s/v/%s-v.html" % (self.base, vid)
        if not line_id or not url_id:
            lines = self._catalog(vid)
            for ln in lines:
                eps = ln.get("episodes") or []
                if eps:
                    line_id = int(ln.get("line_id") or 0)
                    url_id = int(eps[0].get("url_id") or 0)
                    src_vid = int(ln.get("source_vod_id") or vid)
                    break
        tk = self._post_json("%s/api/v2/vods/%s/play/ticket" % (self.base, vid),
                             {"vod_id": int(vid), "line_id": line_id, "url_id": url_id, "source_vod_id": src_vid},
                             referer=ref)
        token = ((tk.get("data") or {}).get("token") or "")
        if token:
            rs = self._post_json("%s/api/v2/play/resolve" % self.base, {"token": token}, referer=ref)
            play_url = ((rs.get("data") or {}).get("play_url") or "")
            if play_url:
                return {"parse": 0, "url": play_url,
                        "header": {"User-Agent": self.ua}}
        return {"parse": 1, "url": ref, "header": {"User-Agent": self.ua, "Referer": self.base + "/"}}

    def isVideoFormat(self, url):
        u = str(url or "").lower()
        return any(k in u for k in (".m3u8", ".mp4", "mpegurl"))

    def destroy(self):
        pass
