"""
Simple test script to verify API key model functionality
"""

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

from mbetterclient.database.models import ApiKeyModel
from datetime import datetime, timedelta

def test_api_key_model():
    """Test API key model functions directly"""
    print("Testing API key model functions...")
    
    # Test 1: Generate API key
    print("\n1. Testing API key generation...")
    api_key = ApiKeyModel.generate_api_key()
    print(f"✅ Generated API key: {api_key}")
    print(f"   Length: {len(api_key)} characters")
    
    # Test 2: Hash API key
    print("\n2. Testing API key hashing...")
    key_hash = ApiKeyModel.hash_key(api_key)
    print(f"✅ Hashed API key: {key_hash}")
    
    # Test 3: Verify API key
    print("\n3. Testing API key verification...")
    is_valid = ApiKeyModel.verify_key(api_key, key_hash)
    print(f"✅ Verification with correct key: {is_valid}")
    
    # Test verification with incorrect key
    wrong_key = ApiKeyModel.generate_api_key()
    is_valid = ApiKeyModel.verify_key(wrong_key, key_hash)
    print(f"✅ Verification with incorrect key: {is_valid}")
    
    # Test 4: API key expiration
    print("\n4. Testing API key expiration...")
    # Create a key that expired yesterday
    expired_key = ApiKeyModel(
        user_id=1,
        name="Expired Key",
        key_hash=key_hash,
        is_active=True,
        expires_at=datetime.utcnow() - timedelta(days=1)
    )
    
    is_expired = expired_key.is_expired()
    is_valid = expired_key.is_valid()
    
    print(f"✅ Expired key check: {is_expired}")
    print(f"✅ Valid key check (expired): {is_valid}")
    
    # Create a key that expires in 30 days
    valid_key = ApiKeyModel(
        user_id=1,
        name="Valid Key",
        key_hash=key_hash,
        is_active=True,
        expires_at=datetime.utcnow() + timedelta(days=30)
    )
    
    is_expired = valid_key.is_expired()
    is_valid = valid_key.is_valid()
    
    print(f"✅ Expired key check (valid): {is_expired}")
    print(f"✅ Valid key check (valid): {is_valid}")
    
    # Test 5: Revoke API key
    print("\n5. Testing API key revocation...")
    valid_key.revoke()
    print(f"✅ Key active status after revocation: {valid_key.is_active}")
    print(f"✅ Valid key check (revoked): {valid_key.is_valid()}")
    
    # Test 6: Extend expiration
    print("\n6. Testing expiration extension...")
    original_expiry = valid_key.expires_at
    valid_key.extend_expiration(365)  # Extend by 1 year
    print(f"✅ Expiration extended from {original_expiry.date()} to {valid_key.expires_at.date()}")
    
    print("\n✅ All API key model tests passed!")
    return True


if __name__ == "__main__":
    try:
        success = test_api_key_model()
        sys.exit(0 if success else 1)
    except Exception as e:
        print(f"❌ Test failed: {e}")
        import traceback
        print(traceback.format_exc())
        sys.exit(1)