#!/usr/bin/env python3
"""
手动测试登录功能的脚本
"""

import requests
import json
from datetime import datetime

def test_login_page():
    """测试登录页面是否可访问"""
    print("=" * 50)
    print("登录功能测试报告")
    print("=" * 50)
    print(f"测试时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print()
    
    # 测试前端页面访问
    frontend_url = "http://localhost:3001/login?redirect=/trainee/exam"
    print(f"1. 测试前端页面访问: {frontend_url}")
    
    try:
        response = requests.get(frontend_url, timeout=5)
        print(f"   状态码: {response.status_code}")
        print(f"   响应头: {dict(response.headers)}")
        
        if response.status_code == 200:
            print("   ✅ 前端页面可以正常访问")
            content_length = len(response.text)
            print(f"   页面内容长度: {content_length} 字符")
            
            # 检查是否包含登录相关元素
            content = response.text.lower()
            login_indicators = ['login', '登录', 'username', 'password', 'form']
            found_indicators = [indicator for indicator in login_indicators if indicator in content]
            
            if found_indicators:
                print(f"   找到登录相关元素: {found_indicators}")
            else:
                print("   ⚠️  未找到明显的登录相关元素")
        else:
            print(f"   ❌ 前端页面访问失败，状态码: {response.status_code}")
            
    except requests.exceptions.ConnectionError:
        print("   ❌ 无法连接到前端服务 (localhost:3001)")
    except requests.exceptions.Timeout:
        print("   ❌ 前端服务响应超时")
    except Exception as e:
        print(f"   ❌ 访问前端页面时出错: {e}")
    
    print()
    
    # 测试后端API
    backend_base = "http://localhost:8000"
    print(f"2. 测试后端API服务: {backend_base}")
    
    try:
        # 测试后端健康检查
        health_url = f"{backend_base}/health"
        response = requests.get(health_url, timeout=5)
        print(f"   健康检查状态码: {response.status_code}")
        
        # 测试登录API端点
        login_api_url = f"{backend_base}/api/v1/auth/login"
        response = requests.options(login_api_url, timeout=5)
        print(f"   登录API OPTIONS请求状态码: {response.status_code}")
        
        if response.status_code in [200, 405]:  # 405表示方法不允许但端点存在
            print("   ✅ 后端API服务正常运行")
        else:
            print(f"   ⚠️  后端API可能有问题，状态码: {response.status_code}")
            
    except requests.exceptions.ConnectionError:
        print("   ❌ 无法连接到后端服务 (localhost:8000)")
    except requests.exceptions.Timeout:
        print("   ❌ 后端服务响应超时")
    except Exception as e:
        print(f"   ❌ 访问后端API时出错: {e}")
    
    print()
    
    # 测试数据库连接（通过后端API）
    print("3. 测试数据库连接状态")
    try:
        db_status_url = f"{backend_base}/api/v1/system/status"
        response = requests.get(db_status_url, timeout=5)
        
        if response.status_code == 200:
            try:
                data = response.json()
                print("   ✅ 系统状态API响应正常")
                print(f"   响应数据: {json.dumps(data, indent=2, ensure_ascii=False)}")
            except json.JSONDecodeError:
                print("   ⚠️  系统状态API响应不是有效JSON")
        else:
            print(f"   ⚠️  系统状态API状态码: {response.status_code}")
            
    except requests.exceptions.ConnectionError:
        print("   ❌ 无法获取系统状态")
    except Exception as e:
        print(f"   ❌ 获取系统状态时出错: {e}")
    
    print()
    print("=" * 50)
    print("测试建议:")
    print("1. 确保前后端服务都在运行")
    print("2. 检查端口配置是否正确")
    print("3. 验证数据库连接是否正常")
    print("4. 使用浏览器手动访问登录页面进行测试")
    print("=" * 50)

if __name__ == "__main__":
    test_login_page()
