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

host = "https://www.pdy0.com"
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',
    'Referer': host
}
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):
        classes = [
            {"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": "短剧"}
        ]
        return {"class": classes}

    def homeVideoContent(self):
        videos = []
        try:
            url = host + "/"
            response = requests.get(url=url, headers=headers, timeout=timeout)
            response.encoding = "utf-8"
            html = response.text
            
            # 打印部分html调试
            print(f"首页HTML长度: {len(html)}")
            
            # 匹配推荐视频 - 使用更通用的模式
            # 匹配 <a href="/vod/xxx.html"> 里面有图片的
            pattern = r'<a[^>]*href="(/vod/[^"]+\.html)"[^>]*>.*?<img[^>]*src="([^"]*)"[^>]*alt="([^"]*)"'
            matches = re.findall(pattern, html, re.DOTALL)
            
            if not matches:
                # 尝试另一种匹配
                pattern = r'<img[^>]*src="([^"]*)"[^>]*alt="([^"]*)"[^>]*/>.*?<a[^>]*href="(/vod/[^"]+\.html)"'
                matches = re.findall(pattern, html, re.DOTALL)
                for match in matches:
                    pic, title, link = match
                    matches = [(link, pic, title)]
            
            for match in matches[:30]:
                if len(match) >= 3:
                    link = match[0]
                    pic = match[1]
                    title = match[2]
                elif len(match) == 2:
                    link, pic = match
                    title = ""
                else:
                    continue
                
                if not link.startswith('http'):
                    if link.startswith('/'):
                        link = host + link
                    else:
                        link = host + '/' + link
                
                if pic and not pic.startswith('http'):
                    if pic.startswith('/'):
                        pic = host + pic
                    else:
                        pic = host + '/' + pic
                
                # 提取vod_id
                vod_id = re.search(r'/vod/([^/]+)\.html', link)
                vod_id = vod_id.group(1) if vod_id else link
                
                videos.append({
                    "vod_id": vod_id,
                    "vod_name": title.strip() if title else "未知",
                    "vod_pic": pic,
                    "vod_remarks": ""
                })
                
        except Exception as e:
            print(f"获取首页内容失败: {e}")
            
        return {'list': videos}

    def categoryContent(self, cid, pg, filter, ext):
        videos = []
        page = int(pg) if pg else 1
        
        # 分类映射
        type_map = {
            "1": "1",  # 电影
            "2": "2",  # 剧集
            "3": "3",  # 综艺
            "4": "4",  # 动漫
            "5": "5"   # 短剧
        }
        
        type_id = type_map.get(str(cid), "1")
        url = f"{host}/vod/type/id/{type_id}/page/{page}.html"
        
        print(f"分类URL: {url}")
        
        try:
            response = requests.get(url=url, headers=headers, timeout=timeout)
            response.encoding = "utf-8"
            html = response.text
            
            print(f"分类HTML长度: {len(html)}")
            
            # 匹配视频列表 - 更通用的模式
            # 模式1: 标准列表
            pattern = r'<a[^>]*href="(/vod/[^"]+\.html)"[^>]*>.*?<img[^>]*src="([^"]*)"[^>]*alt="([^"]*)"'
            matches = re.findall(pattern, html, re.DOTALL)
            
            if not matches:
                # 模式2: li标签内的
                pattern = r'<li[^>]*>.*?<a[^>]*href="(/vod/[^"]+\.html)"[^>]*>.*?<img[^>]*src="([^"]*)"[^>]*alt="([^"]*)"'
                matches = re.findall(pattern, html, re.DOTALL)
            
            if not matches:
                # 模式3: 更宽松的匹配
                pattern = r'href="(/vod/[^"]+\.html)".*?src="([^"]+)".*?alt="([^"]+)"'
                matches = re.findall(pattern, html, re.DOTALL)
            
            # 如果还没匹配到，直接用img+alt提取
            if not matches:
                img_pattern = r'<img[^>]*src="([^"]+)"[^>]*alt="([^"]+)"'
                img_matches = re.findall(img_pattern, html)
                link_pattern = r'href="(/vod/[^"]+\.html)"'
                link_matches = re.findall(link_pattern, html)
                
                # 组合匹配
                for i in range(min(len(img_matches), len(link_matches))):
                    pic, title = img_matches[i]
                    link = link_matches[i]
                    matches.append((link, pic, title))
            
            print(f"匹配到 {len(matches)} 个视频")
            
            for match in matches:
                if len(match) >= 3:
                    link = match[0]
                    pic = match[1]
                    title = match[2]
                elif len(match) == 2:
                    link, pic = match
                    title = ""
                else:
                    continue
                
                # 补全链接
                if not link.startswith('http'):
                    if link.startswith('/'):
                        link = host + link
                    else:
                        link = host + '/' + link
                
                if pic and not pic.startswith('http'):
                    if pic.startswith('/'):
                        pic = host + pic
                    else:
                        pic = host + '/' + pic
                
                # 提取vod_id
                vod_id = re.search(r'/vod/([^/]+)\.html', link)
                vod_id = vod_id.group(1) if vod_id else link.split('/')[-1].replace('.html', '')
                
                videos.append({
                    "vod_id": vod_id,
                    "vod_name": title.strip() if title else "未知",
                    "vod_pic": pic,
                    "vod_remarks": ""
                })
                    
        except Exception as e:
            print(f"获取分类内容失败: {e}")
            
        return {
            'list': videos,
            'page': page,
            'pagecount': 99,
            'limit': len(videos),
            'total': 9999
        }

    def detailContent(self, ids):
        did = ids[0]
        
        # 构建详情URL
        if '.html' in did:
            detail_url = did if did.startswith('http') else host + did
        else:
            detail_url = f"{host}/vod/{did}.html"
        
        print(f"详情URL: {detail_url}")
        
        try:
            response = requests.get(url=detail_url, headers=headers, timeout=timeout)
            response.encoding = "utf-8"
            html = response.text
            
            print(f"详情HTML长度: {len(html)}")
            
            # 提取标题
            title_match = re.search(r'<h1[^>]*>([^<]+)</h1>', html)
            title = title_match.group(1).strip() if title_match else ""
            
            if not title:
                title_match = re.search(r'<title>([^<]+)</title>', html)
                title = title_match.group(1).strip() if title_match else ""
            
            # 提取封面
            pic_match = re.search(r'<img[^>]*class="[^"]*pic[^"]*"[^>]*src="([^"]+)"', html)
            if not pic_match:
                pic_match = re.search(r'<img[^>]*src="([^"]+)"[^>]*class="[^"]*pic[^"]*"', html)
            if not pic_match:
                pic_match = re.search(r'<div[^>]*class="[^"]*poster[^"]*"[^>]*>.*?<img[^>]*src="([^"]+)"', html, re.DOTALL)
            pic = pic_match.group(1) if pic_match else ""
            if pic and not pic.startswith('http'):
                pic = host + pic if pic.startswith('/') else host + '/' + pic
            
            # 提取演员
            actor_match = re.search(r'演员[：:]\s*([^<\n]+)', html)
            if not actor_match:
                actor_match = re.search(r'主演[：:]\s*([^<\n]+)', html)
            actor = actor_match.group(1).strip() if actor_match else ""
            
            # 提取类型
            type_match = re.search(r'类型[：:]\s*([^<\n]+)', html)
            type_name = type_match.group(1).strip() if type_match else ""
            
            # 提取简介
            desc_match = re.search(r'简介[：:]\s*([^<\n]+)', html)
            if not desc_match:
                desc_match = re.search(r'<div[^>]*class="[^"]*desc[^"]*"[^>]*>([^<]+)</div>', html)
            if not desc_match:
                desc_match = re.search(r'<p[^>]*class="[^"]*desc[^"]*"[^>]*>([^<]+)</p>', html)
            desc = desc_match.group(1).strip() if desc_match else ""
            
            # 提取播放列表
            play_from = []
            play_url = []
            
            # 匹配播放链接 - 各种模式
            # 模式1: <a href="...">名称</a>
            pattern = r'<a[^>]*href="([^"]*play[^"]*\.html[^"]*)"[^>]*>([^<]+)</a>'
            matches = re.findall(pattern, html)
            
            if not matches:
                pattern = r'<a[^>]*href="([^"]*vod[^"]*\.html[^"]*)"[^>]*>([^<]+)</a>'
                matches = re.findall(pattern, html)
            
            if not matches:
                pattern = r'<a[^>]*href="([^"]*m3u8[^"]*)"[^>]*>([^<]+)</a>'
                matches = re.findall(pattern, html)
            
            # 过滤并构建播放列表
            play_items = []
            for link, name in matches:
                # 过滤掉非播放链接
                if 'search' in link or 'type' in link:
                    continue
                if not link.startswith('http'):
                    if link.startswith('/'):
                        link = host + link
                    else:
                        link = host + '/' + link
                # 清除空白字符
                name = name.strip()
                if name and link:
                    play_items.append(f"{name}${link}")
            
            if play_items:
                play_from.append("播放源")
                play_url.append("#".join(play_items))
            else:
                # 如果没有匹配到，尝试从iframe提取
                iframe_match = re.search(r'<iframe[^>]*src="([^"]*)"', html)
                if iframe_match:
                    iframe_url = iframe_match.group(1)
                    play_from.append("播放源")
                    play_url.append(f"播放$" + iframe_url)
            
            vod = {
                "vod_id": did,
                "vod_name": title,
                "vod_pic": pic,
                "vod_actor": actor,
                "type_name": type_name,
                "vod_remarks": "",
                "vod_content": desc,
                "vod_play_from": "$$$".join(play_from) if play_from else "",
                "vod_play_url": "$$$".join(play_url) if play_url else ""
            }
            
            print(f"解析到: {title}, 播放源: {play_from}")
            
            return {'list': [vod]}
            
        except Exception as e:
            print(f"获取详情失败: {e}")
            return {'list': []}

    def playerContent(self, flag, id, vipFlags):
        print(f"播放请求: {id}")
        
        try:
            # 如果直接是视频地址
            if id.endswith('.m3u8') or id.endswith('.mp4') or 'm3u8' in id:
                return {
                    "parse": 0,
                    "playUrl": '',
                    "url": id,
                    "header": headers
                }
            
            response = requests.get(url=id, headers=headers, timeout=timeout)
            response.encoding = "utf-8"
            html = response.text
            
            # 提取视频地址 - 多种模式
            patterns = [
                r'<video[^>]*src="([^"]+)"',
                r'<iframe[^>]*src="([^"]+)"',
                r'data-video="([^"]+)"',
                r'data-url="([^"]+)"',
                r'url:"([^"]+)"',
                r'"url":"([^"]+)"',
                r'<source[^>]*src="([^"]+)"',
                r'src="([^"]*\.m3u8[^"]*)"',
                r'src="([^"]*\.mp4[^"]*)"',
                r'playUrl:\s*"([^"]+)"',
                r'video:\s*"([^"]+)"'
            ]
            
            for pattern in patterns:
                match = re.search(pattern, html)
                if match:
                    play_url = match.group(1)
                    if play_url:
                        if not play_url.startswith('http'):
                            if play_url.startswith('//'):
                                play_url = 'https:' + play_url
                            elif play_url.startswith('/'):
                                play_url = host + play_url
                        print(f"找到播放地址: {play_url}")
                        return {
                            "parse": 0,
                            "playUrl": '',
                            "url": play_url,
                            "header": headers
                        }
            
            # 如果没找到，尝试iframe嵌套
            iframe_match = re.search(r'<iframe[^>]*src="([^"]+)"', html)
            if iframe_match:
                iframe_url = iframe_match.group(1)
                if iframe_url and not iframe_url.startswith('http'):
                    if iframe_url.startswith('/'):
                        iframe_url = host + iframe_url
                    else:
                        iframe_url = host + '/' + iframe_url
                # 递归获取iframe中的视频
                try:
                    resp2 = requests.get(url=iframe_url, headers=headers, timeout=timeout)
                    resp2.encoding = "utf-8"
                    html2 = resp2.text
                    for pattern in patterns:
                        match = re.search(pattern, html2)
                        if match:
                            play_url = match.group(1)
                            if play_url and not play_url.startswith('http'):
                                if play_url.startswith('//'):
                                    play_url = 'https:' + play_url
                            if play_url:
                                return {
                                    "parse": 0,
                                    "playUrl": '',
                                    "url": play_url,
                                    "header": headers
                                }
                except:
                    pass
                    
        except Exception as e:
            print(f"获取播放地址失败: {e}")
            
        return {
            "parse": 0,
            "playUrl": '',
            "url": 'about:blank',
            "header": headers
        }

    def searchContent(self, key, quick, pg=1):
        videos = []
        page = int(pg) if pg else 1
        
        search_url = f"{host}/vod/search/page/{page}.html?wd={urllib.parse.quote(key)}"
        print(f"搜索URL: {search_url}")
        
        try:
            response = requests.get(url=search_url, headers=headers, timeout=timeout)
            response.encoding = "utf-8"
            html = response.text
            
            print(f"搜索HTML长度: {len(html)}")
            
            # 匹配搜索结果
            pattern = r'<a[^>]*href="(/vod/[^"]+\.html)"[^>]*>.*?<img[^>]*src="([^"]*)"[^>]*alt="([^"]*)"'
            matches = re.findall(pattern, html, re.DOTALL)
            
            if not matches:
                pattern = r'<img[^>]*src="([^"]*)"[^>]*alt="([^"]*)"[^>]*/>.*?<a[^>]*href="(/vod/[^"]+\.html)"'
                matches = re.findall(pattern, html, re.DOTALL)
                for match in matches:
                    pic, title, link = match
                    matches = [(link, pic, title)]
            
            print(f"搜索匹配到 {len(matches)} 个结果")
            
            for match in matches:
                if len(match) >= 3:
                    link = match[0]
                    pic = match[1]
                    title = match[2]
                elif len(match) == 2:
                    link, pic = match
                    title = ""
                else:
                    continue
                
                if not link.startswith('http'):
                    if link.startswith('/'):
                        link = host + link
                    else:
                        link = host + '/' + link
                
                if pic and not pic.startswith('http'):
                    if pic.startswith('/'):
                        pic = host + pic
                    else:
                        pic = host + '/' + pic
                
                vod_id = re.search(r'/vod/([^/]+)\.html', link)
                vod_id = vod_id.group(1) if vod_id else link.split('/')[-1].replace('.html', '')
                
                videos.append({
                    "vod_id": vod_id,
                    "vod_name": title.strip() if title else "未知",
                    "vod_pic": pic,
                    "vod_remarks": ""
                })
                
        except Exception as e:
            print(f"搜索失败: {e}")
            
        return {
            'list': videos,
            'page': page,
            'pagecount': 99,
            'limit': len(videos),
            'total': 9999
        }