#!/usr/bin/env python3
"""Test script for API key endpoints"""

import sys
sys.path.insert(0, '/home/nextime/mbetterc')

from mbetterclient.web_dashboard.auth import AuthManager
from mbetterclient.database.manager import DatabaseManager
from mbetterclient.config.manager import ConfigManager
from flask import Flask
import requests

# Initialize database manager
config_manager = ConfigManager()
db_manager = DatabaseManager(config_manager)

# Initialize auth manager
app = Flask(__name__)
app.config['JWT_SECRET_KEY'] = 'test_secret_key'
app.config['PERMANENT_SESSION_LIFETIME'] = 3600
auth_manager = AuthManager(db_manager, app)

# Create a test broker user if it doesn't exist
test_user = db_manager.get_user_by_username('test_broker')
if not test_user:
    from mbetterclient.database.models import UserModel
    user = UserModel(
        username='test_broker',
        email='test_broker@example.com',
        password_hash=auth_manager.hash_password('test_password'),
        is_admin=False,
        role='broker'
    )
    db_manager.save_user(user)
    test_user = db_manager.get_user_by_username('test_broker')

# Create a JWT token for the test user
token = auth_manager.create_jwt_token(test_user.id)
if hasattr(token, 'decode'):
    token = token.decode('utf-8')

print(f"Generated JWT token: {token}")

# Test the API key endpoints
base_url = 'http://localhost:5001/api'
headers = {'Authorization': f'Bearer {token}'}

print("\n1. Testing GET /api/broker/api-key")
try:
    response = requests.get(f"{base_url}/broker/api-key", headers=headers)
    print(f"Status code: {response.status_code}")
    print(f"Response: {response.json()}")
except Exception as e:
    print(f"Error: {e}")

print("\n2. Testing POST /api/broker/regenerate-api-key")
try:
    response = requests.post(f"{base_url}/broker/regenerate-api-key", headers=headers)
    print(f"Status code: {response.status_code}")
    print(f"Response: {response.json()}")
except Exception as e:
    print(f"Error: {e}")

print("\n3. Testing GET /api/broker/api-keys")
try:
    response = requests.get(f"{base_url}/broker/api-keys", headers=headers)
    print(f"Status code: {response.status_code}")
    print(f"Response: {response.json()}")
except Exception as e:
    print(f"Error: {e}")

print("\n4. Testing POST /api/broker/api-keys")
try:
    response = requests.post(f"{base_url}/broker/api-keys", headers=headers, json={
        'name': 'Test API Key',
        'expires_days': 30
    })
    print(f"Status code: {response.status_code}")
    print(f"Response: {response.json()}")
except Exception as e:
    print(f"Error: {e}")