#!/usr/bin/env python3
"""
检查API请求和响应
"""

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()
    
    # 监听网络请求
    api_requests = []
    
    def handle_request(request):
        if '/api/' in request.url:
            headers = request.headers
            api_requests.append({
                'url': request.url,
                'method': request.method,
                'has_signature': 'X-Signature' in headers,
                'has_timestamp': 'X-Timestamp' in headers,
                'has_token': 'Authorization' in headers
            })
            print(f"\n请求: {request.method} {request.url}")
            print(f"  签名头: {headers.get('X-Signature', 'None')[:30]}...")
            print(f"  时间戳: {headers.get('X-Timestamp', 'None')}")
            print(f"  Token: {headers.get('Authorization', 'None')[:30]}...")
    
    def handle_response(response):
        if '/api/' in response.url:
            print(f"\n响应: {response.status} {response.url}")
            if response.status == 401:
                print(f"  ⚠️ 401错误！")
    
    page.on('request', handle_request)
    page.on('response', handle_response)
    
    # 登录
    print("登录...")
    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:
            break
    
    print(f"\nToken: {token[:50]}...")
    
    # 访问dashboard
    print("\n\n访问Dashboard...")
    page.goto("http://localhost:3002/dashboard")
    page.wait_for_load_state("networkidle")
    time.sleep(2)
    
    # 访问用户管理
    print("\n\n访问用户管理...")
    page.goto("http://localhost:3002/users")
    page.wait_for_load_state("networkidle")
    time.sleep(2)
    
    print(f"\n最终URL: {page.url}")
    
    browser.close()
