# -*- coding: utf-8 -*-
"""
AI深夜短剧 TVBox/影视仓 爬虫（修复版）
站点: https://licefor.aisydj.cc

修复要点（均已通过实测该站点验证）：
1. 播放解析：原版未带 X-Requested-With 头，/huangguo.php?ac=play 必定 403，
   且把返回的 /huangguo.php?ac=media&t=... 又套进已废弃的 /hgmedia.php?url=，必然播不了。
2. 备注解析：卡片角标类名是 card-eps，原正则未包含 eps，导致 vod_remarks 恒为空。
3. 搜索地址：原版 /vod/search/wd/xx/ 为 404，真实入口是 /search/-------------/?wd=xx。
4. 分页判断：原版 max(...) 恒加一页，最后一页会凭空多出一页空白。
5. 首页推荐：原版返回空列表，实际 /home/ 有 40 条数据。
6. 标题/简介未做 HTML 实体反转义，且海报相对地址未补全。
"""

import sys
import ssl
import time
import json
import re
import html as _html
import urllib.request
import urllib.parse
import urllib.error
from http.cookiejar import CookieJar

try:
    from base.spider import Spider as BaseSpider
except Exception:
    class BaseSpider(object):
        pass


SITE_NAME = "AI深夜短剧"
DEFAULT_SITE_URL = "https://licefor.aisydj.cc"

SEARCH_MIN_INTERVAL = 3.2  # 站点限制：两次搜索间隔不得小于 3 秒，否则返回“系统提示”拦截页

_ANCHOR_RE = re.compile(r"<a\b([^>]*)>(.*?)</a>", re.S | re.I)
_ATTR_RE = re.compile(r"""([\w:-]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+))""", re.S)
_TAG_RE = re.compile(r"<[^>]+>", re.S)
_WS_RE = re.compile(r"[ \t\r\n\u3000]+")
_EP_SPLIT_RE = re.compile(r"\|")
_PLAY_HREF_RE = re.compile(r"/play/[^\"'\s<>]+")


class Spider(BaseSpider):
    def __init__(self):
        self.site_url = DEFAULT_SITE_URL
        self.headers = {
            "User-Agent": (
                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
                "(KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36"
            ),
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
            "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
            "Connection": "keep-alive",
        }
        self.cookie_jar = CookieJar()
        self.opener = self._build_opener()
        self._page_cache = {}
        self._last_search_at = 0.0

    # ------------------------------------------------------------------ 基础

    def _build_opener(self):
        ctx = ssl.create_default_context()
        ctx.check_hostname = False
        ctx.verify_mode = ssl.CERT_NONE
        try:
            ctx.set_ciphers("DEFAULT@SECLEVEL=1")
        except Exception:
            pass
        handlers = [
            urllib.request.HTTPSHandler(context=ctx),
            urllib.request.HTTPCookieProcessor(self.cookie_jar),
        ]
        try:
            handlers.append(urllib.request.HTTPRedirectHandler())
        except Exception:
            pass
        return urllib.request.build_opener(*handlers)

    def _fetch(self, url, retry=2, referer=None, headers=None, timeout=15):
        """返回 {status_code, final_url, headers, html}；失败抛最后一次异常。"""
        hdrs = dict(self.headers)
        if referer:
            hdrs["Referer"] = referer
        if headers:
            hdrs.update(headers)

        last_err = None
        candidates = [url]
        # https 握手异常时退化到 http（该站点两套协议内容一致）
        if url.startswith("https://"):
            candidates.append("http://" + url[len("https://"):])

        for attempt in range(retry + 1):
            if attempt:
                time.sleep(0.4 * attempt)
            for candidate in candidates:
                try:
                    req = urllib.request.Request(candidate, headers=hdrs)
                    with self.opener.open(req, timeout=timeout) as resp:
                        raw = resp.read()
                        final_url = resp.geturl()
                        status = resp.getcode()
                        resp_headers = dict(resp.headers)
                    charset = "utf-8"
                    ctype = resp_headers.get("Content-Type", "") or ""
                    m = re.search(r"charset=([\w\-]+)", ctype, re.I)
                    if m:
                        charset = m.group(1).strip()
                    try:
                        text = raw.decode(charset, "ignore")
                    except Exception:
                        text = raw.decode("utf-8", "ignore")
                    return {
                        "status_code": status,
                        "final_url": final_url,
                        "headers": resp_headers,
                        "html": text.lstrip("\ufeff"),
                    }
                except Exception as e:
                    last_err = e
        raise last_err if last_err else RuntimeError("fetch failed: %s" % url)

    def _get(self, path, referer=None, headers=None):
        url = path if path.startswith("http") else self.site_url + path
        return self._fetch(url, referer=referer, headers=headers)

    def _abs(self, url):
        url = (url or "").strip()
        if not url:
            return ""
        if url.startswith("//"):
            return "https:" + url
        if url.startswith("http://") or url.startswith("https://"):
            return url
        if url.startswith("/"):
            return self.site_url + url
        return self.site_url + "/" + url.lstrip("./")

    def _text(self, s):
        if not s:
            return ""
        s = _TAG_RE.sub(" ", s)
        s = _html.unescape(s)
        s = s.replace("\xa0", " ")
        return _WS_RE.sub(" ", s).strip()

    def _attrs(self, s):
        out = {}
        for m in _ATTR_RE.finditer(s or ""):
            key = m.group(1).lower()
            val = m.group(2)
            if val is None:
                val = m.group(3)
            if val is None:
                val = m.group(4)
            out[key] = val or ""
        return out

    # ------------------------------------------------------------- 列表解析

    def _parse_cards(self, html):
        """从任意列表页解析卡片，按 vod_id 去重。"""
        items = []
        seen = set()
        if not html:
            return items

        for m in _ANCHOR_RE.finditer(html):
            attrs = self._attrs(m.group(1))
            href = attrs.get("href", "")
            id_m = re.search(r"/detail/(\d+)", href)
            if not id_m:
                continue
            vod_id = id_m.group(1)
            if vod_id in seen:
                continue
            inner = m.group(2)

            name = ""
            t_m = re.search(
                r'class="[^"]*(?:card-title|title|name)[^"]*"[^>]*>(.*?)</', inner, re.S | re.I
            )
            if t_m:
                name = self._text(t_m.group(1))
            if not name:
                name = self._text(attrs.get("title", ""))
            if not name:
                a_m = re.search(r"<img[^>]*\balt\s*=\s*[\"']([^\"']*)[\"']", inner, re.I)
                if a_m:
                    name = self._text(a_m.group(1))
            if not name:
                continue

            pic = ""
            p_m = re.search(
                r"<img[^>]*(?:data-src|data-original|src)\s*=\s*[\"']([^\"']+)[\"']", inner, re.I
            )
            if p_m:
                pic = self._abs(p_m.group(1))

            remark = ""
            r_m = re.search(
                r'<span[^>]*class="[^"]*(?:card-eps|eps|badge|tag|note|remarks|duration|score)[^"]*"'
                r"[^>]*>(.*?)</span>",
                inner,
                re.S | re.I,
            )
            if r_m:
                remark = self._text(r_m.group(1))

            seen.add(vod_id)
            items.append(
                {
                    "vod_id": vod_id,
                    "vod_name": name,
                    "vod_pic": pic,
                    "vod_remarks": remark or SITE_NAME,
                }
            )
        return items

    @staticmethod
    def _has_next_page(html):
        """分页器里有可点的『下一页』链接才算有下一页。"""
        if not html:
            return False
        for m in re.finditer(r"<a\b([^>]*)>(.*?)</a>", html, re.S | re.I):
            label = _TAG_RE.sub("", m.group(2))
            if ("下一页" in label or "下頁" in label) and "disabled" not in (m.group(1) or ""):
                return True
        return False

    @staticmethod
    def _max_page_in_pager(html):
        nums = [int(x) for x in re.findall(r"/page/(\d+)/", html or "")]
        return max(nums) if nums else 0

    # ------------------------------------------------------------------ 接口

    def init(self, extend=""):
        """支持在 TVBox 配置里用 {"site":"https://xxx"} 覆盖站点域名。"""
        try:
            if not extend:
                return
            if isinstance(extend, dict):
                site = extend.get("site") or extend.get("url") or ""
            else:
                text = str(extend).strip()
                site = ""
                if text.startswith("{"):
                    try:
                        site = (json.loads(text) or {}).get("site", "") or ""
                    except Exception:
                        site = ""
                elif text.startswith("http"):
                    site = text
            site = (site or "").strip().rstrip("/")
            if site.startswith("http"):
                self.site_url = site
        except Exception:
            pass

    def homeContent(self, filter):
        classes = [
            {"type_id": "AIchengrenduanju", "type_name": "AI成人短剧"},
            {"type_id": "AIchengrenmanju", "type_name": "AI成人漫剧"},
            {"type_id": "AImogai", "type_name": "AI魔改"},
            {"type_id": "AIhuanlian", "type_name": "AI换脸"},
        ]
        sort_filter = {
            "key": "by",
            "name": "排序",
            "value": [
                {"n": "最新上线", "v": "time"},
                {"n": "按热度", "v": "hits"},
                {"n": "评分最高", "v": "score"},
            ],
        }
        filters = {}
        for c in classes:
            filters[c["type_id"]] = [sort_filter]
        return {"class": classes, "filters": filters}

    def homeVideoContent(self):
        items = []
        try:
            res = self._get("/home/")
            items = self._parse_cards(res.get("html", ""))
        except Exception:
            items = []
        return {"list": items[:40]}

    def categoryContent(self, tid, pg, filter, extend):
        try:
            page = int(pg) if str(pg).strip().isdigit() else 1
        except Exception:
            page = 1

        by = ""
        if isinstance(extend, dict):
            by = str(extend.get("by") or "").strip()
        if by not in ("time", "hits", "score"):
            by = ""
        elif by == "time":
            by = ""  # time 就是默认排序

        base = "/aidj/%s/" % tid
        if by:
            path = "%sby/%s/" % (base, by)
            if page > 1:
                path = "%sby/%s/page/%d/" % (base, by, page)
        else:
            path = base if page <= 1 else "%spage/%d/" % (base, page)

        try:
            res = self._get(path)
            html = res.get("html", "")
            vod_list = self._parse_cards(html)
        except Exception:
            html = ""
            vod_list = []

        # 分页总数：只有分页器里存在可点的“下一页”才认为还有页；
        # 同时参考分页器里出现过的最大页码，避免误报。
        if vod_list and self._has_next_page(html):
            page_count = max(page + 1, self._max_page_in_pager(html))
        else:
            page_count = page

        return {
            "page": page,
            "pagecount": page_count,
            "limit": len(vod_list) or 24,
            "total": page_count * 24 if page_count > 1 else len(vod_list),
            "list": vod_list,
        }

    def detailContent(self, ids):
        vod_id = ""
        if isinstance(ids, (list, tuple)) and ids:
            vod_id = str(ids[0])
        elif ids is not None:
            vod_id = str(ids)
        vod_id = re.sub(r"\D", "", vod_id) or str(vod_id)

        vod_name = "短剧_%s" % vod_id
        vod_pic = ""
        vod_content = ""
        vod_remarks = ""
        type_name = "短剧"
        episodes = []

        try:
            res = self._get("/detail/%s/" % vod_id, referer=self.site_url + "/")
            html = res.get("html", "")

            m = re.search(r'<h1[^>]*class="[^"]*watch-title[^"]*"[^>]*>(.*?)</h1>', html, re.S | re.I)
            if not m:
                m = re.search(r"<h1[^>]*>(.*?)</h1>", html, re.S | re.I)
            if m:
                vod_name = self._text(m.group(1)) or vod_name

            m = re.search(
                r"<img[^>]*class=\"[^\"]*(?:detail-poster|poster)[^\"]*\"[^>]*\bsrc\s*=\s*[\"']([^\"']+)[\"']",
                html,
                re.S | re.I,
            )
            if not m:
                m = re.search(
                    r"<img[^>]*\bsrc\s*=\s*[\"']([^\"']+)[\"'][^>]*class=\"[^\"]*(?:detail-poster|poster)[^\"]*\"",
                    html,
                    re.S | re.I,
                )
            if not m:
                m = re.search(
                    r"<meta[^>]*(?:property|name)=\s*[\"']og:image[\"'][^>]*content=\s*[\"']([^\"']+)[\"']",
                    html,
                    re.I,
                )
            if m:
                vod_pic = self._abs(m.group(1))

            m = re.search(r'<div[^>]*class="[^"]*watch-desc[^"]*"[^>]*>(.*?)</div>', html, re.S | re.I)
            if not m:
                m = re.search(
                    r'<div[^>]*class="[^"]*(?:desc|content|intro)[^"]*"[^>]*>(.*?)</div>', html, re.S | re.I
                )
            if m:
                vod_content = self._text(m.group(1))

            meta = re.search(r'<div[^>]*class="[^"]*hero-meta[^"]*"[^>]*>(.*?)</div>', html, re.S | re.I)
            if meta:
                spans = [_TAG_RE.sub("", s) for s in re.findall(r"<span[^>]*>(.*?)</span>", meta.group(1), re.S)]
                spans = [self._text(s) for s in spans if self._text(s)]
                if spans:
                    vod_remarks = spans[0]
                for s in spans:
                    if s.endswith("短剧") or s.endswith("漫剧") or s in ("AI魔改", "AI换脸"):
                        type_name = s
                        break

            seen_eps = set()
            for m in re.finditer(r"<a\b([^>]*)>(.*?)</a>", html, re.S | re.I):
                attrs = self._attrs(m.group(1))
                href = attrs.get("href", "")
                if not _PLAY_HREF_RE.search(href):
                    continue
                href = _PLAY_HREF_RE.search(href).group(0)
                if href in seen_eps:
                    continue
                ep_name = self._text(m.group(2)) or ("第%d集" % (len(episodes) + 1))
                seen_eps.add(href)
                episodes.append("%s$%s" % (ep_name, href))
        except Exception:
            pass

        if not episodes:
            episodes = ["正片$/play/%s-1-1/" % vod_id]

        if not vod_content:
            vod_content = "AI 精品短剧，畅享高清视界。"

        return {
            "list": [
                {
                    "vod_id": vod_id,
                    "vod_name": vod_name,
                    "vod_pic": vod_pic,
                    "type_name": type_name,
                    "vod_remarks": vod_remarks or SITE_NAME,
                    "vod_year": "",
                    "vod_area": "",
                    "vod_actor": SITE_NAME,
                    "vod_director": SITE_NAME,
                    "vod_content": vod_content,
                    "vod_play_from": SITE_NAME,
                    "vod_play_url": "#".join(episodes),
                }
            ]
        }

    # ------------------------------------------------------------- 播放解析

    def _extract_player_data(self, html):
        if not html:
            return {}
        m = re.search(r"player_data\s*=\s*", html)
        if not m:
            return {}
        start = html.find("{", m.end())
        if start < 0:
            return {}
        depth = 0
        in_str = False
        esc = False
        limit = min(len(html), start + 20000)
        for i in range(start, limit):
            ch = html[i]
            if in_str:
                if esc:
                    esc = False
                elif ch == "\\":
                    esc = True
                elif ch == '"':
                    in_str = False
            else:
                if ch == '"':
                    in_str = True
                elif ch == "{":
                    depth += 1
                elif ch == "}":
                    depth -= 1
                    if depth == 0:
                        raw = html[start : i + 1]
                        try:
                            data = json.loads(raw)
                            return data if isinstance(data, dict) else {}
                        except Exception:
                            return {}
        return {}

    @staticmethod
    def _decode_player_url(value, encrypt):
        value = value or ""
        if str(encrypt) == "1":
            try:
                value = urllib.parse.unquote(value)
            except Exception:
                pass
        elif str(encrypt) == "2":
            try:
                import base64

                value = base64.b64decode(value + "=" * (-len(value) % 4)).decode("utf-8", "ignore")
                value = urllib.parse.unquote(value)
            except Exception:
                pass
        return value

    def _resolve_play_url(self, play_page_url):
        """播放页 -> 可直连的 m3u8 地址。"""
        res = self._get(play_page_url, referer=self.site_url + "/")
        html = res.get("html", "")

        data = self._extract_player_data(html)
        raw = self._decode_player_url(data.get("url", ""), data.get("encrypt", 0)).strip()

        # 情况一：url 已是直链
        if raw.startswith("http") and re.search(r"\.(?:m3u8|mp4|flv)(?:\?|$)", raw, re.I):
            return raw

        # 情况二：url 形如 "15579|1"，需要走站点播放接口
        if raw:
            parts = _EP_SPLIT_RE.split(raw, 1)
            src_id = parts[0].strip()
            ep = parts[1].strip() if len(parts) > 1 else "1"
            if src_id.isdigit() and ep.isdigit():
                api_url = "%s/huangguo.php?ac=play&id=%s&ep=%s&_=%d" % (
                    self.site_url,
                    urllib.parse.quote(src_id),
                    urllib.parse.quote(ep),
                    int(time.time() * 1000),
                )
                api_res = self._fetch(
                    api_url,
                    retry=1,
                    referer=play_page_url,
                    headers={
                        "Accept": "application/json, text/javascript, */*; q=0.01",
                        "X-Requested-With": "XMLHttpRequest",
                    },
                )
                api_text = (api_res.get("html") or "").strip()
                try:
                    api_data = json.loads(api_text)
                except Exception:
                    api_data = {}
                target = (api_data or {}).get("url") or ""
                if target:
                    return self._abs(target)

        # 情况三：页面里直接写死了流地址
        m = re.search(r"[\"'](https?://[^\"']+?\.(?:m3u8|mp4)[^\"']*)[\"']", html, re.I)
        if m:
            return m.group(1)
        return ""

    def playerContent(self, flag, id, vipFlags):
        play_id = str(id or "").strip()
        if play_id.startswith("http"):
            play_page_url = play_id
        elif play_id.startswith("/"):
            play_page_url = self.site_url + play_id
        else:
            play_page_url = "%s/play/%s/" % (self.site_url, play_id)

        header = {
            "User-Agent": self.headers["User-Agent"],
            "Referer": self.site_url + "/",
        }

        try:
            url = self._resolve_play_url(play_page_url)
        except Exception:
            url = ""

        if url:
            return {"parse": 0, "playUrl": "", "url": url, "header": header}

        # 兜底：把播放页交给解析/浏览器
        return {"parse": 1, "playUrl": "", "url": play_page_url, "header": header}

    # ------------------------------------------------------------- 搜索

    @staticmethod
    def _is_rate_limited_page(html):
        """站点在 3 秒内重复搜索时会返回一个 200 的『系统提示』拦截页。"""
        if not html:
            return False
        if "请不要频繁操作" in html:
            return True
        return "系统提示" in html and len(html) < 4000

    def _search_pace(self):
        gap = SEARCH_MIN_INTERVAL - (time.time() - self._last_search_at)
        if 0 < gap < SEARCH_MIN_INTERVAL:
            time.sleep(gap)
        self._last_search_at = time.time()

    def searchContent(self, key, quick, pg="1"):
        key = (key or "").strip()
        try:
            page = int(pg) if str(pg).strip().isdigit() else 1
        except Exception:
            page = 1
        if not key:
            return {"page": 1, "pagecount": 0, "limit": 0, "total": 0, "list": []}
        # 站点搜索不分页，直接返回单页结果；避免上拉加载时重复请求
        if page > 1:
            return {"page": page, "pagecount": 1, "limit": 0, "total": 0, "list": []}

        path = "/search/-------------/?" + urllib.parse.urlencode({"wd": key})

        vod_list = []
        for attempt in range(3):
            try:
                self._search_pace()
                res = self._get(path, referer=self.site_url + "/")
                html = res.get("html", "")
                if self._is_rate_limited_page(html):
                    time.sleep(SEARCH_MIN_INTERVAL)
                    continue
                vod_list = self._parse_cards(html)
                break
            except Exception:
                if attempt >= 2:
                    vod_list = []
                else:
                    time.sleep(1.0)

        return {
            "page": 1,
            "pagecount": 1,
            "limit": len(vod_list) or 24,
            "total": len(vod_list),
            "list": vod_list,
        }

    # ------------------------------------------------------------- 其它

    def action(self, action):
        return ""

    def liveContent(self):
        return ""

    def localProxy(self, params):
        return [200, "text/plain;charset=utf-8", ""]

    def manualVideoCheck(self):
        return False

    def isVideoFormat(self, url):
        return bool(re.search(r"\.(?:m3u8|mp4|flv)(?:\?|$)", url or "", re.I))

    def destroy(self):
        self._page_cache = {}
