"""Test script for broker API key functionality"""

import requests
import json

BASE_URL = "http://localhost:5001"

def create_broker_user():
    """Create a broker user via API"""
    url = f"{BASE_URL}/api/signup"
    data = {
        "username": "testbroker",
        "email": "broker@test.com",
        "password": "password123",
        "role": "broker"
    }
    
    try:
        response = requests.post(url, json=data)
        print(f"Create broker user - Status: {response.status_code}")
        print(f"Response: {response.text}")
        
        if response.status_code == 201:
            print("Broker user created successfully")
            return True
        elif response.status_code == 400:
            print("Broker user already exists")
            return True
        else:
            print(f"Failed to create broker user: {response.status_code}")
            return False
    except Exception as e:
        print(f"Error creating broker user: {e}")
        return False

def login_broker():
    """Login as broker to get JWT token"""
    url = f"{BASE_URL}/api/auth/login"
    data = {
        "username": "testbroker",
        "password": "password123"
    }
    
    try:
        response = requests.post(url, json=data)
        print(f"Login - Status: {response.status_code}")
        print(f"Response: {response.text}")
        
        if response.status_code == 200:
            result = response.json()
            token = result.get("access_token")
            print(f"Login successful - Token: {token}")
            return token
        else:
            print(f"Login failed: {response.status_code}")
            return None
    except Exception as e:
        print(f"Error logging in: {e}")
        return None

def get_broker_api_key(token):
    """Get broker API key using JWT token"""
    url = f"{BASE_URL}/api/broker/api-key"
    headers = {
        "Authorization": f"Bearer {token}"
    }
    
    try:
        response = requests.get(url, headers=headers)
        print(f"Get API key - Status: {response.status_code}")
        print(f"Response: {response.text}")
        
        if response.status_code == 200:
            result = response.json()
            if result.get("success"):
                api_key = result.get("api_key")
                print(f"API key obtained: {api_key}")
                return api_key
            else:
                print(f"API key request failed: {result.get('error')}")
                return None
        else:
            print(f"Failed to get API key: {response.status_code}")
            return None
    except Exception as e:
        print(f"Error getting API key: {e}")
        return None

def regenerate_broker_api_key(token):
    """Regenerate broker API key"""
    url = f"{BASE_URL}/api/broker/regenerate-api-key"
    headers = {
        "Authorization": f"Bearer {token}"
    }
    
    try:
        response = requests.post(url, headers=headers)
        print(f"Regenerate API key - Status: {response.status_code}")
        print(f"Response: {response.text}")
        
        if response.status_code == 200:
            result = response.json()
            if result.get("success"):
                api_key = result.get("api_key")
                print(f"API key regenerated: {api_key}")
                return api_key
            else:
                print(f"API key regeneration failed: {result.get('error')}")
                return None
        else:
            print(f"Failed to regenerate API key: {response.status_code}")
            return None
    except Exception as e:
        print(f"Error regenerating API key: {e}")
        return None

def test_api_key_endpoints():
    """Main test function for API key endpoints"""
    print("=== Testing Broker API Key Functionality ===\n")
    
    # Step 1: Create broker user (if not exists)
    if not create_broker_user():
        print("\nTest failed - Could not create broker user")
        return False
    
    # Step 2: Login to get token
    token = login_broker()
    if not token:
        print("\nTest failed - Could not login")
        return False
    
    # Step 3: Get API key
    print("\n=== Getting API Key ===")
    api_key = get_broker_api_key(token)
    if not api_key:
        print("\nTest failed - Could not get API key")
        return False
    
    # Step 4: Regenerate API key
    print("\n=== Regenerating API Key ===")
    new_api_key = regenerate_broker_api_key(token)
    if not new_api_key:
        print("\nTest failed - Could not regenerate API key")
        return False
    
    print("\n=== All Tests Passed ===")
    print(f"Original API Key: {api_key}")
    print(f"New API Key: {new_api_key}")
    
    return True

if __name__ == "__main__":
    test_api_key_endpoints()