#!/usr/bin/env python3
"""
Register test user for WebSocket testing
"""

import asyncio
import sys

try:
    import httpx
except ImportError:
    import subprocess
    subprocess.check_call([sys.executable, "-m", "pip", "install", "httpx"])
    import httpx

async def register_test_user():
    """Register a test user"""
    
    test_email = "wstester@test.com"
    test_password = "WsTest1234!"
    
    print(f"📝 Registering test user...")
    print(f"   Email: {test_email}")
    print(f"   Password: {test_password}\n")
    
    try:
        async with httpx.AsyncClient() as client:
            # Register
            response = await client.post(
                "http://localhost:8001/api/v1/auth/register",
                json={
                    "email": test_email,
                    "password": test_password,
                    "first_name": "WS",
                    "last_name": "Tester",
                    "username": "wstester"
                },
                timeout=10.0
            )
            
            print(f"Register Status: {response.status_code}")
            if response.status_code not in (200, 201):
                print(f"Response: {response.text}")
                print("⚠️  User might already exist, trying to login...\n")
            else:
                print(f"✅ User registered successfully\n")
            
            # Now login
            print("🔐 Getting JWT token...")
            response = await client.post(
                "http://localhost:8001/api/v1/auth/login",
                json={
                    "email": test_email,
                    "password": test_password
                },
                timeout=10.0
            )
            
            print(f"Login Status: {response.status_code}")
            
            if response.status_code != 200:
                print(f"Response: {response.text}")
                return False
            
            data = response.json()
            token = data.get("access_token")
            
            # Decode token to get user_id
            import base64
            parts = token.split('.')
            if len(parts) == 3:
                payload = parts[1]
                # Add padding if needed
                padding = 4 - len(payload) % 4
                if padding != 4:
                    payload += '=' * padding
                decoded = base64.urlsafe_b64decode(payload)
                import json
                token_data = json.loads(decoded)
                user_id = token_data.get("sub")
            else:
                user_id = None
            
            print(f"✅ JWT token obtained!")
            print(f"\n📋 WebSocket Connection Details:")
            print(f"   User ID: {user_id}")
            print(f"   Token: {token[:50]}...")
            print(f"\n   WebSocket URL:")
            print(f"   ws://localhost:8002/api/v1/emergency/ws/{user_id}?token={token}")
            
            return True
            
    except Exception as e:
        print(f"❌ Error: {e}")
        return False

if __name__ == "__main__":
    try:
        result = asyncio.run(register_test_user())
        sys.exit(0 if result else 1)
    except KeyboardInterrupt:
        print("\n⚠️  Interrupted by user")
        sys.exit(1)
