"""
Test script to verify API key management functionality
"""

import sys
import os
sys.path.insert(0, os.path.abspath('.'))

from mbetterclient.database.manager import DatabaseManager
from mbetterclient.database.models import ApiKeyModel, UserModel
from datetime import datetime, timedelta
from sqlalchemy.exc import SQLAlchemyError

def test_api_key_management():
    """Test API key management functions"""
    print("Testing API key management system...")
    
    # Initialize database manager
    db_manager = DatabaseManager('test_api_keys.db')
    if not db_manager.initialize():
        print("❌ Failed to initialize database manager")
        return False
    
    try:
        # Create a test broker user if not exists
        session = db_manager.get_session()
        test_user = session.query(UserModel).filter_by(username='test_broker').first()
        
        if not test_user:
            print("Creating test broker user...")
            test_user = UserModel(
                username='test_broker',
                email='test_broker@example.com',
                is_admin=False
            )
            test_user.set_password('test123')
            if hasattr(test_user, 'set_role'):
                test_user.set_role('broker')
            elif hasattr(test_user, 'role'):
                test_user.role = 'broker'
            session.add(test_user)
            session.commit()
            session.refresh(test_user)
        
        print(f"✅ Test broker user created/retrieved: ID={test_user.id}, Username={test_user.username}, Role={test_user.role}")
        
        # Test 1: Create API key
        print("\n1. Testing API key creation...")
        test_key = ApiKeyModel(
            user_id=test_user.id,
            name="Test API Key",
            key_hash=ApiKeyModel.hash_key(ApiKeyModel.generate_api_key()),
            is_active=True,
            expires_at=datetime.utcnow() + timedelta(days=365)
        )
        session.add(test_key)
        session.commit()
        session.refresh(test_key)
        
        print(f"✅ API key created: ID={test_key.id}, Name={test_key.name}")
        
        # Test 2: Get API key by hash
        print("\n2. Testing API key retrieval by hash...")
        retrieved_key = session.query(ApiKeyModel).filter_by(key_hash=test_key.key_hash).first()
        
        if retrieved_key:
            print(f"✅ API key retrieved by hash: ID={retrieved_key.id}, Name={retrieved_key.name}")
        else:
            print("❌ API key not found by hash")
        
        # Test 3: Get user's API keys
        print("\n3. Testing user API keys retrieval...")
        user_keys = session.query(ApiKeyModel).filter_by(user_id=test_user.id).all()
        
        print(f"✅ Found {len(user_keys)} API keys for user {test_user.username}")
        for key in user_keys:
            print(f"  - ID: {key.id}, Name: {key.name}, Active: {key.is_active}")
        
        # Test 4: Revoke API key
        print("\n4. Testing API key revocation...")
        test_key.is_active = False
        session.commit()
        
        revoked_key = session.query(ApiKeyModel).get(test_key.id)
        if not revoked_key.is_active:
            print(f"✅ API key {revoked_key.id} revoked successfully")
        else:
            print("❌ API key revocation failed")
        
        # Clean up
        print("\nCleaning up test data...")
        session.delete(test_key)
        session.delete(test_user)
        session.commit()
        
        print("✅ All tests passed!")
        return True
        
    except SQLAlchemyError as e:
        print(f"❌ Database error: {e}")
        session.rollback()
        return False
    except Exception as e:
        print(f"❌ Unexpected error: {e}")
        import traceback
        print(traceback.format_exc())
        return False
    finally:
        session.close()
        db_manager.close()
        
        # Cleanup test database file
        if os.path.exists('test_api_keys.db'):
            try:
                os.remove('test_api_keys.db')
            except:
                pass


if __name__ == "__main__":
    success = test_api_key_management()
    sys.exit(0 if success else 1)