# -*- coding: utf-8 -*-
# AnaCams 直播源 (TVBox Python Spider)
# 站点结构(实测 2026-11-02):
#   本质: Chaturbate 导流站，列表在 anacams.com，播放走 chaturbate.com
#   列表: GET https://anacams.com/models/ 及 /models/{pg}/
#         卡片: <a href="/model/{name}/" class="stretched-link">
#               <h2 class="card-title">{name}</h2></a>
#         封面: <img class="card-img-top" src="https://thumb.live.mmcdn.com/riw/{name}.jpg">
#         每页约 64 张，真分页 (/2/, /3/... )。
#   详情: 免抓，vod_id 即模特名。
#   播放: 模特页 https://anacams.com/model/{name}/ 内嵌
#         <iframe src="https://chaturbate.com/embed/{cb_user}/...">
#         取 cb_user 后抓 https://chaturbate.com/{cb_user}/
#         内嵌 "hls_source"(整页 \\uXXXX 转义，解转义后正则取)，
#         为签名 LL-HLS 主清单，token 绑出口 IP，必须现抓现解。
#         无 hls_source 时退 parse=1。
import re
import ssl
import time
import json
import gzip
import http.client
import urllib.request
import urllib.parse
from http.cookiejar import CookieJar

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


class Spider(BaseSpider):

    def __init__(self):
        self.site_url = "https://anacams.com"
        self.cb_url = "https://chaturbate.com"
        self.headers = {
            "User-Agent": "Mozilla/5.0 (Linux; Android 13) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36",
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
            "Accept-Language": "en-US,en;q=0.9",
            "Connection": "keep-alive",
        }
        self.cookie_jar = CookieJar()
        self.opener = self._build_opener()
        self._throttle = 0.5
        self._last_req = 0.0

    # ---------- 基础抓取 ----------
    def _build_opener(self):
        ctx = ssl.create_default_context()
        ctx.check_hostname = False
        ctx.verify_mode = ssl.CERT_NONE
        return urllib.request.build_opener(
            urllib.request.HTTPSHandler(context=ctx),
            urllib.request.HTTPCookieProcessor(self.cookie_jar),
        )

    def _decode(self, raw):
        if not raw:
            return ""
        if raw[:2] == b"\x1f\x8b":
            try:
                raw = gzip.decompress(raw)
            except Exception:
                pass
        return raw.decode("utf-8", errors="ignore")

    def _fetch(self, url, referer=None):
        headers = dict(self.headers)
        if referer:
            headers["Referer"] = referer
        gap = time.time() - self._last_req
        if gap < self._throttle:
            time.sleep(self._throttle - gap)
        self._last_req = time.time()
        for _ in range(3):
            try:
                req = urllib.request.Request(url, headers=headers)
                with self.opener.open(req, timeout=15) as resp:
                    raw = resp.read()
                    if raw:
                        return self._decode(raw)
            except http.client.IncompleteRead as e:
                if e.partial:
                    return self._decode(bytes(e.partial))
            except Exception:
                time.sleep(0.5)
        return ""

    # ---------- 卡片解析 ----------
    def _parse_cards(self, html):
        cards, seen = [], set()
        # 卡片: <a href="/model/xxx/" class="stretched-link"><h2 class="card-title">xxx</h2></a>
        for m in re.finditer(
            r'<a[^>]+href="(/model/([^"/]+)/)"[^>]*class="stretched-link"[^>]*>\s*'
            r'<h2[^>]*class="card-title"[^>]*>([^<]+)</h2>',
            html, re.I,
        ):
            name = m.group(2).strip()
            title = m.group(3).strip()
            if not name or name in seen:
                continue
            seen.add(name)
            # 封面: thumb.live.mmcdn.com/riw/{name}.jpg
            pic = "https://thumb.live.mmcdn.com/riw/%s.jpg" % name
            # 找同卡片内的 img 确认（可能有不同尺寸）
            cards.append({
                "vod_id": name,
                "vod_name": title or name,
                "vod_pic": pic,
                "vod_remarks": "Live",
            })
        return cards

    # ---------- 壳接口 ----------
    def init(self, extend=""):
        return ""

    def getName(self):
        return "AnaCams"

    # 分类: 全部 + 55 个标签
    CATS = [
        ("all", "全部模特"),
        ("tag:18-years-old", "18岁"),
        ("tag:amateur", "业余"),
        ("tag:anal", "肛交"),
        ("tag:asian", "亚洲"),
        ("tag:ass", "美臀"),
        ("tag:ass-clapping", "拍臀"),
        ("tag:babe", "美女"),
        ("tag:bbc", "BBC"),
        ("tag:big-ass", "巨臀"),
        ("tag:big-dick", "巨根"),
        ("tag:big-tits", "巨乳"),
        ("tag:blonde", "金发"),
        ("tag:blowjob", "口交"),
        ("tag:boobs", "胸部"),
        ("tag:booty", "翘臀"),
        ("tag:bouncing-tits", "抖胸"),
        ("tag:brunette", "褐发"),
        ("tag:cock", "肉棒"),
        ("tag:cum", "射精"),
        ("tag:cumshot", "颜射"),
        ("tag:cute", "可爱"),
        ("tag:dildo", "假阳具"),
        ("tag:doggystyle", "后入"),
        ("tag:ebony", "黑珍珠"),
        ("tag:hot", "热门"),
        ("tag:huge-tits", "豪乳"),
        ("tag:latina", "拉丁"),
        ("tag:lingerie", "内衣"),
        ("tag:milf", "熟女"),
        ("tag:naked", "裸体"),
        ("tag:natural-tits", "天然胸"),
        ("tag:nude", "裸露"),
        ("tag:onlyfans", "OnlyFans"),
        ("tag:petite", "娇小"),
        ("tag:public", "公共场合"),
        ("tag:pussy", "蜜穴"),
        ("tag:sexy", "性感"),
        ("tag:strip", "脱衣"),
        ("tag:shemale", "人妖"),
        ("tag:teen", "少女"),
        ("tag:trans", "跨性别"),
        ("tag:twerking", "电臀"),
    ]

    def homeContent(self, filter):
        return {
            "class": [{"type_id": tid, "type_name": name} for tid, name in self.CATS],
            "filters": {},
        }

    def homeVideoContent(self):
        html = self._fetch(self.site_url + "/models/")
        return {"list": self._parse_cards(html)}

    def _cat_url(self, tid, pg):
        tid = str(tid or "all")
        if tid.startswith("tag:"):
            slug = tid[4:]
            base = "%s/tiktok-porn/%s/" % (self.site_url, slug)
            if pg > 1:
                base += "p-%d/" % pg
        else:
            # models分页: 第1页 /models/，第N页 /{N}/
            base = self.site_url + "/models/" if pg == 1 else "%s/%d/" % (self.site_url, pg)
        return base

    def categoryContent(self, tid, pg, filter, extend):
        try:
            pg = int(pg)
        except Exception:
            pg = 1
        if pg < 1:
            pg = 1
        url = self._cat_url(tid, pg)
        cards = self._parse_cards(self._fetch(url))
        return {"list": cards, "page": pg, "pagecount": pg + 1, "limit": len(cards), "total": 0}

    def detailContent(self, ids):
        name = str(ids[0]).strip().strip("/") if ids else ""
        if not name:
            return {"list": []}
        return {"list": [{
            "vod_id": name,
            "vod_name": name,
            "vod_pic": "https://thumb.live.mmcdn.com/riw/%s.jpg" % name,
            "vod_remarks": "直播",
            "vod_content": "AnaCams 直播间: %s" % name,
            "vod_play_from": "AnaCams",
            "vod_play_url": "直播$%s" % name,
        }]}

    def playerContent(self, flag, id, vipFlags):
        name = str(id or "").split("$")[-1].strip().strip("/")
        header = {"User-Agent": self.headers["User-Agent"], "Referer": self.site_url + "/"}
        if not name:
            return {"parse": 1, "url": self.site_url + "/", "header": header}
        # 1. 模特页取 chaturbate 用户名
        html = self._fetch("%s/model/%s/" % (self.site_url, name), referer=self.site_url + "/models/")
        cb_user = ""
        m = re.search(r'chaturbate\.com/embed/([^/?#"\s]+)', html)
        if m:
            cb_user = m.group(1)
        if not cb_user:
            cb_user = name  # 兜底：多数情况下两站用户名一致
        # 2. chaturbate 房间页解 hls_source
        room_url = "%s/%s/" % (self.cb_url, cb_user)
        room_html = self._fetch(room_url, referer=self.cb_url + "/")
        stream = self._extract_hls(room_html)
        if stream:
            return {"parse": 0, "url": stream, "header": header}
        return {"parse": 1, "url": room_url, "header": header}

    def searchContent(self, key, quick, pg="1"):
        # 站无搜索接口，拉首页按名过滤
        kw = str(key or "").strip().lower()
        if not kw:
            return {"list": []}
        cards = self._parse_cards(self._fetch(self.site_url + "/models/"))
        hit = [c for c in cards if kw in c["vod_name"].lower() or kw in c["vod_id"].lower()]
        return {"list": hit, "page": 1, "pagecount": 1, "limit": len(hit), "total": len(hit)}

    # ---------- 播放解析（Chaturbate 同款） ----------
    @staticmethod
    def _extract_hls(html):
        if not html:
            return ""
        dec = html.replace("\\/", "/")
        try:
            dec = re.sub(r"\\u([0-9a-fA-F]{4})", lambda m: chr(int(m.group(1), 16)), dec)
        except Exception:
            pass
        m = re.search(r'"hls_source"\s*:\s*"(https://[^"\\]+?\.m3u8[^"\\]*)"', dec)
        if m:
            return m.group(1)
        m = re.search(r'https://[^\s"\\]+?llhls\.m3u8[^\s"\\]*', dec)
        return m.group(0) if m else ""

    def isVideoFormat(self, url):
        u = (url or "").lower()
        return ".m3u8" in u or u.endswith(".mp4")

    def manualVideoCheck(self):
        return False

    def destroy(self):
        pass
