#!/usr/bin/env python3

import json
import requests
import time

def test_registration_and_login():
    """Test registration and login flow"""
    base_url = "http://localhost:8000"
    
    # Test user data
    test_user = {
        "email": "testuser@example.com",
        "username": "testuser123",
        "password": "SecurePass123",
        "first_name": "Test",
        "last_name": "User"
    }
    
    print("🔧 Creating test user")
    print("=" * 50)
    
    # Try to register the user
    try:
        headers = {
            "Content-Type": "application/json",
            "Accept": "application/json"
        }
        
        print(f"Registering user: {test_user['email']}")
        
        registration_response = requests.post(
            f"{base_url}/api/v1/auth/register",
            json=test_user,
            headers=headers,
            timeout=10
        )
        
        print(f"Registration Status: {registration_response.status_code}")
        print(f"Registration Response: {registration_response.text}")
        
        if registration_response.status_code == 200:
            print("✅ User registered successfully")
        elif registration_response.status_code == 400:
            if "already registered" in registration_response.text.lower():
                print("ℹ️  User already exists, proceeding with login test")
            else:
                print(f"❌ Registration failed: {registration_response.text}")
                return
        else:
            print(f"❌ Registration failed with status: {registration_response.status_code}")
            return
        
        time.sleep(1)
        
        # Test login scenarios
        login_tests = [
            {
                "name": "Login with email",
                "data": {
                    "email": test_user["email"],
                    "password": test_user["password"]
                }
            },
            {
                "name": "Login with username",
                "data": {
                    "username": test_user["username"],
                    "password": test_user["password"]
                }
            },
            {
                "name": "Login with wrong password",
                "data": {
                    "email": test_user["email"],
                    "password": "wrongpassword"
                }
            }
        ]
        
        for test in login_tests:
            print(f"\n🧪 Testing: {test['name']}")
            print("=" * 50)
            
            try:
                print(f"Login data: {json.dumps(test['data'], indent=2)}")
                
                login_response = requests.post(
                    f"{base_url}/api/v1/auth/login",
                    json=test["data"],
                    headers=headers,
                    timeout=10
                )
                
                print(f"Login Status: {login_response.status_code}")
                print(f"Login Response: {login_response.text}")
                
                if login_response.status_code == 200:
                    try:
                        token_data = login_response.json()
                        print(f"✅ Login successful! Token type: {token_data.get('token_type')}")
                        print(f"Access token (first 20 chars): {token_data.get('access_token', '')[:20]}...")
                    except:
                        print("✅ Login successful but response parsing failed")
                else:
                    print(f"❌ Login failed")
                
            except Exception as e:
                print(f"Login error: {str(e)}")
            
            time.sleep(1)
        
    except Exception as e:
        print(f"Test error: {str(e)}")

if __name__ == "__main__":
    print("🔍 Testing registration and login flow")
    test_registration_and_login()