#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
测试小红书 cookies 是否有效（强制使用代理 + 随机延迟）
"""

import json
import time
import random
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 有效性（强制代理 + 随机延迟）", flush=True)
print("=" * 70)
print(f"\n已加载 {len(COOKIES)} 个 cookies", flush=True)
print(f"使用代理: {PROXY_SERVER}", flush=True)

# 随机延迟函数
def random_delay(min_sec=3, max_sec=8):
    """随机延迟，模拟真人行为"""
    delay = random.uniform(min_sec, max_sec)
    print(f"  等待 {delay:.1f} 秒...", flush=True)
    time.sleep(delay)

with sync_playwright() as p:
    browser = p.chromium.launch(
        headless=True,
        executable_path='/usr/bin/google-chrome',
        args=[
            '--disable-blink-features=AutomationControlled',
            '--disable-dev-shm-usage',
            '--no-sandbox',
            '--disable-setuid-sandbox',
            '--disable-web-security',
            '--disable-features=IsolateOrigins,site-per-process'
        ]
    )
    
    context = browser.new_context(
        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",
        viewport={"width": 1920, "height": 1080},
        locale='zh-CN',
        timezone_id='Asia/Shanghai'
    )
    
    # 注入脚本隐藏自动化特征
    page = context.new_page()
    page.add_init_script("""
        Object.defineProperty(navigator, 'webdriver', {
            get: () => undefined,
        });
        Object.defineProperty(navigator, 'plugins', {
            get: () => [1, 2, 3, 4, 5],
        });
        Object.defineProperty(navigator, 'languages', {
            get: () => ['zh-CN', 'zh'],
        });
    """)
    
    context.add_cookies(COOKIES)
    
    # 访问小红书首页
    print("\n[1/6] 访问小红书首页...", flush=True)
    page.goto('https://www.xiaohongshu.com', wait_until='networkidle', timeout=90000)
    random_delay(5, 10)
    
    # 检查登录状态
    print("[2/6] 检查登录状态...", flush=True)
    current_url = page.url
    print(f"  当前 URL: {current_url}", flush=True)
    
    # 检查是否被风控
    if 'IP at risk' in current_url or 'error' in current_url:
        print("❌ 检测到风控或错误页面", flush=True)
        screenshot_path = Path(__file__).parent / "data" / "xhs_proxy_error.png"
        page.screenshot(path=str(screenshot_path))
        print(f"  错误截图：{screenshot_path}", flush=True)
        browser.close()
        exit(1)
    
    # 查找用户头像或登录按钮
    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)
    
    # 截图查看
    print("[3/6] 截图查看...", flush=True)
    screenshot_path = Path(__file__).parent / "data" / "xhs_proxy_test.png"
    page.screenshot(path=str(screenshot_path))
    print(f"  截图已保存：{screenshot_path}", flush=True)
    
    # 随机延迟
    random_delay(5, 10)
    
    # 尝试搜索测试
    print("[4/6] 尝试搜索测试...", flush=True)
    print("  搜索关键词：法 门 寺", flush=True)
    
    # 使用 URL 编码的搜索关键词
    search_url = 'https://www.xiaohongshu.com/search_result?keyword=%E6%B3%95%E9%97%A8%E5%AF%BA&source=web_search_result_notes'
    page.goto(search_url, wait_until='networkidle', timeout=90000)
    random_delay(8, 15)
    
    # 检查是否有笔记
    print("[5/6] 检查搜索结果...", flush=True)
    
    # 尝试多种选择器
    notes_selectors = [
        'section.note-item',
        'div.note-card',
        'article.note',
        'div[data-v-note-item]',
        'a[href*="/explore/"]'
    ]
    
    notes = []
    for selector in notes_selectors:
        try:
            found = page.query_selector_all(selector)
            if found:
                notes = found
                print(f"  使用选择器 '{selector}' 找到 {len(notes)} 篇笔记", flush=True)
                break
        except:
            continue
    
    if len(notes) > 0:
        print(f"✅ 搜索成功 - 找到 {len(notes)} 篇笔记", flush=True)
        print("✅ 代理 + COOKIES 工作正常！", flush=True)
    else:
        print("⚠️ 没有找到笔记 - 可能被风控或页面结构变化", flush=True)
    
    # 搜索测试截图
    print("[6/6] 保存搜索截图...", flush=True)
    search_screenshot = Path(__file__).parent / "data" / "xhs_proxy_search.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)
