"""
E2E登录功能调试测试
捕获浏览器控制台日志和网络请求
"""

from playwright.sync_api import sync_playwright
import time

def debug_login():
    """调试登录功能"""
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=True)
        context = browser.new_context()
        page = context.new_page()
        
        console_messages = []
        network_requests = []
        
        def handle_console(msg):
            console_messages.append({
                'type': msg.type,
                'text': msg.text,
                'location': msg.location
            })
            print(f"[Console {msg.type}] {msg.text}")
        
        def handle_request(request):
            if 'login' in request.url or 'auth' in request.url:
                network_requests.append({
                    'method': request.method,
                    'url': request.url,
                    'headers': dict(request.headers)
                })
                print(f"[Request {request.method}] {request.url}")
        
        def handle_response(response):
            if 'login' in response.url or 'auth' in response.url:
                print(f"[Response {response.status}] {response.url}")
                try:
                    body = response.text()
                    print(f"  Response Body: {body[:500]}")
                except:
                    pass
        
        page.on('console', handle_console)
        page.on('request', handle_request)
        page.on('response', handle_response)
        
        try:
            print("=" * 60)
            print("开始调试登录流程...")
            print("=" * 60)
            
            print("\n1. 访问登录页面...")
            page.goto('http://localhost:3002')
            page.wait_for_load_state('networkidle')
            time.sleep(2)
            
            print("\n2. 查找登录表单元素...")
            username_input = page.locator('input[type="text"], input[placeholder*="用户名"], input[placeholder*="账号"]').first
            password_input = page.locator('input[type="password"]').first
            login_button = page.locator('button:has-text("登录"), button:has-text("Login")').first
            
            print(f"   用户名输入框数量: {username_input.count()}")
            print(f"   密码输入框数量: {password_input.count()}")
            print(f"   登录按钮数量: {login_button.count()}")
            
            print("\n3. 填写登录表单...")
            username_input.fill('admin')
            password_input.fill('admin123')
            print("   已填写用户名和密码")
            
            print("\n4. 点击登录按钮...")
            login_button.click()
            
            print("\n5. 等待响应...")
            time.sleep(5)
            page.wait_for_load_state('networkidle')
            
            print("\n6. 检查结果...")
            current_url = page.url
            print(f"   当前URL: {current_url}")
            
            page.screenshot(path='/tmp/login_debug_full.png', full_page=True)
            print("   截图已保存到 /tmp/login_debug_full.png")
            
            print("\n7. 检查页面内容...")
            page_content = page.content()
            if '登录失败' in page_content or 'login failed' in page_content.lower():
                print("   发现登录失败提示")
            
            error_elements = page.locator('.error, .alert-danger, [class*="error"]').all()
            if error_elements:
                print(f"   发现 {len(error_elements)} 个错误提示元素")
                for elem in error_elements[:3]:
                    print(f"     - {elem.text_content()}")
            
            print("\n" + "=" * 60)
            print("调试信息汇总:")
            print("=" * 60)
            print(f"控制台消息数量: {len(console_messages)}")
            if console_messages:
                print("最近的控制台消息:")
                for msg in console_messages[-5:]:
                    print(f"  [{msg['type']}] {msg['text']}")
            
            print(f"\n网络请求数量: {len(network_requests)}")
            if network_requests:
                print("登录相关请求:")
                for req in network_requests:
                    print(f"  {req['method']} {req['url']}")
            
            print("=" * 60)
            
            return 'login' not in current_url.lower()
            
        except Exception as e:
            print(f"\n❌ 错误: {str(e)}")
            import traceback
            traceback.print_exc()
            page.screenshot(path='/tmp/login_error_debug.png', full_page=True)
            return False
        finally:
            browser.close()

if __name__ == "__main__":
    debug_login()
