#!/usr/bin/env python3
"""
调试API问题
"""
import asyncio
import os
import sys
from pathlib import Path

# 设置环境变量
os.environ["DATABASE_URL"] = "mysql+aiomysql://root:root@localhost:3306/kaopeilian"
os.environ["SECRET_KEY"] = "dev-secret-key-for-testing-only-not-for-production"

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

async def debug_login():
    """调试登录问题"""
    try:
        # 导入所有必要的模块
        from app.config.database import AsyncSessionLocal
        from app.services.auth_service import AuthService
        from app.schemas.auth import UserLogin, Token
        from app.schemas.base import ResponseModel
        from app.core.exceptions import BaseError
        from app.core.logger import logger
        from fastapi import HTTPException, status
        
        print("🔍 开始调试登录流程...")
        
        # 创建登录数据
        login_data = UserLogin(username="testuser", password="TestPass123!")
        print(f"📝 登录数据: {login_data}")
        
        async with AsyncSessionLocal() as db:
            try:
                print("🔐 开始认证...")
                auth_service = AuthService(db)
                
                # 验证用户
                user = await auth_service.authenticate_user(
                    username=login_data.username,
                    password=login_data.password
                )
                print(f"✅ 用户认证成功: {user.username}")
                
                # 创建tokens
                tokens = await auth_service.create_tokens_for_user(user)
                print(f"✅ Token创建成功")
                
                # 创建响应
                response = ResponseModel(data=tokens)
                print(f"✅ 响应创建成功: {response}")
                
                return response
                
            except BaseError as e:
                print(f"❌ 业务错误: {e}")
                raise HTTPException(
                    status_code=e.code,
                    detail={
                        "message": e.message,
                        "error_code": e.error_code
                    }
                )
            except Exception as e:
                print(f"❌ 系统错误: {e}")
                import traceback
                traceback.print_exc()
                raise HTTPException(
                    status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                    detail={"message": "登录失败，请稍后重试"}
                )
                
    except Exception as e:
        print(f"❌ 调试失败: {e}")
        import traceback
        traceback.print_exc()

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