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': 'https://www.pdy0.com/',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
    'Accept-Encoding': 'gzip, deflate, br',
    'Connection': 'keep-alive',
    'Upgrade-Insecure-Requests': '1'
}
timeout = 20

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):
        return {'list': []}

    def categoryContent(self, cid, pg, filter, ext):
        videos = []
        page = int(pg) if pg else 1
        
        # 根据实际页面结构，URL格式是 /vt/1.html 或 /vt/1_2.html
        if page == 1:
            url = f"{host}/vt/{cid}.html"
        else:
            url = f"{host}/vt/{cid}_{page}.html"
        
        print(f"分类URL: {url}")
        
        try:
            session = requests.Session()
            session.headers.update(headers)
            
            response = session.get(url=url, timeout=timeout, allow_redirects=True)
            response.encoding = "utf-8"
            html = response.text
            
            print(f"状态码: {response.status_code}")
            print(f"HTML长度: {len(html)}")
            
            # 根据你提供的页面内容，视频列表格式是：
            # <a href="/detail/xxx.html">标题</a>
            # 或者带有图片的格式
            
            # 方法1: 直接提取所有 /detail/ 链接
            detail_links = re.findall(r'<a[^>]*?href="(/detail/[^"]+\.html)"[^>]*?>([^<]+)</a>', html)
            
            print(f"找到 {len(detail_links)} 个详情链接")
            
            for link, title in detail_links:
                title = title.strip()
                # 过滤掉非视频标题（如导航、页码等）
                if not title or len(title) < 2:
                    continue
                if '首页' in title or '上一页' in title or '下一页' in title or '尾页' in title:
                    continue
                if 'HD' in title and len(title) < 10:  # 过滤掉单独的"HD"标签
                    continue
                
                vod_id = link.split('/')[-1].replace('.html', '')
                
                videos.append({
                    "vod_id": vod_id,
                    "vod_name": title,
                    "vod_pic": "",
                    "vod_remarks": ""
                })
            
            # 如果上面没找到，尝试匹配带图片的
            if not videos:
                pattern = r'<a[^>]*?href="(/detail/[^"]+\.html)"[^>]*?>.*?<img[^>]*?src="([^"]*?)"[^>]*?alt="([^"]*?)"'
                matches = re.findall(pattern, html, re.DOTALL)
                
                for match in matches:
                    link = match[0].strip()
                    pic = match[1].strip()
                    title = match[2].strip()
                    
                    if not title or len(title) < 2:
                        continue
                    
                    vod_id = link.split('/')[-1].replace('.html', '')
                    
                    if pic and not pic.startswith('http'):
                        pic = host + pic if pic.startswith('/') else host + '/' + pic
                    
                    videos.append({
                        "vod_id": vod_id,
                        "vod_name": title,
                        "vod_pic": pic,
                        "vod_remarks": ""
                    })
            
            # 如果还没找到，尝试从文本中提取视频标题
            if not videos:
                # 匹配类似 "### 公民义警" 这种格式
                title_pattern = r'<a[^>]*?href="/detail/[^"]+\.html"[^>]*?>([^<]+)</a>'
                titles = re.findall(title_pattern, html)
                
                for title in titles:
                    title = title.strip()
                    if not title or len(title) < 2:
                        continue
                    if '首页' in title or '上一页' in title or '下一页' in title or '尾页' in title:
                        continue
                    
                    # 生成一个简单的ID
                    vod_id = str(len(videos) + 1)
                    videos.append({
                        "vod_id": vod_id,
                        "vod_name": title,
                        "vod_pic": "",
                        "vod_remarks": ""
                    })
                    
        except Exception as e:
            print(f"获取分类内容失败: {e}")
            
        print(f"最终获取 {len(videos)} 个视频")
        
        # 打印前几个视频标题用于调试
        for i, v in enumerate(videos[:5]):
            print(f"  {i+1}. {v['vod_name']}")
        
        return {
            'list': videos,
            'page': page,
            'pagecount': 999,
            'limit': len(videos),
            'total': 99999
        }

    def detailContent(self, ids):
        did = ids[0]
        
        # 详情页URL格式: /detail/xxx.html
        if did.startswith('http'):
            detail_url = did
        elif '.html' in did:
            detail_url = host + did if did.startswith('/') else host + '/' + did
        else:
            detail_url = f"{host}/detail/{did}.html"
        
        print(f"详情URL: {detail_url}")
        
        try:
            session = requests.Session()
            session.headers.update(headers)
            
            response = session.get(url=detail_url, timeout=timeout)
            response.encoding = "utf-8"
            html = response.text
            
            print(f"详情页状态码: {response.status_code}, 长度: {len(html)}")
            
            # 提取标题
            title = ""
            title_match = re.search(r'<h1[^>]*>([^<]+)</h1>', html)
            if title_match:
                title = title_match.group(1).strip()
            if not title:
                title_match = re.search(r'<title>([^<]+)</title>', html)
                if title_match:
                    title = title_match.group(1).strip().replace(' - 皮克网', '').replace(' - 皮克', '')
            
            # 提取封面
            pic = ""
            pic_match = re.search(r'<img[^>]*?src="([^"]*?)"[^>]*?class="[^"]*?poster[^"]*?"', html)
            if not pic_match:
                pic_match = re.search(r'<img[^>]*?src="([^"]*?)"[^>]*?alt="[^"]*?"', html)
            if pic_match:
                pic = pic_match.group(1)
                if pic and not pic.startswith('http'):
                    pic = host + pic if pic.startswith('/') else host + '/' + pic
            
            # 提取演员
            actor = ""
            actor_match = re.search(r'主演[：:]\s*([^<\n]+)', html)
            if not actor_match:
                actor_match = re.search(r'演员[：:]\s*([^<\n]+)', html)
            if actor_match:
                actor = actor_match.group(1).strip()
            
            # 提取类型
            type_name = ""
            type_match = re.search(r'类型[：:]\s*([^<\n]+)', html)
            if type_match:
                type_name = type_match.group(1).strip()
            
            # 提取简介
            desc = ""
            desc_match = re.search(r'简介[：:]\s*([^<\n]+)', html)
            if desc_match:
                desc = desc_match.group(1).strip()
            
            # 提取播放链接
            play_items = []
            
            # 找所有播放链接
            play_pattern = r'<a[^>]*?href="([^"]*?)"[^>]*?>([^<]+?)</a>'
            all_links = re.findall(play_pattern, html)
            
            for link, name in all_links:
                link = link.strip()
                name = name.strip()
                
                if not link or not name:
                    continue
                if 'javascript' in link or '#' in link:
                    continue
                if 'search' in link or 'type' in link or 'vt' in link:
                    continue
                
                # 判断是否是播放链接
                if '播放' in name or '线路' in name or '集' in name or '第' in name or 'HD' in name:
                    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_match = re.search(r'<iframe[^>]*?src="([^"]*?)"', html)
                if iframe_match:
                    iframe_url = iframe_match.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": did,
                "vod_name": title,
                "vod_pic": pic,
                "vod_actor": actor,
                "type_name": type_name,
                "vod_remarks": "",
                "vod_content": desc,
                "vod_play_from": "播放源" if play_items else "",
                "vod_play_url": "#".join(play_items) if play_items else ""
            }
            
            print(f"标题: {title}, 播放链接: {len(play_items)}")
            
            return {'list': [vod]}
            
        except Exception as e:
            print(f"获取详情失败: {e}")
            return {'list': []}

    def playerContent(self, flag, id, vipFlags):
        print(f"播放请求: {id}")
        
        # 如果已经是视频地址
        if '.m3u8' in id or '.mp4' in id or 'm3u8' in id:
            return {
                "parse": 0,
                "playUrl": '',
                "url": id,
                "header": headers
            }
        
        try:
            session = requests.Session()
            session.headers.update(headers)
            
            response = session.get(url=id, timeout=timeout)
            response.encoding = "utf-8"
            html = response.text
            
            # 查找视频地址
            patterns = [
                r'<video[^>]*?src="([^"]*?)"',
                r'<iframe[^>]*?src="([^"]*?)"',
                r'src="([^"]*?\.m3u8[^"]*?)"',
                r'src="([^"]*?\.mp4[^"]*?)"',
                r'"url":"([^"]*?)"',
                r'playUrl":"([^"]*?)"',
                r'data-src="([^"]*?)"',
                r'data-url="([^"]*?)"',
                r'<source[^>]*?src="([^"]*?)"'
            ]
            
            for pattern in patterns:
                match = re.search(pattern, html, re.IGNORECASE)
                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
                            else:
                                play_url = host + '/' + play_url
                        print(f"找到播放地址: {play_url}")
                        return {
                            "parse": 0,
                            "playUrl": '',
                            "url": play_url,
                            "header": headers
                        }
            
            # 如果页面有iframe，进入iframe找
            iframe_match = re.search(r'<iframe[^>]*?src="([^"]*?)"', html)
            if iframe_match:
                iframe_url = iframe_match.group(1)
                if not iframe_url.startswith('http'):
                    iframe_url = host + iframe_url if iframe_url.startswith('/') else host + '/' + iframe_url
                
                try:
                    resp2 = session.get(url=iframe_url, timeout=timeout)
                    resp2.encoding = "utf-8"
                    html2 = resp2.text
                    
                    for pattern in patterns:
                        match = re.search(pattern, html2, re.IGNORECASE)
                        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}/search.html?wd={urllib.parse.quote(key)}"
        if page > 1:
            search_url = f"{host}/search_{page}.html?wd={urllib.parse.quote(key)}"
        
        print(f"搜索URL: {search_url}")
        
        try:
            session = requests.Session()
            session.headers.update(headers)
            
            response = session.get(url=search_url, timeout=timeout)
            response.encoding = "utf-8"
            html = response.text
            
            print(f"搜索页状态码: {response.status_code}, 长度: {len(html)}")
            
            # 匹配搜索结果
            detail_links = re.findall(r'<a[^>]*?href="(/detail/[^"]+\.html)"[^>]*?>([^<]+)</a>', html)
            
            for link, title in detail_links:
                title = title.strip()
                if not title or len(title) < 2:
                    continue
                if '首页' in title or '上一页' in title or '下一页' in title or '尾页' in title:
                    continue
                
                vod_id = link.split('/')[-1].replace('.html', '')
                
                videos.append({
                    "vod_id": vod_id,
                    "vod_name": title,
                    "vod_pic": "",
                    "vod_remarks": ""
                })
                
        except Exception as e:
            print(f"搜索失败: {e}")
            
        return {
            'list': videos,
            'page': page,
            'pagecount': 99,
            'limit': len(videos),
            'total': 9999
        }