from base.spider import Spider
import requests
import re
import urllib.parse

host = "https://vip.wwgz.cn:5200"
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36'
}
timeout = 15

class Spider(Spider):
    def getName(self):
        return "旺旺影视"

    def init(self, extend):
        pass

    def isVideoFormat(self, url):
        pass

    def manualVideoCheck(self):
        pass

    def homeContent(self, filter):
        return {
            "class": [
                {"type_id": "1", "type_name": "电影"},
                {"type_id": "2", "type_name": "剧集"},
                {"type_id": "3", "type_name": "综艺"},
                {"type_id": "4", "type_name": "动漫"},
                {"type_id": "5", "type_name": "短剧"}
            ]
        }

    def homeVideoContent(self):
        return {'list': []}

    def categoryContent(self, cid, pg, filter, ext):
        page = int(pg) if pg else 1
        videos = []
        
        # 苹果CMS标准URL格式: /vod-type-id-分类-pg-页码.html
        url = f"{host}/vod-type-id-{cid}-pg-{page}.html"
        
        try:
            r = requests.get(url, headers=headers, timeout=timeout)
            r.encoding = 'utf-8'
            html = r.text
            
            # 提取视频列表 - 苹果CMS常见格式
            # 格式1: <a href="/vod-detail-id-xxx.html" title="标题">
            pattern = r'<a[^>]*href="(/vod-detail-id-([^"]+)\.html)"[^>]*title="([^"]*)"'
            matches = re.findall(pattern, html)
            
            if not matches:
                # 格式2: <a href="/vod/xxx.html"> <img alt="标题">
                pattern = r'<a[^>]*href="(/vod/[^"]+\.html)"[^>]*>.*?<img[^>]*alt="([^"]*)"'
                matches = re.findall(pattern, html, re.DOTALL)
                matches = [(m[0], m[0].split('/')[-1].replace('.html', ''), m[1]) for m in matches]
            
            if not matches:
                # 格式3: 通用匹配
                pattern = r'href="(/vod[^"]+\.html)"[^>]*>([^<]+)</a>'
                raw = re.findall(pattern, html)
                matches = []
                for link, title in raw:
                    if 'detail' in link or 'play' in link:
                        vid = link.split('/')[-1].replace('.html', '').replace('detail-', '').replace('id-', '')
                        matches.append((link, vid, title.strip()))
            
            for link, vid, name in matches:
                if len(name) < 2 or '首页' in name or '上一页' in name:
                    continue
                videos.append({
                    "vod_id": vid,
                    "vod_name": name,
                    "vod_pic": "",
                    "vod_remarks": ""
                })
                
        except Exception as e:
            print(f"Error: {e}")
        
        return {
            'list': videos,
            'page': page,
            'pagecount': 999,
            'limit': len(videos),
            'total': 99999
        }

    def detailContent(self, ids):
        vid = ids[0]
        
        # 尝试多种URL格式
        urls = [
            f"{host}/vod-detail-id-{vid}.html",
            f"{host}/vod/{vid}.html",
            f"{host}/detail/{vid}.html",
            f"{host}/index.php?m=vod&id={vid}"
        ]
        
        html = ""
        for url in urls:
            try:
                r = requests.get(url, headers=headers, timeout=timeout)
                if r.status_code == 200:
                    r.encoding = 'utf-8'
                    html = r.text
                    break
            except:
                continue
        
        if not html:
            return {'list': []}
        
        try:
            # 提取标题
            title = ""
            t = re.search(r'<h1[^>]*>([^<]+)</h1>', html)
            if t:
                title = t.group(1).strip()
            if not title:
                t = re.search(r'<title>([^<]+)</title>', html)
                if t:
                    title = t.group(1).strip()
            
            # 提取封面
            pic = ""
            p = re.search(r'<img[^>]*src="([^"]*)"[^>]*class="[^"]*pic[^"]*"', html)
            if not p:
                p = re.search(r'<img[^>]*src="([^"]*)"[^>]*alt="[^"]*"', html)
            if p:
                pic = p.group(1)
                if pic and not pic.startswith('http'):
                    pic = host + pic if pic.startswith('/') else host + '/' + pic
            
            # 提取演员
            actor = ""
            a = re.search(r'主演[：:]\s*([^<\n]+)', html)
            if a:
                actor = a.group(1).strip()
            
            # 提取简介
            desc = ""
            d = re.search(r'简介[：:]\s*([^<\n]+)', html)
            if d:
                desc = d.group(1).strip()
            
            # 提取播放链接
            play_items = []
            
            # 苹果CMS播放列表格式: <a href="/vod-play-id-xxx.html">第1集</a>
            links = re.findall(r'<a[^>]*href="(/vod-play-id-[^"]+\.html)"[^>]*>([^<]+)</a>', html)
            
            if not links:
                links = re.findall(r'<a[^>]*href="(/vod/[^"]+\.html)"[^>]*>([^<]+)</a>', html)
            
            for link, name in links:
                link = link.strip()
                name = name.strip()
                if not link or not name:
                    continue
                if 'javascript' in link or link == '#':
                    continue
                if '搜索' in name or '首页' in name:
                    continue
                
                if not link.startswith('http'):
                    link = host + link if link.startswith('/') else host + '/' + link
                play_items.append(f"{name}${link}")
            
            # 如果没有播放链接，找iframe
            if not play_items:
                iframe = re.search(r'<iframe[^>]*src="([^"]*)"', html)
                if iframe:
                    iframe_url = iframe.group(1)
                    if not iframe_url.startswith('http'):
                        iframe_url = host + iframe_url if iframe_url.startswith('/') else host + '/' + iframe_url
                    play_items.append(f"播放${iframe_url}")
            
            vod = {
                "vod_id": vid,
                "vod_name": title or vid,
                "vod_pic": pic,
                "vod_actor": actor,
                "type_name": "",
                "vod_remarks": "",
                "vod_content": desc,
                "vod_play_from": "播放源" if play_items else "",
                "vod_play_url": "#".join(play_items) if play_items else ""
            }
            
            return {'list': [vod]}
            
        except:
            return {'list': []}

    def playerContent(self, flag, id, vipFlags):
        # 直接返回播放地址
        return {
            "parse": 0,
            "playUrl": '',
            "url": id,
            "header": headers
        }

    def searchContent(self, key, quick, pg=1):
        page = int(pg) if pg else 1
        videos = []
        
        url = f"{host}/vod-search-pg-{page}-wd-{urllib.parse.quote(key)}.html"
        
        try:
            r = requests.get(url, headers=headers, timeout=timeout)
            r.encoding = 'utf-8'
            html = r.text
            
            pattern = r'<a[^>]*href="(/vod-detail-id-([^"]+)\.html)"[^>]*title="([^"]*)"'
            matches = re.findall(pattern, html)
            
            for link, vid, name in matches:
                if len(name) < 2:
                    continue
                videos.append({
                    "vod_id": vid,
                    "vod_name": name,
                    "vod_pic": "",
                    "vod_remarks": ""
                })
                
        except:
            pass
        
        return {
            'list': videos,
            'page': page,
            'pagecount': 99,
            'limit': len(videos),
            'total': 9999
        }