# coding=utf-8
# 站點：ipornbase.com（AV空投軍團）
# 結構：Drupal + hls.js，非蘋果CMS，只能走 py 源
import sys, json, base64, re, requests
sys.path.append('..')
from base.spider import Spider

class Spider(Spider):
    # ---- 可調參數 ----
    HOST           = "https://ipornbase.com"
    SEARCH_PAGES   = 30
    SEARCH_WORKERS = 8
    MAX_RESULTS    = 360
    FORCE_HIGHEST  = True   # True=鎖最高檔；False=保留全部但按高到低排
    TIMEOUT        = 15

    def getName(self):
        return "AV空投軍團"

    def init(self, extend=""):
        try:
            cfg = json.loads(base64.b64decode(extend).decode()) if extend else {}
        except Exception:
            cfg = {}
        self.host = (cfg.get("host") or self.HOST).rstrip("/")
        self.ua = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
                   "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0 Safari/537.36")
        self.s = requests.Session()
        self.s.headers.update({"User-Agent": self.ua, "Referer": self.host + "/"})

    def isVideoFormat(self, url):
        return ".m3u8" in url or ".mp4" in url

    def manualVideoCheck(self):
        return True

    # ---------- 基礎 ----------
    def _get(self, path):
        r = self.s.get(self.host + path, timeout=self.TIMEOUT, verify=False)
        r.encoding = "utf-8"
        return r.text

    def _pic(self, u):
        if not u:
            return ""
        u = re.sub(r'/sites/default/files/styles/[^/]+/public/', '/sites/default/files/', u)
        u = re.sub(r'\.webp(\?|$)', r'\1', u)
        u = re.sub(r'\?itok=[^&]*', '', u)
        if u.startswith("/"):
            u = self.host + u
        return u

    def _cards(self, html):
        pics = {}
        for m in re.finditer(
                r'href="([^"]*/video/[^"]+)"[^>]*>\s*(?:<picture>.*?)?<img[^>]+src="([^"]+)"',
                html, re.S):
            pics[m.group(1).rsplit("/", 1)[-1]] = self._pic(m.group(2))

        out, seen = [], set()
        for m in re.finditer(
                r'<div class="videotitle[^"]*"><a href="([^"]*/video/[^"]+)"[^>]*>([^<]+)</a>',
                html):
            vid = m.group(1).rsplit("/", 1)[-1]
            name = m.group(2).strip()
            if not name or vid in seen:
                continue
            seen.add(vid)
            out.append({"vod_id": vid, "vod_name": name,
                        "vod_pic": pics.get(vid, ""), "vod_remarks": ""})
        return out

    # ---------- 分類 ----------
    def homeContent(self, filter):
        cats = [
            {"type_id": "asian/new",           "type_name": "亞洲國產·最近更新"},
            {"type_id": "asian/release",       "type_name": "亞洲國產·最新發行"},
            {"type_id": "asian/today-hot",     "type_name": "亞洲國產·今日熱門"},
            {"type_id": "asian/hot",           "type_name": "亞洲國產·總觀看"},
            {"type_id": "japanese/new",        "type_name": "日本AV·最近更新"},
            {"type_id": "japanese/release",    "type_name": "日本AV·最新發行"},
            {"type_id": "uncensored-leak/new", "type_name": "JAV無碼·最近更新"},
            {"type_id": "fc2/new",             "type_name": "FC2素人"},
            {"type_id": "hentai/new",          "type_name": "裏番"},
            {"type_id": "western/new",         "type_name": "歐美"},
            {"type_id": "korean/new",          "type_name": "韓國直播"},
            {"type_id": "ai/new",              "type_name": "AI短劇"},
            {"type_id": "chinese-subtitles",   "type_name": "中文字幕"},
        ]
        return {"class": cats, "list": self._cards(self._get("/asian/new"))}

    def categoryContent(self, tid, pg, filter, extend):
        html = self._get(f"/{tid}?page={max(int(pg) - 1, 0)}")
        return {"list": self._cards(html), "page": int(pg),
                "pagecount": 9999, "limit": 12, "total": 999999}

    # ---------- 搜索：多級回退 ----------
    @staticmethod
    def _page_url(base, idx):
        if idx <= 0:
            return base
        return base + ("&" if "?" in base else "?") + f"page={idx}"

    def _try(self, base, idx):
        try:
            return self._cards(self._get(self._page_url(base, idx)))
        except Exception:
            return []

    def _crawl(self, base, start):
        out, seen = [], set()

        def take(cards):
            for c in cards:
                if c["vod_id"] not in seen and len(out) < self.MAX_RESULTS:
                    seen.add(c["vod_id"])
                    out.append(c)

        pages = list(range(start, start + self.SEARCH_PAGES))
        try:
            from concurrent.futures import ThreadPoolExecutor
            with ThreadPoolExecutor(max_workers=self.SEARCH_WORKERS) as ex:
                for cards in ex.map(lambda i: self._try(base, i), pages):
                    if len(out) >= self.MAX_RESULTS:
                        break
                    if not cards:
                        break
                    take(cards)
        except Exception:
            for i in pages:
                if len(out) >= self.MAX_RESULTS:
                    break
                cards = self._try(base, i)
                if not cards:
                    break
                take(cards)
        return out

    def _local(self, key):
        out, seen = [], set()
        for path in ("asian/new", "uncensored-leak/new", "japanese/new"):
            for i in range(2):
                try:
                    cards = self._cards(self._get(f"/{path}?page={i}"))
                except Exception:
                    cards = []
                for c in cards:
                    if key in c["vod_name"] and c["vod_id"] not in seen:
                        seen.add(c["vod_id"])
                        out.append(c)
        return out

    def searchContent(self, key, quick, pg="1"):
        key = (key or "").strip()
        block = max(int(pg) - 1, 0)
        if not key:
            return {"list": [], "page": int(pg), "pagecount": 9999}

        q = requests.utils.quote(key)
        qs = requests.utils.quote(key, safe="")
        start = block * self.SEARCH_PAGES

        for base in (f"/search?fulltext={q}",
                     f"/search?fulltext={q}*",
                     f"/tags/{qs}"):
            if not self._try(base, start):
                continue
            return {"list": self._crawl(base, start),
                    "page": int(pg), "pagecount": 9999}

        return {"list": self._local(key) if block == 0 else [],
                "page": int(pg), "pagecount": 9999}

    # ---------- 詳情 ----------
    def _srcs(self, html):
        eps = []
        m = re.search(r'window\.m3u8List\s*=\s*(\[.*?\])', html, re.S)
        if m:
            try:
                eps = [x for x in json.loads(m.group(1)) if x]
            except Exception:
                eps = re.findall(r'"(https?://[^"]+)"', m.group(1))
        if not eps:
            eps = re.findall(r'"contentUrl"\s*:\s*"(https?://[^"]+)"', html)
        return list(dict.fromkeys(eps))

    def detailContent(self, ids):
        vid = ids[0]
        html = self._get(f"/video/{vid}")
        title = (re.search(r'<h1 class="vdtitle">([^<]+)', html) or [None, vid])[1].strip()
        pic = self._pic((re.search(r'property="og:image" content="([^"]+)"', html) or [None, ""])[1])
        desc = (re.search(r'name="description" content="([^"]*)"', html) or [None, ""])[1]
        rel = (re.search(r'發行日期</div>\s*<div class="field__item"><time[^>]*>([^<]+)', html)
               or [None, ""])[1]

        eps = self._srcs(html)
        if eps:
            play_from = "默認"
            play_url = "#".join(f"線路{i+1}${u}" for i, u in enumerate(eps))
            remark = f"{len(eps)}線" if len(eps) > 1 else ""
        else:
            play_from, play_url, remark = "失效", "", "來源失效"

        return {"list": [{
            "vod_id": vid, "vod_name": title, "vod_pic": pic,
            "vod_remarks": remark, "vod_year": rel[:4] if rel else "",
            "vod_content": desc, "vod_play_from": play_from, "vod_play_url": play_url,
        }]}

    # ---------- 播放 ----------
    def playerContent(self, flag, id, vipFlags):
        hdr = json.dumps({"User-Agent": self.ua, "Referer": self.host + "/"})
        if ".m3u8" in id:
            token = base64.urlsafe_b64encode(id.encode()).decode()
            return {"parse": 0,
                    "url": "http://127.0.0.1:9978/proxy?do=py&type=m3u8&u=" + token,
                    "header": hdr}
        return {"parse": 0, "url": id, "header": hdr}

    # ---------- 清晰度分級：4K > 2K > 1080 > 720 > 480 ----------
    @staticmethod
    def _score(inf):
        res = re.search(r'RESOLUTION=\d+x(\d+)', inf)
        bw = re.search(r'BANDWIDTH=(\d+)', inf)
        h = int(res.group(1)) if res else 0
        b = int(bw.group(1)) if bw else 0
        if h >= 2000:
            tier = 5          # 4K / 2160
        elif h >= 1300:
            tier = 4          # 2K / 1440
        elif h >= 1000:
            tier = 3          # 1080
        elif h >= 700:
            tier = 2          # 720
        elif h >= 400:
            tier = 1          # 480
        elif h > 0:
            tier = 1          # 更低也按 480 檔處理
        else:
            tier = 0          # 純音頻變體
        return (tier, h, b)

    def _best(self, body, base):
        best, lines = None, body.splitlines()
        for i, l in enumerate(lines):
            if not l.startswith("#EXT-X-STREAM-INF"):
                continue
            uri = next((x.strip() for x in lines[i + 1:]
                        if x.strip() and not x.startswith("#")), None)
            if not uri:
                continue
            score = self._score(l)
            if best is None or score > best[0]:
                best = (score, uri)
        if not best or best[0][0] == 0:
            return None
        u = best[1]
        return u if u.startswith("http") else base + u

    def _sort_master(self, body, base):
        head, pairs = [], []
        lines = body.splitlines()
        i = 0
        while i < len(lines):
            l = lines[i]
            if l.startswith("#EXT-X-STREAM-INF"):
                uri = next((x.strip() for x in lines[i + 1:]
                            if x.strip() and not x.startswith("#")), None)
                if uri:
                    pairs.append((self._score(l), l,
                                  uri if uri.startswith("http") else base + uri))
                    i += 2
                    continue
            head.append(l)
            i += 1
        pairs.sort(key=lambda x: x[0], reverse=True)
        out = [x for x in head if x.startswith("#")]
        for _, inf, uri in pairs:
            out += [inf, uri]
        return "\n".join(out)

    def localProxy(self, param):
        raw = base64.urlsafe_b64decode(str(param.get("u")).encode()).decode()
        r = self.s.get(raw, timeout=self.TIMEOUT)
        base = raw.rsplit("/", 1)[0] + "/"
        body = r.text

        if "#EXT-X-STREAM-INF" in body:
            if self.FORCE_HIGHEST:
                top = self._best(body, base)
                if top:
                    raw, base = top, top.rsplit("/", 1)[0] + "/"
                    body = self.s.get(raw, timeout=self.TIMEOUT).text
            else:
                body = self._sort_master(body, base)

        lines = []
        for line in body.splitlines():
            t = line.strip()
            if not t or t.startswith("#"):
                lines.append(line)
            else:
                lines.append(t if t.startswith("http") else base + t)
        return [200, "application/vnd.apple.mpegurl", "\n".join(lines).encode(), {}]