"""
Test 1: Store and retrieve Gmail credentials

Demonstrates:
- Initialize vault
- Store multiple credentials
- Retrieve credentials
- List credentials
- Delete credentials
"""

import os
import sys
import tempfile
import shutil

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

# Use temp vault directory
temp_dir = tempfile.mkdtemp()
os.environ["VAULT_DIR"] = temp_dir
os.environ["VAULT_AUDIT_LOG_DIR"] = temp_dir

from secure_vault import SecureVault


def test_gmail_credentials():
    """Test storing Gmail credentials"""
    
    print("=== Test: Gmail Credentials ===\n")
    
    # Initialize vault
    print("1. Initializing vault...")
    vault = SecureVault()
    result = vault.init_vault("my-secure-master-password")
    print(f"   Vault initialized: {result['status']}")
    
    # Store Gmail credentials
    print("\n2. Storing Gmail credentials...")
    
    vault.store(
        agent_id="sofiia",
        service="gmail",
        credential_name="password",
        value="your-gmail-password"
    )
    print("   - Stored password")
    
    vault.store(
        agent_id="sofiia",
        service="gmail",
        credential_name="oauth_token",
        value={"access_token": "ya29.xxxx", "refresh_token": "1//xxx"}
    )
    print("   - Stored OAuth token")
    
    vault.store(
        agent_id="sofiia",
        service="gmail",
        credential_name="app_password",
        value="xxxx xxxx xxxx xxxx",
        ttl_seconds=3600  # 1 hour
    )
    print("   - Stored app password (TTL: 1 hour)")
    
    # List services
    print("\n3. Listing services...")
    services = vault.list("sofiia")
    print(f"   Services: {services}")
    
    # List credentials
    print("\n4. Listing credentials for gmail...")
    creds = vault.list("sofiia", "gmail")
    print(f"   Credentials: {creds}")
    
    # Retrieve password
    print("\n5. Retrieving password...")
    password = vault.get("sofiia", "gmail", "password")
    print(f"   Password retrieved: {password is not None}")
    
    # Retrieve OAuth token
    print("\n6. Retrieving OAuth token...")
    token = vault.get("sofiia", "gmail", "oauth_token")
    print(f"   Token type: {type(token)}")
    print(f"   Has access_token: {'access_token' in token}")
    
    # Delete credential
    print("\n7. Deleting app_password...")
    result = vault.delete("sofiia", "gmail", "app_password")
    print(f"   Status: {result['status']}")
    
    # Verify deletion
    creds = vault.list("sofiia", "gmail")
    print(f"   Remaining: {creds}")
    
    # Clean up
    shutil.rmtree(temp_dir)
    
    print("\n✅ Gmail credentials test passed!")
    return True


if __name__ == "__main__":
    test_gmail_credentials()
