#!/usr/bin/env python3
"""
Test script to demonstrate admin API key management functionality.
This script shows how admins can create and manage API keys for other users.
"""

import requests
import json
from datetime import datetime, timedelta

# Configuration
BASE_URL = "http://localhost:8000"
ADMIN_EMAIL = "admin@example.com"
ADMIN_PASSWORD = "admin123"

def login_as_admin():
    """Login as admin and get access token."""
    response = requests.post(f"{BASE_URL}/auth/login", json={
        "email": ADMIN_EMAIL,
        "password": ADMIN_PASSWORD
    })
    
    if response.status_code == 200:
        tokens = response.json()
        return tokens["access_token"]
    else:
        print(f"Login failed: {response.status_code} - {response.text}")
        return None

def create_api_key_for_user(token, user_id, name, scopes):
    """Create an API key for a specific user (admin only)."""
    headers = {"Authorization": f"Bearer {token}"}
    
    # Method 1: Using the general endpoint with user_id parameter
    response = requests.post(f"{BASE_URL}/auth/api-keys", 
        headers=headers,
        json={
            "name": name,
            "scopes": scopes,
            "user_id": user_id,
            "expires_at": (datetime.utcnow() + timedelta(days=30)).isoformat()
        }
    )
    
    if response.status_code == 200:
        result = response.json()
        print(f"✅ Created API key for user {user_id}:")
        print(f"   Name: {result['api_key']['name']}")
        print(f"   Token: {result['token']}")
        print(f"   Scopes: {result['api_key']['scopes']}")
        return result
    else:
        print(f"❌ Failed to create API key: {response.status_code} - {response.text}")
        return None

def list_all_api_keys(token):
    """List all API keys (admin only)."""
    headers = {"Authorization": f"Bearer {token}"}
    
    response = requests.get(f"{BASE_URL}/auth/api-keys", headers=headers)
    
    if response.status_code == 200:
        api_keys = response.json()
        print(f"📋 Found {len(api_keys)} API keys:")
        for key in api_keys:
            print(f"   ID: {key['id']}, User: {key['user_email']}, Name: {key['name']}")
        return api_keys
    else:
        print(f"❌ Failed to list API keys: {response.status_code} - {response.text}")
        return []

def list_user_api_keys(token, user_id):
    """List API keys for a specific user (admin only)."""
    headers = {"Authorization": f"Bearer {token}"}
    
    response = requests.get(f"{BASE_URL}/auth/admin/users/{user_id}/api-keys", headers=headers)
    
    if response.status_code == 200:
        api_keys = response.json()
        print(f"📋 User {user_id} has {len(api_keys)} API keys:")
        for key in api_keys:
            print(f"   ID: {key['id']}, Name: {key['name']}, Active: {key['is_active']}")
        return api_keys
    else:
        print(f"❌ Failed to list user API keys: {response.status_code} - {response.text}")
        return []

def main():
    """Main test function."""
    print("🔧 Testing Admin API Key Management")
    print("=" * 50)
    
    # Login as admin
    print("1. Logging in as admin...")
    token = login_as_admin()
    if not token:
        print("❌ Cannot proceed without admin token")
        return
    
    print("✅ Admin login successful")
    
    # Example: Create API key for user ID 2 (assuming this user exists)
    print("\n2. Creating API key for user ID 2...")
    api_key_result = create_api_key_for_user(
        token=token,
        user_id=2,
        name="Developer Integration Key",
        scopes=["read:projects", "read:tasks", "read:submissions"]
    )
    
    # List all API keys
    print("\n3. Listing all API keys...")
    all_keys = list_all_api_keys(token)
    
    # List API keys for specific user
    print("\n4. Listing API keys for user ID 2...")
    user_keys = list_user_api_keys(token, 2)
    
    print("\n✅ Admin API key management test completed!")
    print("\nKey Features Demonstrated:")
    print("- ✅ Admin can create API keys for any user")
    print("- ✅ Admin can view all API keys in the system")
    print("- ✅ Admin can view API keys for specific users")
    print("- ✅ API keys include user email for admin visibility")

if __name__ == "__main__":
    main()