#!/usr/bin/env python3
"""
调试Token丢失问题
"""

from playwright.sync_api import sync_playwright
import time

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    context = browser.new_context()
    page = context.new_page()
    
    # 登录
    print("1. 登录...")
    page.goto("http://localhost:3002/login")
    page.wait_for_load_state("networkidle")
    page.fill('input[placeholder="请输入用户名"]', 'admin')
    page.fill('input[placeholder="请输入密码"]', 'admin123')
    page.click('button:has-text("登录")')
    
    # 等待Token
    for i in range(10):
        time.sleep(1)
        token = page.evaluate("localStorage.getItem('token')")
        if token:
            print(f"  Token: {token[:50]}...")
            break
    
    # 检查localStorage
    print("\n2. 检查localStorage...")
    all_storage = page.evaluate("JSON.stringify(localStorage)")
    print(f"  localStorage: {all_storage[:200]}...")
    
    # 访问dashboard
    print("\n3. 访问dashboard...")
    page.goto("http://localhost:3002/dashboard")
    page.wait_for_load_state("networkidle")
    time.sleep(1)
    
    token_after = page.evaluate("localStorage.getItem('token')")
    print(f"  URL: {page.url}")
    print(f"  Token: {token_after[:50] if token_after else 'None'}...")
    
    # 访问用户管理
    print("\n4. 访问用户管理...")
    page.goto("http://localhost:3002/users")
    page.wait_for_load_state("networkidle")
    time.sleep(1)
    
    token_after2 = page.evaluate("localStorage.getItem('token')")
    print(f"  URL: {page.url}")
    print(f"  Token: {token_after2[:50] if token_after2 else 'None'}...")
    
    # 检查是否有错误
    print("\n5. 检查控制台错误...")
    console_messages = []
    page.on('console', lambda msg: console_messages.append(f"{msg.type}: {msg.text}"))
    
    # 刷新页面
    print("\n6. 刷新页面...")
    page.reload()
    page.wait_for_load_state("networkidle")
    time.sleep(1)
    
    token_after_reload = page.evaluate("localStorage.getItem('token')")
    print(f"  URL: {page.url}")
    print(f"  Token: {token_after_reload[:50] if token_after_reload else 'None'}...")
    
    # 打印控制台消息
    print("\n控制台消息:")
    for msg in console_messages[-10:]:
        print(f"  {msg}")
    
    browser.close()
