



import json
import time
import requests
from pathlib import Path

# ================= 配置区域 =================
COOKIE_FILE = Path("./cookies.json")
TARGET_SEASON_ID = 7196643  # 要检查的合集 ID
# ===========================================

class BiliCollectionChecker:
    def __init__(self):
        self.load_cookies()
        self.session = requests.Session()
        self.session.headers.update({
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
            "Referer": "https://member.bilibili.com/platform/upload-manager/distribution"
        })

    def load_cookies(self):
        if not COOKIE_FILE.exists():
            raise FileNotFoundError(f"找不到 Cookies 文件: {COOKIE_FILE}")
        with open(COOKIE_FILE, "r", encoding="utf-8") as f:
            data = json.load(f)
        self.cookies = {c["name"]: c["value"] for c in data.get("cookie_info", {}).get("cookies", [])} if "cookie_info" in data else data

    def get_video_pubdate(self, bvid):
        """反查视频详细发布时间"""
        url = "https://api.bilibili.com/x/web-interface/view"
        try:
            res = self.session.get(url, params={"bvid": bvid}).json()
            if res["code"] == 0:
                return res["data"]["pubdate"]
        except: pass
        return 0

    def check_top_10(self):
        print(f"📡 正在拉取合集 {TARGET_SEASON_ID} 当前的实时排位...")
        self.session.cookies.update(self.cookies)
        
        try:
            # 1. 先定位小节 ID
            list_res = self.session.get("https://member.bilibili.com/x2/creative/web/seasons", params={"pn": 1, "ps": 50}).json()
            section_id = None
            for s in list_res.get("data", {}).get("seasons", []):
                if s.get("season", {}).get("id") == TARGET_SEASON_ID:
                    section_id = s.get("sections", {}).get("sections", [])[0]['id']
                    break
            
            if not section_id:
                print("❌ 未找到合集信息")
                return

            # 2. 获取该小节当前的前 10 个视频
            detail_url = "https://member.bilibili.com/x2/creative/web/season/section"
            res_detail = self.session.get(detail_url, params={"id": section_id}).json()
            
            if res_detail.get("code") == 0:
                episodes = res_detail.get("data", {}).get("episodes", [])
                top_10 = episodes[:10] # 截取前 10 个
                
                print("\n" + "="*60)
                print(f"{'排位':<4} | {'发布时间':<20} | {'BVID':<12} | {'视频标题'}")
                print("-" * 60)
                
                for idx, ep in enumerate(top_10):
                    bvid = ep['bvid']
                    # 为了验证排序字段，这里再次请求真实发布时间
                    pubtime = self.get_video_pubdate(bvid)
                    time_str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(pubtime)) if pubtime > 0 else "未知"
                    
                    print(f"#{idx+1:<3} | {time_str:<20} | {bvid:<12} | {ep['title']}")
                
                print("="*60)
                print(f"\n💡 如果看到的发布时间是从 2025 年开始递增的，说明是【正序】。")
                print(f"💡 如果是从 2026 年开始递减的，说明是【逆序】。")
            else:
                print(f"❌ 获取详情失败: {res_detail.get('message')}")

        except Exception as e:
            print(f"❌ 运行异常: {e}")

if __name__ == "__main__":
    checker = BiliCollectionChecker()
    checker.check_top_10()