# -*- coding: utf-8 -*-
import http.cookiejar
import json
import re
import time
import urllib.error
import urllib.request

SITE = "https://m.234iptv.com"
SITES = [SITE, "https://www.234iptv.com", "https://234iptv.com"]
UA = ("Mozilla/5.0 (Linux; Android 11; Pixel 5) AppleWebKit/537.36 "
      "(KHTML, like Gecko) Chrome/120.0 Mobile Safari/537.36")
CLASSES = [("tv", "綜合"), ("ty", "體育"), ("ys", "央視"), ("ws", "衛視"), ("gt", "港澳台")]
CLASS_NAME = dict(CLASSES)
_KEYSTR = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
_TERM = re.compile(r'"([^"]*)"(\.split\(""\)\.reverse\(\)\.join\(""\)?)?')


class Spider:
    def __init__(self):
        self._opener = None
        self._last = 0.0

    def _opener_get(self):
        if self._opener is not None:
            return self._opener
        jar = http.cookiejar.CookieJar()
        try:
            ctx = ssl.create_default_context()
            ctx.set_alpn_protocols(["http/1.1"])
            op = urllib.request.build_opener(
                urllib.request.HTTPSHandler(context=ctx),
                urllib.request.HTTPCookieProcessor(jar))
        except Exception:
            try:
                op = urllib.request.build_opener(
                    urllib.request.HTTPCookieProcessor(jar))
            except Exception:
                op = urllib.request.build_opener()
        op.addheaders = [("User-Agent", UA), ("Referer", SITE + "/")]
        self._opener = op
        return op

    # ---------- 通用请求（纯标准库） ----------
    def _get(self, url, timeout=6):
        # 按 SITES 顺序换入口。超时 / 连接失败直接换下一个站，不在同一个站上死等
        # （否则壳的首页加载会等几十秒然后空白）；只有 429/5xx 才等 2 秒重试一次。
        for base in SITES:
            u = url if base == SITE else url.replace(SITE, base, 1)
            html, retry = self._fetch(u, timeout)
            if html:
                return html
            if retry:
                time.sleep(2)
                html, _ = self._fetch(u, timeout)
                if html:
                    return html
        return ""

    def _fetch(self, url, timeout=6):
        # 返回 (html, 是否值得重试)。超时 / 连接失败不重试（换站更快）。
        now = time.time()
        dt = now - self._last
        if dt < 0.5:
            time.sleep(0.5 - dt)
        self._last = time.time()
        try:
            req = urllib.request.Request(url)
            with self._opener_get().open(req, timeout=timeout) as r:
                if r.status != 200:
                    return "", False
                return r.read().decode("utf-8", "replace"), False
        except urllib.error.HTTPError as e:
            if e.code in (429, 500, 502, 503):
                return "", True
            return "", False
        except (urllib.error.URLError, TimeoutError, OSError, ValueError):
            return "", False

    # ---------- 混淆解码 ----------
    @staticmethod
    def _smwms(data):
        """按页面里的 base64 解码函数原样实现（处理非法字符与补位的方式与之一致）。"""
        if isinstance(data, str):
            data = data.encode("latin-1")
        out = bytearray()
        n = len(data)
        i = 0
        while True:
            h = []
            for _ in range(4):
                if i < n:
                    h.append(_KEYSTR.find(chr(data[i])))
                else:
                    h.append(-1)
                i += 1
            h1, h2, h3, h4 = h
            bits = (h1 << 18) | (h2 << 12) | (h3 << 6) | h4
            a1 = (bits >> 16) & 0xFF
            a2 = (bits >> 8) & 0xFF
            a3 = bits & 0xFF
            if h3 == 64:
                out.append(a1)
            elif h4 == 64:
                out.append(a1)
                out.append(a2)
            else:
                out.append(a1)
                out.append(a2)
                out.append(a3)
            if i >= n:
                break
        return bytes(out)

    @staticmethod
    def _eval_expr(expr):
        """求值 "abc"+"def".split("").reverse().join("") 这类拼接表达式。"""
        out = []
        for m in _TERM.finditer(expr):
            lit = m.group(1)
            out.append(lit[::-1] if ".reverse()" in m.group(0) else lit)
        return "".join(out)

    def _parse_keys(self, html):
        """从播放页内联脚本现取 key/token/占位 token/xor 后缀（每次加载都会换）。"""
        pairs = [(m.group(1), m.end())
                 for m in re.finditer(r'var \w+ = ""; var \w+ =([^;]+);', html)]
        if len(pairs) < 2:
            return None
        key = self._eval_expr(pairs[0][0])
        token = self._eval_expr(pairs[1][0])
        m = re.search(r'"([0-9a-f]{32})"', html[pairs[1][1]:pairs[1][1] + 500])
        ph = m.group(1) if m else ""
        m2 = re.search(r'key\s*=\s*key\s*\+\s*"([^"]+)"', html)
        suffix = m2.group(1) if m2 else ""
        if not key or not token or not ph or not suffix:
            return None
        return key, token, ph, suffix

    def _decode_line(self, value, key, token, ph, suffix):
        try:
            raw = self._smwms(value[::-1].encode("latin-1"))
            k2 = (key + suffix).encode()
            code = bytes(b ^ k2[i % len(k2)] for i, b in enumerate(raw))
            out = self._smwms(code).decode("utf-8", "replace")
            out = out.replace("token=" + ph, "token=" + token)
            out = out.replace(key, "")
            return out
        except Exception:
            return ""

    # ---------- 页面解析 ----------
    @staticmethod
    def _parse_channels(html):
        out = []
        seen = set()
        for m in re.finditer(
                r'<a href="\?act=play&tid=(\w+)&id=(\d+)"[^>]*>([^<]+)</a>', html):
            tid, cid, name = m.group(1), m.group(2), m.group(3).strip()
            if (tid, cid) in seen or not name:
                continue
            seen.add((tid, cid))
            out.append((tid, cid, name))
        return out

    @staticmethod
    def _parse_lines(html):
        return re.findall(r'<option value="([^"]+)">([^<]+)</option>', html)

    # 站内没有台标，用站方 favicon 作频道图（非空的真实图片地址）。
    PIC = "https://d.2026016.xyz/images/favicon.ico"

    @staticmethod
    def _vod(tid, cid, name):
        return {
            "vod_id": "%s_%s" % (tid, cid),
            "vod_name": name,
            "vod_pic": Spider.PIC,
            "vod_remarks": "直播",
            "vod_content": "",
        }

    @staticmethod
    def _split_id(vid):
        # 新格式 tv_24 / tv_24_0；兼容旧格式 tv|24 / tv|24|0。
        sep = "_" if "_" in vid else "|"
        return vid.split(sep)

    # ---------- CatVod 协议 ----------
    def _home_items(self):
        html = self._get(SITE + "/")
        return [self._vod(t, c, n) for t, c, n in self._parse_channels(html)]

    def homeContent(self, *args, **kwargs):
        return {
            "class": [{"type_id": t, "type_name": n} for t, n in CLASSES],
            "filters": {t: [] for t, _ in CLASSES},
            "list": self._home_items(),
        }

    def homeVideoContent(self, *args, **kwargs):
        # 个别壳（OK影视）的首页推荐只调这个接口，没有它首页就是空白。
        return {"list": self._home_items()}

    def categoryContent(self, *args, **kwargs):
        tid = args[0] if len(args) > 0 else kwargs.get("tid", "tv")
        pg = args[1] if len(args) > 1 else kwargs.get("pg", 1)
        pg = max(1, int(pg or 1))
        html = self._get("%s/?tid=%s" % (SITE, tid))
        items = [self._vod(t, c, n) for t, c, n in self._parse_channels(html)]
        return {
            "page": pg,
            "pagecount": 1,
            "limit": max(1, len(items)),
            "total": len(items),
            "list": items,
        }

    def detailContent(self, *args, **kwargs):
        ids = args[0] if len(args) > 0 else kwargs.get("ids", [])
        if isinstance(ids, str):
            ids = [ids]
        vid = (ids or [""])[0]
        parts = self._split_id(vid)
        if len(parts) >= 2:
            tid, cid = parts[0], parts[1]
        else:
            tid, cid = "tv", vid
        html = self._get("%s/?act=play&tid=%s&id=%s" % (SITE, tid, cid))
        name = ""
        m = re.search(r"<title>([^-<]+)", html)
        if m:
            name = m.group(1).strip()
        if not name:
            name = vid
        lines = self._parse_lines(html)
        if not lines:
            lines = [("線路1", "")]
        vod = {
            "vod_id": vid,
            "vod_name": name,
            "vod_pic": "",
            "type_name": CLASS_NAME.get(tid, ""),
            "vod_year": "",
            "vod_area": "",
            "vod_remarks": "直播",
            "vod_content": "",
            "vod_play_from": "$$$".join(n for _, n in lines),
            "vod_play_url": "$$$".join(
                "直播$%s_%s_%d" % (tid, cid, i) for i in range(len(lines))),
        }
        return {"list": [vod]}

    def searchContent(self, *args, **kwargs):
        key = args[0] if len(args) > 0 else kwargs.get("key", "")
        pg = args[2] if len(args) > 2 else kwargs.get("pg", 1)
        pg = max(1, int(pg or 1))
        key = (key or "").strip().lower()
        items = []
        seen = set()
        for tid, _ in CLASSES:
            html = self._get("%s/?tid=%s" % (SITE, tid))
            for t2, cid, name in self._parse_channels(html):
                if cid in seen:
                    continue
                if key and key not in name.lower():
                    continue
                seen.add(cid)
                items.append(self._vod(t2, cid, name))
        return {
            "page": pg,
            "pagecount": 1,
            "limit": 100,
            "total": len(items),
            "list": items,
        }

    def _resolve_stream(self, raw):
        """跟随 302 拿到真实流地址；优先 m3u8，失败回落 flv。"""
        cands = []
        if "type=.flv" in raw:
            cands.append(raw.replace("type=.flv", "type=.m3u8"))
        cands.append(raw)
        for cand in cands:
            try:
                req = urllib.request.Request(cand)
                r = self._opener_get().open(req, timeout=8)
                try:
                    final = r.geturl()
                    ok = r.status == 200
                finally:
                    r.close()
                if ok and (".m3u8" in final or ".flv" in final or final != cand):
                    return final
            except Exception:
                continue
        return raw

    def playerContent(self, *args, **kwargs):
        flag = args[0] if len(args) > 0 else kwargs.get("flag", "")
        id = args[1] if len(args) > 1 else kwargs.get("id", "")
        parts = self._split_id(id or "")
        if len(parts) < 3:
            return {"parse": 0, "playUrl": "", "url": "",
                    "header": {"User-Agent": UA}}
        tid, cid = parts[0], parts[1]
        try:
            line = int(parts[2])
        except ValueError:
            line = 0
        html = self._get("%s/?act=play&tid=%s&id=%s" % (SITE, tid, cid))
        lines = self._parse_lines(html)
        keys = self._parse_keys(html)
        url = ""
        if lines and keys and 0 <= line < len(lines):
            raw = self._decode_line(lines[line][0], *keys)
            if raw.startswith("http"):
                url = self._resolve_stream(raw)
        return {"parse": 0, "playUrl": "", "url": url,
                "header": {"User-Agent": UA, "Referer": SITE + "/"}}

    # ---------- 各壳兼容 ----------
    def getName(self, *args, **kwargs):
        return "234直播"

    def init(self, *args, **kwargs):
        return {}

    def getDependence(self, *args, **kwargs):
        return ""

    def isVideoFormat(self, *args, **kwargs):
        url = args[0] if len(args) > 0 else kwargs.get("url", "")
        url = (url or "").lower()
        return any(x in url for x in (".m3u8", ".flv", ".mp4", "type=.m3u8", "type=.flv"))

    def manualVideoCheck(self, *args, **kwargs):
        return False

    def localProxy(self, *args, **kwargs):
        return self.proxy(*args, **kwargs)

    def proxy(self, *args, **kwargs):
        params = args[0] if len(args) > 0 else kwargs.get("params", {})
        if isinstance(params, str):
            try:
                params = json.loads(params)
            except Exception:
                params = {}
        url = (params or {}).get("url", "")
        if not url:
            return [404, "text/plain", b""]
        try:
            req = urllib.request.Request(url)
            with self._opener_get().open(req, timeout=15) as r:
                # 只读前 1MB：播放列表很小；直播流是无限的，不能一直读下去。
                return [r.status,
                        r.headers.get("Content-Type", "application/octet-stream"),
                        r.read(1024 * 1024)]
        except urllib.error.HTTPError as e:
            try:
                return [e.code,
                        e.headers.get("Content-Type", "text/plain"),
                        e.read()]
            except Exception:
                return [e.code, "text/plain", b""]
        except Exception:
            return [500, "text/plain", b""]

    def destroy(self, *args, **kwargs):
        try:
            if self._opener is not None:
                self._opener.close()
        except Exception:
            pass
