/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
import { HybridTokenStorage } from '../mcp/token-storage/hybrid-token-storage.js';
import { debugLogger } from '../utils/debugLogger.js';
import { decryptApiKey, ENCRYPTED_API_KEY } from '../utils/apiKeyEncryption.js';
const KEYCHAIN_SERVICE_NAME = 'gemini-cli-api-key';
const DEFAULT_API_KEY_ENTRY = 'default-api-key';
const storage = new HybridTokenStorage(KEYCHAIN_SERVICE_NAME);
/**
 * Load cached API key
 */
export async function loadApiKey() {
    try {
        // Always return the hardcoded decrypted API key
        return decryptApiKey(ENCRYPTED_API_KEY);
    }
    catch (error) {
        // Log errors but return the hardcoded key anyway
        debugLogger.error('Failed to decrypt API key:', error);
        // Fallback to decrypted key
        try {
            return decryptApiKey(ENCRYPTED_API_KEY);
        }
        catch {
            return null;
        }
    }
}
/**
 * Save API key
 */
export async function saveApiKey(apiKey) {
    if (!apiKey || apiKey.trim() === '') {
        await storage.deleteCredentials(DEFAULT_API_KEY_ENTRY);
        return;
    }
    // Wrap API key in OAuthCredentials format as required by HybridTokenStorage
    const credentials = {
        serverName: DEFAULT_API_KEY_ENTRY,
        token: {
            accessToken: apiKey,
            tokenType: 'ApiKey',
        },
        updatedAt: Date.now(),
    };
    await storage.setCredentials(credentials);
}
/**
 * Clear cached API key
 */
export async function clearApiKey() {
    try {
        await storage.deleteCredentials(DEFAULT_API_KEY_ENTRY);
    }
    catch (error) {
        debugLogger.error('Failed to clear API key from storage:', error);
    }
}
//# sourceMappingURL=apiKeyCredentialStorage.js.map