import requests
import time
import os

class DoubanManager:
    def __init__(self, config):
        self.cookie = config.get('cookie', '')

    def test_connection(self):
        if not self.cookie:
            return False, "未配置 Cookie"
        # 简单测试，可以访问一个需要登录的页面
        headers = {'Cookie': self.cookie}
        try:
            res = requests.get('https://www.douban.com/mine/', headers=headers, timeout=10)
            if '登录' in res.text:
                 return False, "Cookie 已失效"
            return True, "Cookie 有效"
        except Exception as e:
            return False, f"网络请求失败: {e}"

    def scrape(self, media_path):
        """
        模拟耗时的刮削任务
        :param media_path: 要刮削的媒体文件夹路径
        """
        print(f"开始刮削: {media_path}")
        # 1. 提取剧名
        series_name = os.path.basename(media_path)
        print(f"提取剧名: {series_name}")
        
        # 2. 在豆瓣搜索 (模拟)
        time.sleep(5) 
        print("模拟豆瓣搜索中...")
        
        # 3. 获取信息并写入 NFO 和海报 (模拟)
        time.sleep(5)
        nfo_path = os.path.join(media_path, 'movie.nfo')
        poster_path = os.path.join(media_path, 'poster.jpg')
        
        with open(nfo_path, 'w', encoding='utf-8') as f:
            f.write(f"<movie><title>{series_name}</title><plot>这是一个模拟刮削的剧情简介。</plot></movie>")
        
        # 模拟下载海报
        try:
            # 使用一个占位图
            img_data = requests.get("https://via.placeholder.com/300x450.png?text=Poster").content
            with open(poster_path, 'wb') as handler:
                handler.write(img_data)
        except Exception as e:
            print(f"下载海报失败: {e}")

        print(f"刮削完成: {media_path}")

