#!/usr/bin/env python3
"""
详细登录测试 - 查看请求和响应详情
"""
from playwright.sync_api import sync_playwright
import time

def test_login_detailed():
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=True)
        context = browser.new_context()
        page = context.new_page()
        
        requests_log = []
        responses_log = []
        
        def handle_request(request):
            if '/api/' in request.url:
                headers = dict(request.headers)
                requests_log.append({
                    'url': request.url,
                    'method': request.method,
                    'headers': headers
                })
                print(f"\n请求: {request.method} {request.url}")
                if 'authorization' in headers:
                    print(f"  Authorization: {headers['authorization'][:50]}...")
                if 'x-signature' in headers:
                    print(f"  X-Signature: {headers['x-signature']}")
                if 'x-timestamp' in headers:
                    print(f"  X-Timestamp: {headers['x-timestamp']}")
                if 'x-nonce' in headers:
                    print(f"  X-Nonce: {headers['x-nonce']}")
        
        def handle_response(response):
            if '/api/' in response.url:
                responses_log.append({
                    'url': response.url,
                    'status': response.status,
                    'body': response.text() if response.status != 200 else None
                })
                print(f"响应: {response.status} {response.url}")
                if response.status != 200:
                    try:
                        body = response.text()
                        print(f"  错误: {body[:200]}")
                    except:
                        pass
        
        page.on("request", handle_request)
        page.on("response", handle_response)
        
        try:
            print("访问登录页...")
            page.goto("http://localhost:3002/login", timeout=10000)
            page.wait_for_load_state("networkidle", timeout=10000)
            
            print("\n填写登录表单...")
            page.fill('input[type="text"]', 'admin')
            page.fill('input[type="password"]', 'admin123')
            
            print("\n点击登录按钮...")
            page.click('button[type="submit"]')
            
            time.sleep(5)
            
            current_url = page.url
            print(f"\n当前URL: {current_url}")
            
            token = page.evaluate("localStorage.getItem('token')")
            print(f"Token: {token if token else '不存在'}")
            
            if token:
                print(f"Token内容: {token[:100]}...")
            
        except Exception as e:
            print(f"\n错误: {e}")
        finally:
            browser.close()

if __name__ == "__main__":
    test_login_detailed()
