import sys
import traceback
from app.core.database import SessionLocal
from app.core.security import get_password_hash
from app.models.user import User

def debug_password_hashing():
    """测试密码哈希功能"""
    try:
        print("测试密码哈希功能...")
        password = "Stringst1@"
        hashed = get_password_hash(password)
        print(f"密码哈希成功: {hashed[:50]}...")
        return True
    except Exception as e:
        print(f"密码哈希失败: {str(e)}")
        traceback.print_exc()
        return False

def debug_user_creation():
    """测试用户创建"""
    try:
        print("\n测试用户创建...")

        db = SessionLocal()

        # 检查用户是否已存在
        existing_user = db.query(User).filter(User.username == "peng").first()
        if existing_user:
            print("用户 'peng' 已存在，删除旧记录...")
            db.delete(existing_user)
            db.commit()

        # 创建新用户
        password_hash = get_password_hash("Stringst1@")
        print(f"密码哈希生成成功")

        new_user = User(
            username="peng",
            email="user@example.com",
            password_hash=password_hash,
            is_active=True,
            is_verified=False
        )

        db.add(new_user)
        db.commit()
        db.refresh(new_user)

        print(f"用户创建成功! ID: {new_user.id}")

        # 验证用户
        user = db.query(User).filter(User.username == "peng").first()
        if user:
            print(f"用户验证成功: {user.username}, {user.email}")

        db.close()
        return True

    except Exception as e:
        print(f"用户创建失败: {str(e)}")
        traceback.print_exc()
        return False

if __name__ == "__main__":
    print("=== 调试用户注册问题 ===")

    # 测试密码哈希
    if not debug_password_hashing():
        print("密码哈希有问题，退出")
        sys.exit(1)

    # 测试用户创建
    if not debug_user_creation():
        print("用户创建有问题，退出")
        sys.exit(1)

    print("\n=== 调试完成，一切正常 ===")