import sys
import traceback
from app.core.database import SessionLocal
from app.services.user_service import UserService
from app.schemas.auth import UserRegister

def debug_email_duplicate():
    """调试邮箱重复问题"""
    try:
        print("=== 调试邮箱重复问题 ===")

        db = SessionLocal()
        user_service = UserService(db)

        # 先检查现有用户
        print("1. 检查现有用户...")
        existing_user = user_service.get_user_by_email("user@example.com")
        if existing_user:
            print(f"   找到现有用户: ID={existing_user.id}, 用户名={existing_user.username}, 邮箱={existing_user.email}")
        else:
            print("   未找到现有用户")

        # 尝试创建重复邮箱的用户
        print("\n2. 尝试创建重复邮箱的用户...")
        user_data = UserRegister(
            username="test_duplicate",
            email="user@example.com",  # 重复邮箱
            password="TestPass123!",
            confirm_password="TestPass123!"
        )

        try:
            user = user_service.create_user(user_data)
            print(f"   用户创建成功: {user.id}")
        except Exception as e:
            print(f"   用户创建失败: {e}")
            print(f"   异常类型: {type(e).__name__}")
            print(f"   异常详情: {e.detail if hasattr(e, 'detail') else '无详情'}")
            traceback.print_exc()

        db.close()

    except Exception as e:
        print(f"调试过程出错: {e}")
        traceback.print_exc()

if __name__ == "__main__":
    debug_email_duplicate()