#!/usr/bin/env python
"""
测试User schema的序列化
"""

import asyncio
import sys
from pathlib import Path

# 添加项目根目录到 Python 路径
project_root = Path(__file__).parent
sys.path.append(str(project_root))

from app.schemas.user import User as UserSchema
from app.models.user import User
from app.core.deps import get_db
from app.services.user_service import UserService

async def test_schema():
    """测试schema序列化"""
    
    # 获取数据库会话
    async for db in get_db():
        try:
            # 1. 获取用户
            user_service = UserService(db)
            user = await user_service.get_by_username("superadmin")
            
            if not user:
                print("用户不存在")
                return
                
            # 2. 打印模型数据
            print("=== 模型数据 ===")
            print(f"ID: {user.id}")
            print(f"用户名: {user.username}")
            print(f"邮箱: {user.email}")
            print(f"手机号: {user.phone}")
            print(f"学校: {user.school}")
            print(f"专业: {user.major}")
            print(f"性别: {user.gender}")
            print(f"个人简介: {user.bio}")
            
            # 3. 使用schema序列化
            print("\n=== Schema序列化 ===")
            user_data = UserSchema.model_validate(user)
            print(f"序列化结果: {user_data.model_dump()}")
            
            # 4. 检查具体字段
            print("\n=== 检查序列化后的字段 ===")
            dumped = user_data.model_dump()
            for field in ['username', 'email', 'phone', 'school', 'major', 'gender', 'bio']:
                value = dumped.get(field, 'NOT_FOUND')
                print(f"{field}: {value}")
                
        except Exception as e:
            print(f"错误: {e}")
            import traceback
            traceback.print_exc()
        finally:
            await db.close()
            break

if __name__ == "__main__":
    print("测试User schema序列化...")
    asyncio.run(test_schema())
