#!/usr/bin/env python3
"""
调试用户查询
"""
import asyncio
import sys
import os

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

# 加载本地配置
try:
    import local_config
    print("✅ 本地配置已加载")
except ImportError:
    print("⚠️  未找到local_config.py")

async def debug_user():
    """调试用户查询"""
    try:
        from app.core.database import AsyncSessionLocal
        from app.services.user_service import UserService
        from app.core.security import verify_password
        from sqlalchemy import text
        
        print("🔧 调试用户查询...")
        
        async with AsyncSessionLocal() as session:
            # 直接查询用户
            result = await session.execute(
                text("SELECT id, username, email, password_hash, role, is_active FROM users WHERE username = :username"),
                {"username": "test_dify"}
            )
            user_data = result.fetchone()
            
            if user_data:
                print(f"\n✅ 找到用户:")
                print(f"   ID: {user_data[0]}")
                print(f"   用户名: {user_data[1]}")
                print(f"   邮箱: {user_data[2]}")
                print(f"   密码哈希: {user_data[3]}")
                print(f"   角色: {user_data[4]}")
                print(f"   激活状态: {user_data[5]}")
                
                # 验证密码
                password_ok = verify_password("password123", user_data[3])
                print(f"\n密码验证结果: {password_ok}")
            else:
                print("\n❌ 未找到用户 test_dify")
            
            # 使用UserService查询
            user_service = UserService(session)
            user = await user_service.get_by_username("test_dify")
            if user:
                print(f"\n✅ UserService找到用户: {user.username}")
                print(f"   Model字段: hashed_password = {user.hashed_password}")
            else:
                print("\n❌ UserService未找到用户")
            
            # 测试认证
            auth_user = await user_service.authenticate(username="test_dify", password="password123")
            if auth_user:
                print(f"\n✅ 认证成功: {auth_user.username}")
            else:
                print("\n❌ 认证失败")
        
        print("\n✅ 调试完成！")
        
    except Exception as e:
        print(f"❌ 调试失败: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    asyncio.run(debug_user())
