#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
测试小红书 cookies 是否有效（使用 Clash 代理）
"""

import json
from pathlib import Path
from playwright.sync_api import sync_playwright

# 加载 cookies
CONFIG_FILE = Path(__file__).parent.parent / "beijing-exhibitions" / "config" / "xiaohongshu_cookies.json"

with open(CONFIG_FILE, "r", encoding="utf-8") as f:
    COOKIES_DICT = json.load(f)

# 转换为 Playwright 格式
COOKIES = [
    {"name": name, "value": value, "domain": ".xiaohongshu.com", "path": "/"}
    for name, value in COOKIES_DICT.items()
]

# Clash 代理配置
PROXY_SERVER = "http://127.0.0.1:7890"

print("=" * 70)
print("测试小红书 Cookies 有效性（使用 Clash 代理）", flush=True)
print("=" * 70)
print(f"\n已加载 {len(COOKIES)} 个 cookies", flush=True)
print(f"使用代理: {PROXY_SERVER}", flush=True)

with sync_playwright() as p:
    browser = p.chromium.launch(
        headless=True,
        executable_path='/usr/bin/google-chrome',
        args=['--disable-blink-features=AutomationControlled'],
        proxy={"server": PROXY_SERVER}
    )
    
    context = browser.new_context()
    context.add_cookies(COOKIES)
    page = context.new_page()
    
    # 访问小红书首页
    print("\n访问小红书首页...", flush=True)
    page.goto('https://www.xiaohongshu.com', wait_until='networkidle', timeout=60000)
    page.wait_for_timeout(5000)
    
    # 检查登录状态
    print("检查登录状态...", flush=True)
    
    # 方法 1：检查 URL 是否包含登录页
    current_url = page.url
    print(f"当前 URL: {current_url}", flush=True)
    
    # 方法 2：查找用户头像或登录按钮
    try:
        # 尝试查找用户头像（已登录标志）
        avatar = page.query_selector('img.avatar, .user-avatar, [class*="avatar"]')
        if avatar:
            print("✅ 找到用户头像 - COOKIES 有效（已登录）", flush=True)
        else:
            # 尝试查找登录按钮（未登录标志）
            login_btn = page.query_selector('text=登录, text=登录/注册, [class*="login"]')
            if login_btn:
                print("❌ 找到登录按钮 - COOKIES 已失效（未登录）", flush=True)
            else:
                print("⚠️ 无法判断登录状态，需要手动检查", flush=True)
    except Exception as e:
        print(f"⚠️ 检查失败：{e}", flush=True)
    
    # 方法 3：截图查看
    screenshot_path = Path(__file__).parent / "data" / "xhs_proxy_test_screenshot.png"
    page.screenshot(path=str(screenshot_path))
    print(f"\n截图已保存：{screenshot_path}", flush=True)
    print("请查看截图确认登录状态", flush=True)
    
    # 尝试搜索测试
    print("\n尝试搜索测试...", flush=True)
    page.goto('https://www.xiaohongshu.com/search_result?keyword=%E6%B3%95%E9%97%A8%E5%AF%BA&source=web_search_result_notes', 
             wait_until='networkidle', timeout=60000)
    page.wait_for_timeout(5000)
    
    # 检查是否有笔记
    notes = page.query_selector_all('section.note-item, div.note-card, article.note')
    print(f"搜索结果：找到 {len(notes)} 篇笔记", flush=True)
    
    if len(notes) > 0:
        print("✅ 搜索成功 - COOKIES 有效，代理工作正常", flush=True)
    else:
        print("⚠️ 没有找到笔记 - 可能被风控或需要重新登录", flush=True)
    
    # 搜索测试截图
    search_screenshot = Path(__file__).parent / "data" / "xhs_proxy_search_test.png"
    page.screenshot(path=str(search_screenshot))
    print(f"搜索测试截图：{search_screenshot}", flush=True)
    
    browser.close()

print("\n" + "=" * 70, flush=True)
print("测试完成", flush=True)
print("=" * 70, flush=True)
