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
            
            # 提取推荐视频（首页轮播或推荐区域）
            # 匹配类似 <a href="/vod/xxx.html"> 的链接
            pattern = r'<a[^>]*href="([^"]*)"[^>]*>\s*<img[^>]*src="([^"]*)"[^>]*alt="([^"]*)"[^>]*>'
            matches = re.findall(pattern, html)
            
            for match in matches[:20]:
                link = match[0]
                pic = match[1]
                title = match[2]
                
                if not pic.startswith('http'):
                    if pic.startswith('/'):
                        pic = host + pic
                    else:
                        pic = host + '/' + pic
                
                # 提取vod_id
                vod_id = link.split('/')[-1].replace('.html', '') if '.html' in link else link
                
                videos.append({
                    "vod_id": vod_id,
                    "vod_name": title.strip(),
                    "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"
        
        try:
            response = requests.get(url=url, headers=headers, timeout=timeout)
            response.encoding = "utf-8"
            html = response.text
            
            # 匹配视频列表
            # 常见模式: <div class="movie-item"> 或 <li> 等
            pattern = r'<a[^>]*href="([^"]*vod[^"]*\.html)"[^>]*>\s*<img[^>]*src="([^"]*)"[^>]*alt="([^"]*)"[^>]*>'
            matches = re.findall(pattern, html)
            
            if not matches:
                # 尝试其他模式
                pattern = r'<a[^>]*href="(/vod/[^"]+\.html)"[^>]*>\s*<div[^>]*>\s*<img[^>]*src="([^"]*)"[^>]*alt="([^"]*)"'
                matches = re.findall(pattern, html)
            
            for match in matches:
                if len(match) >= 3:
                    link = match[0]
                    pic = match[1] if len(match) > 1 else ""
                    title = match[2] if len(match) > 2 else ""
                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 = link.split('/')[-1].replace('.html', '') if '.html' in link else link
                
                videos.append({
                    "vod_id": vod_id,
                    "vod_name": title.strip() if title else "未知",
                    "vod_pic": pic,
                    "vod_remarks": ""
                })
            
            # 如果没有匹配到，尝试另一种模式
            if not videos:
                pattern = r'<li[^>]*>\s*<a[^>]*href="([^"]*)"[^>]*>\s*<img[^>]*src="([^"]*)"[^>]*\s*alt="([^"]*)"'
                matches = re.findall(pattern, html)
                for match in matches:
                    link, pic, title = match
                    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 = link.split('/')[-1].replace('.html', '')
                    videos.append({
                        "vod_id": vod_id,
                        "vod_name": title.strip(),
                        "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]
        
        # 如果did包含.html则直接使用，否则构建URL
        if '.html' in did:
            detail_url = did if did.startswith('http') else host + did
        else:
            detail_url = f"{host}/vod/{did}.html"
        
        try:
            response = requests.get(url=detail_url, headers=headers, timeout=timeout)
            response.encoding = "utf-8"
            html = response.text
            
            # 提取标题
            title_match = re.search(r'<h1[^>]*>([^<]+)</h1>', 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)
            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*([^<]+)', html)
            if not actor_match:
                actor_match = re.search(r'主演[：:]\s*([^<]+)', html)
            actor = actor_match.group(1).strip() if actor_match else ""
            
            # 提取类型
            type_match = re.search(r'类型[：:]\s*([^<]+)', html)
            type_name = type_match.group(1).strip() if type_match else ""
            
            # 提取简介
            desc_match = re.search(r'简介[：:]\s*([^<]+)', html)
            if not desc_match:
                desc_match = re.search(r'<div[^>]*class="[^"]*desc[^"]*"[^>]*>([^<]+)</div>', html)
            desc = desc_match.group(1).strip() if desc_match else ""
            
            # 提取播放列表
            play_from = []
            play_url = []
            
            # 匹配播放源和链接
            # 常见模式: <div class="play-list"> 或 <ul id="playlist">
            play_pattern = r'<a[^>]*href="([^"]*)"[^>]*>([^<]+)</a>'
            play_matches = re.findall(play_pattern, html)
            
            # 过滤出播放链接
            play_items = []
            for link, name in play_matches:
                if 'vod' in link or 'play' in link or 'm3u8' in link:
                    if not link.startswith('http'):
                        if link.startswith('/'):
                            link = host + link
                        else:
                            link = host + '/' + link
                    play_items.append(f"{name}${link}")
            
            if play_items:
                play_from.append("播放源")
                play_url.append("#".join(play_items))
            else:
                # 尝试另一种模式
                play_pattern = r'<li[^>]*>\s*<a[^>]*href="([^"]*)"[^>]*>([^<]+)</a>'
                play_matches = re.findall(play_pattern, html)
                play_items = []
                for link, name in play_matches:
                    if 'vod' in link or 'play' in link or 'm3u8' in link:
                        if not link.startswith('http'):
                            if link.startswith('/'):
                                link = host + link
                            else:
                                link = host + '/' + link
                        play_items.append(f"{name}${link}")
                if play_items:
                    play_from.append("播放源")
                    play_url.append("#".join(play_items))
            
            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 ""
            }
            
            return {'list': [vod]}
            
        except Exception as e:
            print(f"获取详情失败: {e}")
            return {'list': []}

    # 播放页
    def playerContent(self, flag, id, vipFlags):
        try:
            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="([^"]*)"'
            ]
            
            for pattern in patterns:
                match = re.search(pattern, html)
                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
                        elif play_url.startswith('/'):
                            play_url = host + play_url
                    if 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)}"
        
        try:
            response = requests.get(url=search_url, headers=headers, timeout=timeout)
            response.encoding = "utf-8"
            html = response.text
            
            # 匹配搜索结果
            pattern = r'<a[^>]*href="([^"]*vod[^"]*\.html)"[^>]*>\s*<img[^>]*src="([^"]*)"[^>]*alt="([^"]*)"[^>]*>'
            matches = re.findall(pattern, html)
            
            if not matches:
                pattern = r'<div[^>]*class="[^"]*search-item[^"]*"[^>]*>\s*<a[^>]*href="([^"]*)"[^>]*>\s*<img[^>]*src="([^"]*)"[^>]*alt="([^"]*)"'
                matches = re.findall(pattern, html)
            
            for match in matches:
                link = match[0]
                pic = match[1]
                title = match[2]
                
                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 = link.split('/')[-1].replace('.html', '') if '.html' in link else link
                
                videos.append({
                    "vod_id": vod_id,
                    "vod_name": title.strip(),
                    "vod_pic": pic,
                    "vod_remarks": ""
                })
                
        except Exception as e:
            print(f"搜索失败: {e}")
            
        return {
            'list': videos,
            'page': page,
            'pagecount': 99,
            'limit': len(videos),
            'total': 9999
        }