"""
测试使用现有JWT令牌进行FastAPI认证
"""

import sys
import os
import asyncio
import json
import redis
from fastapi import FastAPI, Depends, Request
from fastapi.security import HTTPBearer
from fastapi.testclient import TestClient
from mwauth.fastapi_auth import FastApiKongAuth, FastApiSessionMiddleware

# 添加项目路径
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

# 创建应用实例
app = FastAPI(
    title="JWT Authentication Test",
    description="测试现有JWT令牌的FastAPI认证",
    version="1.0.0"
)

# 定义 JWT 安全方案
security = HTTPBearer()

# 您提供的JWT令牌
EXISTING_JWT = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3NTQyOTIxNTQsImlzcyI6ImZjT09NWlJXZlR1YmczM3ZiZk9DUWlFNUtpdW1MTFMxIn0.zb04GZOrrDLtibnK3vQZWbbUUQj4WFO6rrWkYd6L9_Q"

# Redis连接配置 - 使用您提供的地址
redis_client = redis.Redis(host='192.168.101.78', port=30033, db=0, decode_responses=False)

# 初始化认证实例
auth = FastApiKongAuth(redis_client=redis_client)

# 添加会话中间件
app.add_middleware(FastApiSessionMiddleware, redis_client=redis_client)

@app.get("/")
async def root(request: Request, current_user = Depends(auth.get_current_user())):
    """
    需要认证的根路由
    """
    return {
        "message": "Hello World",
        "user": {
            "uid": current_user.uid,
            "uname": current_user.uname,
            "systemuser": current_user.systemuser,
            "manageuser": current_user.manageuser,
            "companyid": current_user.companyid,
            "type": current_user.type,
            "phone": current_user.phone
        }
    }

@app.get("/protected")
async def protected_route(
    request: Request,
    current_user = Depends(auth.get_current_user())
):
    """
    受保护的路由，需要认证
    """
    return {
        "message": "This is a protected route",
        "user_info": {
            "uid": current_user.uid,
            "uname": current_user.uname,
            "type": current_user.type
        }
    }

@app.get("/test-with-jwt")
async def test_with_jwt(request: Request):
    """
    直接使用auth的valid_login方法测试JWT
    """
    try:
        current_user = await auth.valid_login(request)
        return {
            "message": "JWT Authentication successful",
            "user": {
                "uid": current_user.uid,
                "uname": current_user.uname,
                "systemuser": current_user.systemuser,
                "manageuser": current_user.manageuser,
                "companyid": current_user.companyid,
                "type": current_user.type,
                "phone": current_user.phone
            },
            "headers": dict(request.headers),
            "session_data": getattr(request.state, 'session', {})
        }
    except Exception as e:
        return {
            "error": str(e),
            "headers": dict(request.headers),
            "session_data": getattr(request.state, 'session', {})
        }

def test_with_existing_jwt():
    """
    使用现有JWT令牌测试认证功能
    """
    print("🧪 开始测试现有JWT令牌认证...")
    print(f"🔑 使用JWT令牌: {EXISTING_JWT[:20]}...{EXISTING_JWT[-10:]}")
    
    # 使用TestClient进行测试
    client = TestClient(app)
    
    # 准备带有JWT的请求头
    headers = {
        "Authorization": f"Bearer {EXISTING_JWT}",
        "X-Consumer-Username": "13712363409",  # 根据提供的用户数据
        "X-Consumer-Custom-Id": "349643"       # 根据提供的用户数据
    }
    
    print("\n📋 测试步骤:")
    print("1. 测试根路由 (/)")
    response = client.get("/", headers=headers)
    print(f"   响应状态: {response.status_code}")
    if response.status_code == 200:
        print(f"   响应数据: {response.json()}")
    else:
        print(f"   错误信息: {response.text}")
    
    print("\n2. 测试保护路由 (/protected)")
    response = client.get("/protected", headers=headers)
    print(f"   响应状态: {response.status_code}")
    if response.status_code == 200:
        print(f"   响应数据: {response.json()}")
    else:
        print(f"   错误信息: {response.text}")
    
    print("\n3. 测试JWT验证路由 (/test-with-jwt)")
    response = client.get("/test-with-jwt", headers=headers)
    print(f"   响应状态: {response.status_code}")
    if response.status_code == 200:
        print(f"   响应数据: {response.json()}")
    else:
        print(f"   错误信息: {response.text}")

def manual_verify_jwt_in_redis():
    """
    手动验证Redis中是否存在JWT对应的会话数据
    """
    print("\n🔍 手动验证Redis中的JWT会话数据...")
    
    try:
        # 尝试获取JWT作为session ID的数据
        session_key = f"session:{EXISTING_JWT}"
        session_data = redis_client.get(session_key)
        
        if session_data:
            print(f"✅ 在Redis中找到会话数据，键: {session_key}")
            print(f"   会话数据: {session_data}")
            # 解析JSON数据
            try:
                parsed_data = json.loads(session_data)
                print(f"   解析后的数据: {parsed_data}")
            except json.JSONDecodeError:
                print("   ❌ 无法解析JSON数据")
        else:
            print(f"❌ 在Redis中未找到键为 '{session_key}' 的会话数据")
        
        # 尝试获取预期的会话数据（根据您提供的用户信息）
        expected_session_data = {
            "uid": "349643",
            "uname": "13712363409",
            "systemuser": False,
            "manageuser": False,
            "manageuserid": "",
            "companyid": "",
            "type": "member",
            "locale": "zh-CN",
            "email": "cxhjet@qq.com",
            "phone": "13712363409",
            "timezone": None
        }
        
        print(f"\n📝 预期的会话数据: {expected_session_data}")
        
        # 检查是否有匹配的会话键
        print("\n🔍 搜索Redis中可能的会话键...")
        pattern = "session:*"
        keys = []
        for key in redis_client.scan_iter(match=pattern):
            keys.append(key.decode('utf-8'))
        
        print(f"   找到 {len(keys)} 个会话键")
        for key in keys[:10]:  # 只显示前10个
            data = redis_client.get(key)
            print(f"   键: {key}, 数据: {data}")
        
        if len(keys) > 10:
            print(f"   ... 还有 {len(keys) - 10} 个键未显示")
            
    except Exception as e:
        print(f"❌ 验证Redis数据时发生错误: {e}")

if __name__ == "__main__":
    print("🚀 FastAPI JWT 认证测试工具")
    print("=" * 50)
    
    # 执行手动Redis验证
    manual_verify_jwt_in_redis()
    
    # 执行API测试
    test_with_existing_jwt()
    
    print("\n" + "=" * 50)
    print("✅ 测试完成")