"""
@header({
  searchable: 1,
  filterable: 1,
  quickSearch: 1,
  title: '旺旺影视',
  lang: 'hipy',
})
"""
# -*- coding: utf-8 -*-
import re, json
import requests
from urllib.parse import quote
from base.spider import Spider as BaseSpider


class Spider(BaseSpider):
    def init(self, extend=""):
        self.host = "https://vip.wwgz.cn:5200"
        self.headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
            "Accept-Language": "zh-CN,zh;q=0.9",
            "Referer": self.host + "/",
        }

    def getName(self):
        return '旺旺影视'

    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):
        html = self._fetch('/')
        return {"list": self._parse_video_list(html)}

    def categoryContent(self, tid, pg, filter, extend):
        # 旺旺影视URL格式: /vod-type-id-1-pg-1.html
        url = f'/vod-type-id-{tid}-pg-{pg}.html'
        html = self._fetch(url)
        items = self._parse_video_list(html)
        page = int(pg)
        page_count = page if len(items) < 20 else page + 2
        return {"list": items, "page": page, "pagecount": page_count, "limit": 20, "total": 99999}

    def detailContent(self, ids):
        result = {"list": []}
        vid = ids[0]
        try:
            # 尝试多种URL格式
            urls = [
                f'/vod-detail-id-{vid}.html',
                f'/vod/{vid}.html',
                f'/detail/{vid}.html',
            ]
            html = ''
            for url in urls:
                html = self._fetch(url)
                if html:
                    break
            
            if not html:
                return result

            # 片名
            vod_name = ''
            m_name = re.search(r'<h1[^>]*>([^<]+)</h1>', html)
            if not m_name:
                m_name = re.search(r'<title>([^<]+)</title>', html)
            if m_name:
                vod_name = m_name.group(1).strip()
                # 去除后缀
                vod_name = vod_name.replace(' - 旺旺影视', '').replace(' - 旺旺', '')

            # 图片
            vod_pic = ''
            m_pic = re.search(r'<img[^>]*src="([^"]*)"[^>]*class="[^"]*pic[^"]*"', html)
            if not m_pic:
                m_pic = re.search(r'<img[^>]*src="([^"]*)"[^>]*alt="[^"]*"', html)
            if m_pic:
                vod_pic = m_pic.group(1)
                if vod_pic and not vod_pic.startswith('http'):
                    vod_pic = self.host + vod_pic if vod_pic.startswith('/') else self.host + '/' + vod_pic

            # 演员
            vod_actor = ''
            m_actor = re.search(r'主演[：:]\s*([^<\n]+)', html)
            if not m_actor:
                m_actor = re.search(r'演员[：:]\s*([^<\n]+)', html)
            if m_actor:
                vod_actor = m_actor.group(1).strip()

            # 类型
            type_name = ''
            m_type = re.search(r'类型[：:]\s*([^<\n]+)', html)
            if m_type:
                type_name = m_type.group(1).strip()

            # 简介
            vod_content = ''
            m_desc = re.search(r'简介[：:]\s*([^<\n]+)', html)
            if not m_desc:
                m_desc = re.search(r'<meta\s+name="description"\s+content="([^"]+)"', html)
            if m_desc:
                vod_content = m_desc.group(1).strip()

            # 播放源
            play_from = []
            play_url = []

            # 提取播放列表 - 苹果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:
                # 格式: <a href="/play/xxx.html">第1集</a>
                links = re.findall(r'<a[^>]*href="(/play/[^"]+\.html)"[^>]*>([^<]+)</a>', html)
            
            if not links:
                # 格式: <a href="/vod/xxx.html">第1集</a>
                links = re.findall(r'<a[^>]*href="(/vod/[^"]+\.html)"[^>]*>([^<]+)</a>', html)
            
            if links:
                ep_list = []
                for link, ep_name in links:
                    ep_name = ep_name.strip()
                    if not ep_name or len(ep_name) < 1:
                        continue
                    if '搜索' in ep_name or '首页' in ep_name:
                        continue
                    if not link.startswith('http'):
                        link = self.host + link if link.startswith('/') else self.host + '/' + link
                    ep_list.append(f'{ep_name}${link}')
                
                if ep_list:
                    play_from.append('播放源')
                    play_url.append('#'.join(ep_list))

            # 如果没有播放链接，找iframe
            if not play_from:
                iframe = re.search(r'<iframe[^>]*src="([^"]*)"', html)
                if iframe:
                    iframe_url = iframe.group(1)
                    if not iframe_url.startswith('http'):
                        iframe_url = self.host + iframe_url if iframe_url.startswith('/') else self.host + '/' + iframe_url
                    play_from.append('播放源')
                    play_url.append(f'播放${iframe_url}')

            vod = {
                "vod_id": vid,
                "vod_name": vod_name,
                "vod_pic": vod_pic,
                "vod_actor": vod_actor,
                "type_name": type_name,
                "vod_remarks": '',
                "vod_content": vod_content,
                "vod_play_from": "$$$".join(play_from),
                "vod_play_url": "$$$".join(play_url),
            }
            result["list"].append(vod)
        except Exception as e:
            print(f'detailContent error: {e}')
        return result

    def searchContent(self, key, quick, pg="1"):
        videos = []
        try:
            decoded = quote(key)
        except:
            decoded = key
        # 苹果CMS搜索格式
        url = f'/vod-search-pg-{pg}-wd-{decoded}.html'
        html = self._fetch(url)
        if html:
            # 匹配搜索结果
            pattern = r'<a[^>]*href="(/vod-detail-id-([^"]+)\.html)"[^>]*title="([^"]*)"'
            matches = re.findall(pattern, html)
            
            # 如果没有匹配，尝试另一种格式
            if not matches:
                pattern = r'<a[^>]*href="(/vod/[^"]+\.html)"[^>]*>([^<]+)</a>'
                raw = re.findall(pattern, html)
                for link, name in raw:
                    if 'detail' in link or 'play' in link:
                        vid = link.split('/')[-1].replace('.html', '')
                        matches.append((link, vid, name.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": ""
                })
        
        return {"list": videos, "page": int(pg), "pagecount": 1, "limit": 36, "total": len(videos)}

    def playerContent(self, flag, id, vipFlags):
        # 如果id是完整URL，直接使用
        if id.startswith('http'):
            url = id
        else:
            url = self.host + id if id.startswith('/') else self.host + '/' + id
        
        try:
            html = self._fetch(url)
            if html:
                # 尝试从页面提取视频地址
                patterns = [
                    r'var\s+player_aaaa\s*=\s*({.*?});',
                    r'var\s+player\s*=\s*({.*?});',
                    r'"url":"([^"]*)"',
                    r'<video[^>]*src="([^"]*)"',
                    r'<iframe[^>]*src="([^"]*)"',
                    r'src="([^"]*\.m3u8[^"]*)"',
                ]
                for pattern in patterns:
                    m = re.search(pattern, html, re.S)
                    if m:
                        content = m.group(1)
                        if content.startswith('{'):
                            try:
                                pd = json.loads(content)
                                play_url = pd.get('url', '')
                                if play_url:
                                    return {"parse": 0, "playUrl": '', "url": play_url, "header": self.headers}
                            except:
                                pass
                        else:
                            play_url = content
                            if play_url and not play_url.startswith('http'):
                                if play_url.startswith('//'):
                                    play_url = 'https:' + play_url
                                elif play_url.startswith('/'):
                                    play_url = self.host + play_url
                            if play_url and ('.m3u8' in play_url or '.mp4' in play_url or 'http' in play_url):
                                return {"parse": 0, "playUrl": '', "url": play_url, "header": self.headers}
        except Exception as e:
            print(f'playerContent error: {e}')
        
        return {"parse": 1, "url": url}

    def localProxy(self, param=''):
        return {}

    def isVideoFormat(self, url):
        return False

    def manualVideoCheck(self):
        return False

    def _fetch(self, url):
        try:
            if not url.startswith('http'):
                url = self.host + url
            rsp = self.fetch(url, headers=self.headers)
            return rsp.text if rsp else ''
        except:
            return ''

    def _parse_video_list(self, html):
        videos, seen = [], set()
        
        # 匹配视频列表 - 苹果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="([^"]*)"'
            raw = re.findall(pattern, html, re.DOTALL)
            for link, name in raw:
                vid = link.split('/')[-1].replace('.html', '')
                matches.append((link, vid, name))
        
        if not matches:
            # 格式3: 从首页提取
            pattern = r'href="(/mv/(\d+)\.html)"[^>]*title="([^"]*)"'
            matches = re.findall(pattern, html)
        
        for link, vid, name in matches:
            if vid in seen:
                continue
            seen.add(vid)
            
            name = name.strip()
            if len(name) < 2:
                continue
            
            # 提取封面
            pic = ''
            pic_pattern = r'href="' + re.escape(link) + r'"[^>]*>.*?data-original="([^"]*)"'
            pic_match = re.search(pic_pattern, html, re.DOTALL)
            if pic_match:
                pic = pic_match.group(1)
            if not pic:
                pic_pattern = r'href="' + re.escape(link) + r'"[^>]*>.*?src="([^"]*)"'
                pic_match = re.search(pic_pattern, html, re.DOTALL)
                if pic_match:
                    pic = pic_match.group(1)
            
            if pic and not pic.startswith('http'):
                pic = self.host + pic if pic.startswith('/') else self.host + '/' + pic
            
            # 提取备注
            remarks = ''
            remarks_pattern = r'href="' + re.escape(link) + r'"[^>]*>.*?</a>\s*<span[^>]*>([^<]+)</span>'
            remarks_match = re.search(remarks_pattern, html, re.DOTALL)
            if remarks_match:
                remarks = remarks_match.group(1).strip()
            
            videos.append({
                "vod_id": vid,
                "vod_name": name,
                "vod_pic": pic,
                "vod_remarks": remarks,
            })
        
        return videos