# -*- coding: utf-8 -*-
# 广西妹妹 https://gaximm.gaximm01.lol/gaximm/
# WordPress 站：分类 /gaximm/vt/{slug}/，翻页 /gaximm/vt/{slug}/page/{n}/
# 卡片 div.post-item，/gaximm/v/{id}/，封面 img[src] 直链，标题 span
# 播放页 JS 里 url: 'https://.../index.m3u8' 直出；搜索 /gaximm/?s={词}

import re
import ssl
import html as html_lib
import urllib.request

try:
    from base.spider import Spider as BaseSpider
except Exception:
    try:
        from models.spider import Spider as BaseSpider
    except Exception:
        class BaseSpider:
            def getName(self): return ""


class Spider(BaseSpider):

    def getName(self):
        return "广西妹妹"

    def init(self, extend=""):
        self.site = "https://gaximm.gaximm01.lol"
        self.base = self.site + "/gaximm"
        self.ua = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
                   "(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
        self.ctx = ssl.create_default_context()
        self.ctx.check_hostname = False
        self.ctx.verify_mode = ssl.CERT_NONE
        self.cats = [
            ("ou-mei-jin-bao", "欧美劲爆"), ("lun-li-ying-pian", "伦理影片"),
            ("zi-pai-tou-pai", "自拍偷拍"), ("ri-han-wu-ma", "日韩无码"),
            ("cheng-ren-dong-man", "成人动漫"), ("ri-han-jing-pin", "日韩精品"),
            ("guo-chan-zhu-bo", "国产主播"), ("zi-wei-xi-lie", "自慰系列"),
            ("kou-jiao-shi-pin", "口交视频"), ("jiao-shi-xue-sheng", "教师学生"),
            ("yan-she-xi-lie", "颜射系列"), ("ju-ru-you-wu", "巨乳尤物"),
            ("qun-p-huan-qi", "群P换妻"), ("ai-huan-lian", "AI换脸"),
            ("av-ming-xing", "AV明星"), ("av-jie-shuo", "AV解说"),
            ("zhong-wen-zi-mu", "中文字幕"), ("sm-zhong-wei", "SM重味"),
            ("qiang-jian-luan-lun", "强奸乱伦"), ("ren-qi-xi-lie", "人妻系列"),
            ("zhi-fu-you-huo", "制服诱惑"), ("shu-nv-shao-fu", "熟女少妇"),
            ("chi-gua-hei-liao", "吃瓜黑料"), ("yan-zhi-zheng-yi", "颜值正义"),
            ("guo-chan-chuan-mei", "国产传媒"), ("jiu-dian-tan-hua", "酒店探花"),
            ("zhi-bo-luo-liao", "直播裸聊"), ("fan-cha-mu-gou", "反差母狗"),
            ("jia-ting-luan-lun", "家庭乱伦"), ("tou-qing-shao-fu", "偷情少妇"),
            ("bai-he-nv-tong", "百合女同"), ("sm-tiao-jiao", "SM调教"),
            ("lu-guan-bi-kan", "撸管必看"), ("ye-zhan-che-zhen", "野战车震"),
            ("xue-sheng-kong-jie", "学生空姐"),
        ]

    # ---------- 基础 ----------
    def _get(self, url, timeout=15):
        req = urllib.request.Request(url, headers={
            "User-Agent": self.ua, "Referer": self.base + "/",
            "Accept": "text/html,application/xhtml+xml",
            "Accept-Language": "zh-CN,zh;q=0.9",
        })
        with urllib.request.urlopen(req, timeout=timeout, context=self.ctx) as r:
            return r.read().decode("utf-8", errors="replace")

    def _cards(self, html):
        out, seen = [], set()
        for m in re.finditer(r'<div class="post-item"[^>]*>', html):
            seg = html[m.start():m.start() + 1500]
            hm = re.search(r'href="([^"]+/gaximm/v/[^"/]+/?)"', seg)
            if not hm:
                continue
            href = hm.group(1)
            # 统一成相对路径
            href = re.sub(r'^https?://[^/]+', '', href)
            if href in seen:
                continue
            seen.add(href)
            title_m = re.search(r'<span>(.*?)</span>', seg, re.S)
            title = html_lib.unescape(re.sub(r'<[^>]+>', '', title_m.group(1))).strip() if title_m else ""
            img_m = re.search(r'<img[^>]+src="([^"]+)"', seg)
            pic = img_m.group(1) if img_m else ""
            if pic.startswith("//"):
                pic = "https:" + pic
            if title:
                out.append({"vod_id": href, "vod_name": title, "vod_pic": pic, "vod_remarks": ""})
        return out

    # ---------- 接口 ----------
    def homeContent(self, filter):
        cats = [{"type_id": s, "type_name": n} for s, n in self.cats]
        return {"class": cats, "filters": {}, "list": []}

    def homeVideoContent(self):
        try:
            return {"list": self._cards(self._get(self.base + "/"))}
        except Exception:
            return {"list": []}

    def categoryContent(self, cid, page, filter, ext):
        page = int(page or 1)
        if page > 1:
            url = "%s/vt/%s/page/%d/" % (self.base, cid, page)
        else:
            url = "%s/vt/%s/" % (self.base, cid)
        try:
            return {"list": self._cards(self._get(url)), "page": page,
                    "pagecount": 9999, "limit": 12, "total": 999999}
        except Exception:
            return {"list": []}

    def searchContent(self, key, quick, page="1"):
        from urllib.parse import quote
        url = "%s/?s=%s" % (self.base, quote(key))
        try:
            return {"list": self._cards(self._get(url)), "page": int(page or 1),
                    "pagecount": 9999, "limit": 12, "total": 999999}
        except Exception:
            return {"list": []}

    def detailContent(self, ids):
        vid = ids[0]
        url = vid if vid.startswith("http") else self.site + vid
        try:
            html = self._get(url)
        except Exception:
            html = ""
        title_m = re.search(r'<h1[^>]*>(.*?)</h1>', html, re.S)
        title = html_lib.unescape(re.sub(r'<[^>]+>', '', title_m.group(1))).strip() if title_m else vid
        img_m = re.search(r'<img[^>]+src="([^"]+)"', html)
        pic = img_m.group(1) if img_m else ""
        if pic.startswith("//"):
            pic = "https:" + pic
        v = {"vod_id": vid, "vod_name": title, "vod_pic": pic,
             "vod_play_from": "在线播放", "vod_play_url": "播放$" + vid}
        return {"list": [v]}

    def playerContent(self, flag, id, vipFlags):
        vid = id.split("$")[-1]
        url = vid if vid.startswith("http") else self.site + vid
        play_url, parse = "", 1
        try:
            html = self._get(url)
            m = re.search(r"url:\s*'(https?://[^\s']+\.m3u8[^\s']*)'", html)
            if m:
                play_url, parse = m.group(1), 0
            else:
                m3u8s = set(re.findall(r'https?://[^\s"\']+\.m3u8[^\s"\']*', html))
                if m3u8s:
                    play_url, parse = sorted(m3u8s)[0], 0
        except Exception:
            pass
        return {"parse": parse, "url": play_url, "playUrl": play_url,
                "header": {"User-Agent": self.ua, "Referer": url}}

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

    def destroy(self):
        pass
