"""
测试 JWT Token 解析
"""
from jose import JWTError, jwt
from core.security import SECRET_KEY, ALGORITHM
from datetime import datetime

# 你提供的 token
token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhZG1pbiIsImV4cCI6MTc3NTk4MjQ4MX0.xDiv21_74J4485K_6F8Dt5xdMz2dWA0Y6hzjEH3gk0A"

print("="*60)
print("测试 JWT Token 解析")
print("="*60)

print(f"\nToken: {token[:50]}...")
print(f"\nSECRET_KEY: {SECRET_KEY}")
print(f"ALGORITHM: {ALGORITHM}")

try:
    # 解码 token
    payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
    print("\n✓ Token 解码成功!")
    print(f"Payload: {payload}")
    
    username = payload.get("sub")
    exp = payload.get("exp")
    
    print(f"\n用户名: {username}")
    print(f"过期时间戳: {exp}")
    
    # 检查是否过期
    if exp:
        exp_datetime = datetime.fromtimestamp(exp)
        now = datetime.now()
        print(f"过期时间: {exp_datetime}")
        print(f"当前时间: {now}")
        
        if now > exp_datetime:
            print("\n✗ Token 已过期!")
        else:
            print("\n✓ Token 未过期")
            
except JWTError as e:
    print(f"\n✗ Token 解码失败: {e}")
except Exception as e:
    print(f"\n✗ 错误: {e}")

print("\n" + "="*60)

# 测试数据库查询
print("\n测试数据库查询...")
import sqlite3

conn = sqlite3.connect('qa_system.db')
cursor = conn.cursor()

cursor.execute("SELECT id, username, email, is_active, is_admin FROM users WHERE username = 'admin'")
user = cursor.fetchone()

if user:
    print(f"✓ 找到用户:")
    print(f"  ID: {user[0]}")
    print(f"  用户名: {user[1]}")
    print(f"  邮箱: {user[2]}")
    print(f"  激活状态: {user[3]}")
    print(f"  管理员: {user[4]}")
else:
    print("✗ 未找到用户")

conn.close()
