#!/usr/bin/env python3
"""Simple test server to isolate the login issue."""

from fastapi import FastAPI, Response
from motor.motor_asyncio import AsyncIOMotorClient
from app.core.config import settings
from app.core.security import verify_password, create_access_token, create_refresh_token
from app.models.user import User
from app.schemas.auth import LoginRequest, LoginResponse

app = FastAPI()

@app.post("/test-login")
async def test_login(login_data: LoginRequest, response: Response):
    print(f"1. Received login request for: {login_data.email}")
    
    # Create database connection directly
    client = AsyncIOMotorClient(settings.mongodb_uri)
    db = client[settings.mongodb_db]
    
    try:
        print("2. Connecting to database...")
        # Find user by email
        user_doc = await db.users.find_one({"email": login_data.email})
        print(f"3. User lookup result: {user_doc is not None}")
        
        if not user_doc:
            print("4. User not found")
            return {"error": "User not found"}

        user = User(**user_doc)
        print(f"5. User model created: {user.email}")

        # Verify password
        print("6. Verifying password...")
        password_valid = verify_password(login_data.password, user.hashed_password)
        print(f"7. Password valid: {password_valid}")
        
        if not password_valid:
            print("8. Password invalid")
            return {"error": "Invalid password"}

        if not user.is_active:
            print("9. User inactive")
            return {"error": "User inactive"}

        print("10. Creating tokens...")
        # Create tokens
        access_token = create_access_token(subject=str(user.id))
        refresh_token = create_refresh_token(subject=str(user.id))
        print("11. Tokens created successfully")

        # Set refresh token as HttpOnly cookie
        response.set_cookie(
            key="refresh_token",
            value=refresh_token,
            httponly=True,
            secure=settings.cookie_secure,
            samesite=settings.cookie_samesite,
            domain=settings.cookie_domain if settings.app_env == "prod" else None,
            max_age=settings.jwt_refresh_ttl_days * 24 * 60 * 60,
        )
        print("12. Cookie set")

        result = LoginResponse(
            access_token=access_token,
            user_id=str(user.id),
            role=user.role.value,
        )
        print("13. Response prepared")
        return result
    
    except Exception as e:
        print(f"ERROR: {e}")
        import traceback
        traceback.print_exc()
        return {"error": str(e)}
    
    finally:
        print("14. Closing database connection")
        client.close()

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8002)